The start of a forth program for card games

in forth •  last month

1 Poker in Forth
════════════════

I want to make a simple program that will play heads-up limit poker.
I will write this program in Forth, with some annotations along the
way.

The logical start seems to be to put the cards in memory, but before
that can be achieved I would like to think about how I will retrieve
the cards.
┌────
│ 12 13 /mod . .

└────

This gives 0 12 as a reesult, that might be useful, I can use 0 of
each suit for the ace, otherwise there will be a weird case where the
king will "belong" to another suit. Then it will be a simple matter
of adding 1 to the result of the remainder and use that for rank.
This seems a reasonable way to do things.

then 13 will be the start of the second suit, and 26 the start of the
third and 39 the start of the last suit.

Then I can begin implementing this.
┌────
│ variable deck 60 cells allot

└────

Putting the cards in memory is a simple thing, a simple loop will
achieve this.
┌────
│ variable deck 60 cells allot

│ : new-deck 52 0 do I dup cells deck + ! loop ;

└────

Now to making the swapping, not so complicated forth is pretty great
since you can go to a forth system and directly interact with the
system, even compiling stuff, this is very convenient for testing
ideas quickly.

┌────
│ variable deck 60 cells allot

│ : new-deck 52 0 do I dup cells deck + ! loop ;

│ : [email protected] dup cells deck + @ ;
│ : card! cells deck + ! ;
│ : swap-card [email protected] rot [email protected] rot swap card! swap card! ;

└────

With this code I can begin to consider how to make the shuffler

The next thing is a random number generator
┌────
│ variable rnd here rnd !
│ : random rnd @ 31421 * 6927 + dup rnd ! ;
│ : choose random um* nip ;

└────

Now I just need to write a shuffler and then we can progress to the
next part of this project. The one where we focus on more immediate
things related to actually implementing card games. First perhaps
implementing something like WAR might make sense, just since that is
the easiest card game I can think of.

┌────
│ variable deck 60 cells allot

│ : new-deck 52 0 do I dup cells deck + ! loop ;

│ : [email protected] dup cells deck + @ ;
│ : card! cells deck + ! ;
│ : swap-card [email protected] rot [email protected] rot swap card! swap card! ;

│ variable rnd here rnd !
│ : random rnd @ 31421 * 6927 + dup rnd ! ;
│ : choose random um* nip ;

│ : shuffler 10000 0 do 2dup choose choose swap-card loop drop drop ;

└────

The drops are just to make sure that the stack is clean after I am
done, since I have to maintain stack balance.

This should be a decent implementation to build upon, from here I can
implement any number of card games. These will be in other posts.