I have some code for a simple playing card type:
type
Face = enum
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
Suit = enum
Heart,
Club,
Spade,
Diamond
Card = object
suit: Suit
face: Face
and now I'd like to say something like
let
deck = [] of Card
for s in Suit.fields:
for f in Face.fields:
deck.append(Card(suit: s, face: f))
and I'm not understanding how that can be done. Perhaps this is a wildly ignorant question, I am new to static typed languages for the most part.
Thanks in advance.
Hello! It's really simple, enums without holes have an items iterator defined (so you can iterate over them), and deck can be made via a sequence:
type
Face = enum
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
Suit = enum
Heart,
Club,
Spade,
Diamond
Card = object
suit: Suit
face: Face
var deck: seq[Card]
for s in Suit:
for f in Face:
deck.add(Card(suit: s, face: f))
you might wanna start with the basics
https://nim-lang.org/docs/tut1.html
var deck: seq[Card]
for s in Suit:
for f in Face:
deck.add(Card(suit: s, face: f))
I did not expect such quick responses!
I should've started at the tutorial indeed. I really appreciate the help. I guess I'll work my way through that now.
Thank yall very much for responding, early on a Sunday morning no less! :)
@haydenjones you can also calculate the whole deck at compile-time so you won't need to spend time at runtime:
type
Face = enum
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
Suit = enum
Heart,
Club,
Spade,
Diamond
Card = object
suit: Suit
face: Face
proc len[T: enum](x: typedesc[T]): int =
result = len(T.low .. T.high)
const deck = static:
# var res: array[52, Card]
var res: array[len(Face) * len(Suit), Card]
var i = 0
for s in Suit:
for f in Face:
res[i] = Card(suit: s, face: f)
res
echo deck
You forgot to increment index i. The last block needs it
const deck = static:
# var res: array[52, Card]
var res: array[len(Face) * len(Suit), Card]
var i = 0
for s in Suit:
for f in Face:
res[i] = Card(suit: s, face: f)
inc i
res