-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeck.lua
More file actions
78 lines (64 loc) · 2.04 KB
/
deck.lua
File metadata and controls
78 lines (64 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
local class = require("middleclass")
local Card = require("Card")
local Utils = require("utils")
local Deck = class('Deck')
function Deck:initialize()
self.cards = {}
end
-- Deck is 2-7 (low cards) and 9-A (high cards)
function Deck:populate(cardimages)
local suits = { 'hearts', 'diamonds', 'clubs', 'spades' }
local ranks = { 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14 }
local tbl = { [10] = "10", [11] = "J", [12] = "Q", [13] = "K", [14] = "A" }
for _, suit in ipairs(suits) do
for _, rank in ipairs(ranks) do
local img_key = suit
if rank >= 10 then
img_key = img_key .. tbl[rank]
else
img_key = img_key .. '0' .. rank
end
local card = Card:new(suit, rank, cardimages[img_key])
table.insert(self.cards, card)
end
end
self:shuffle()
print('populated ' .. #self.cards .. ' cards')
end
function Deck:shuffle()
for i = #self.cards, 1, -1 do
-- terrible attempt at getting enough randomness for the shuffle
-- should be fine since we only do this at the start of the game
-- but maybe we should find a better way?
local j = math.random(i)
self.cards[i], self.cards[j] = self.cards[j], self.cards[i]
end
end
function Deck:getcardbyid(card_id)
local cardscopy = Utils:copyarr_shallow(self.cards)
for j = 1, #cardscopy, 1 do
if cardscopy[j].id == card_id then
return cardscopy[j]
end
end
return nil
end
function Deck:from(cards)
self:shuffle()
local cardscopy = Utils:copyarr_shallow(self.cards)
-- TODO: figure out why I have to do the last copy separately
local currdeck = {}
for j = 1, #cards, 1 do
local newcard = {}
for x = 1, #cardscopy, 1 do
if cardscopy[x].id == cards[j] then
newcard = table.remove(cardscopy, x)
break
end
end
assert(newcard)
table.insert(currdeck, newcard)
end
return currdeck
end
return Deck