forth/sticks.f

74 lines
1.7 KiB
Forth
Executable File

\ sticks.f
\ After "23 Matches" in Ahl, _Basic Computer Games_
\ Ahl attributes the original to Bob Albrecht
cr .( Reading sticks.f)
\ random number generator
s" random.f" included
\ Rules of the game
: rules ( -- )
cr ." Sticks"
cr
cr ." The game starts with 23 sticks. "
." By turns, you and Forth take"
cr ." from 1 to 3 sticks. "
." Whoever takes the last stick loses."
cr
cr ." You take sticks by entering: n STICKS"
cr ." where n is 1, 2, or 3"
cr ;
\ Display sticks
: .sticks ( n -- ) 0 ?do ." |" loop ;
\ Report remaining sticks
: left ( sticks taken -- left )
- dup cr .sticks space dup . ." left." ;
\ The fates of Forth
: you-win ( sticks -- ) drop ." You win! " ;
: forth-wins ( sticks -- )
." Forth took " 1- .
cr ." 1 left - sorry!" ;
: 4-play ( sticks -- left )
." Forth took " 3 choose 1+ dup . left ;
\ My esteemed opponent
: computer ( sticks -- left| )
cr
dup 1 = if you-win else
dup 5 < if forth-wins else
4-play
then then ;
\ First play
: coin ( 23 -- n )
2 choose
cr ." A coin has been flipped: "
if ." Heads, Forth is first." computer
else ." Tails, you start."
then ;
\ Confine n between min and max
: clamp ( n min max -- n ) rot min max ;
\ May take between 1 and 3 sticks, leaving at least 1
: legal ( sticks try -- sticks taken )
over 1- 3 min 1 swap clamp ;
\ My play
: programmer ( sticks try -- left ) legal left ;
\ 1 Round
: sticks ( sticks try -- left| ) programmer computer ;
\ Alias for STICKS
: stick ( sticks try -- left| ) sticks ;
: game ( -- )
rules 23 dup cr .sticks randomize coin ;
cr .( Ready. To play, enter: GAME)