numbers-game: simplify for readability.
parent
14d75bbbcb
commit
bf84e85126
|
@ -1,39 +1,23 @@
|
|||
USING: kernel math math.parser random io ;
|
||||
USING: combinators io kernel math.order math.parser random ;
|
||||
IN: numbers-game
|
||||
|
||||
: printfl ( s -- )
|
||||
print flush ;
|
||||
|
||||
: writefl ( s -- )
|
||||
write flush ;
|
||||
|
||||
: read-number ( -- n )
|
||||
readln string>number ;
|
||||
|
||||
: guess-banner ( -- )
|
||||
"I'm thinking of a number between 0 and 100." printfl ;
|
||||
"I'm thinking of a number between 0 and 100." print flush ;
|
||||
|
||||
: guess-prompt ( -- ) "Enter your guess: " writefl ;
|
||||
: guess-number ( -- n )
|
||||
"Enter your guess: " write flush readln string>number ;
|
||||
|
||||
: too-high ( -- ) "Too high" printfl ;
|
||||
|
||||
: too-low ( -- ) "Too low" printfl ;
|
||||
|
||||
: correct ( -- ) "Correct - you win!" printfl ;
|
||||
|
||||
: inexact-guess ( actual guess -- )
|
||||
< [ too-high ] [ too-low ] if ;
|
||||
|
||||
: judge-guess ( actual guess -- ? )
|
||||
2dup = [ 2drop correct f ] [ inexact-guess t ] if ;
|
||||
|
||||
: number-to-guess ( -- n ) 100 random ;
|
||||
: correct? ( actual guess -- ? )
|
||||
<=> {
|
||||
{ +lt+ [ "Too high" print flush f ] }
|
||||
{ +eq+ [ "Correct - you win!" print flush t ] }
|
||||
{ +gt+ [ "Too low" print flush f ] }
|
||||
} case ;
|
||||
|
||||
: numbers-game-loop ( actual -- )
|
||||
dup guess-prompt read-number judge-guess
|
||||
[ numbers-game-loop ] [ drop ] if ;
|
||||
[ dup guess-number correct? not ] loop drop ;
|
||||
|
||||
: numbers-game ( -- )
|
||||
guess-banner number-to-guess numbers-game-loop ;
|
||||
guess-banner 100 random numbers-game-loop ;
|
||||
|
||||
MAIN: numbers-game
|
||||
|
|
Loading…
Reference in New Issue