Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Got a card of Rank = 0, is that right? #1

Open
dcu opened this issue Aug 3, 2019 · 3 comments
Open

Got a card of Rank = 0, is that right? #1

dcu opened this issue Aug 3, 2019 · 3 comments

Comments

@dcu
Copy link

dcu commented Aug 3, 2019

No description provided.

@preslavmihaylov
Copy link
Owner

preslavmihaylov commented Aug 3, 2019

Card of Rank 0 is Ace.

decks/deck.go

Line 29 in 9e34f47

const (

Note that the ranks do not necessarily correspond to the values of a card - e.g. 1 for Ace, as those are different for every game.

If you want to add values to a card, I suggest writing a custom function in your own package. Something like valueOf(c decks.Card).

And if you want to check whether a card you got is of a certain rank, you can do:

if (c.Rank == decks.Ace) {
    // handle Ace
}

Or a range:

if (c.Rank >= decks.Two && c.Rank < decks.Ten) {
    // handle cards [2, 10)
}

@dcu
Copy link
Author

dcu commented Aug 3, 2019

why not starting in iota+1? that would cover the value for most cases

@preslavmihaylov
Copy link
Owner

The initial implementation used that, yes.

But eventually, I decided to change it as it is now, because that approach causes issues with iterating over cards.

If the Ace starts at value 1, not zero, then there are all sorts of off-by-one errors that could occur.
For example, let's say you want to iterate over all ranks. Intuitively, you might do something like this:

cards := make([]Card, decks.RanksCnt)
for i := 0; i < decks.RanksCnt; i++ {
    cards[i] = decks.Card{Rank: i}
}

Issues with the code above if Ace starts at 1:

  1. Rank of zero is invalid
  2. You won't include the last rank (King)

Even if you do:

cards := make([]Card, decks.RanksCnt)
for i := decks.Ace; i < decks.RanksCnt; i++ {
    cards[i] = decks.Card{Rank: i}
}

This is still wrong, because you will miss the last rank (King) as decks.King == decks.RanksCnt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants