Thursday, April 14, 2011

playerhand drawcard ok

In our previous post we explained the Forth words we created for building and shuffling a deck as well as for getting the next card off the deck.

Now we have started building up a library of words for working with "hands" (a player's set of cards).

First of all, as in the original Java version, Crazy Eights is a two player game between the player and the dealer (computer). In the Java version these two hands are represented by instantiating instances of the Hand class.

In our Forth implementation we are representing the two hands by allocating space in memory as follows:
create playerhand 12 allot
create dealerhand 12 allot

This code creates two sets of 12 empty slots in memory.

Next we created a word for drawing a card:
: drawcard
nextcardfromdeck
swap
gethandcardcount
swap
+
c!
;

This word calls on two other words: nextcardfromdeck which gets the next card from the top of the deck (as explained in our previous post) and gethandcardcount. The gethandcardcount word is a "helper" word we created which uses a variable (#cardcount) to count how many cards are in a hand. It does this by starting at the address of the "hand" and looping through until it finds the first memory slot with the value of 0 which represents a blank card. Below is the code for the gethandcardcount word.
: gethandcardcount
0 #cardcount !
begin
dup
#cardcount @
swap
+
c@
0>
while
#cardcount @ 1 +
#cardcount !
repeat
#cardcount @
;


So, now that we have a word that draws a card from the deck we can use it as follows:
playerhand drawcard

1 comment:

  1. Just noticed there is a bug with the gethandcardcount word. We are currently representing cards as 0-51... this means if a hand has the 0 card the word will not see that as a card and stop counting the cards in the hand upon hitting that card. So, for example, if a hand had card 23, 14, 0, 8 - the word would only think there are 2 cards when really there are 4. There are a couple ways around this 1) refactor the card representation numbers to be 1-52, or 2) initialize the hand memory slots each to -1.

    ReplyDelete