home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
forth
/
compiler
/
fpc
/
source
/
l3p110.seq
< prev
next >
Wrap
Text File
|
1990-04-01
|
3KB
|
83 lines
\ Simple numeric input, version 2
\ Check to see if n is an ASCII key code corresponding
\ to a numeric digit 0 thru 9.
: DIGIT? ( n -- flag )
48 ( ASCII 0 ) 57 ( ASCII 9 ) [IN] ;
\ Erase character behind the cursor and backup one
\ character position.
: RUBOUT ( -- )
8 ( backspace ) EMIT SPACE 8 EMIT ;
\ Remove the most recently accumulated digit. For example
\ 123/10 = 12 The digit 3 is removed.
: -DIGIT ( n -- n/10 )
10 / ;
\ Take the ASCII code c for a digit 0 thru 9 and add it
\ into the number being formed. For example if n = 12
\ and c=51, the ASCII code for digit 3 then number left on
\ the stack will be 123. Try it yourself.
: +DIGIT ( n c -- 10n+c-48)
48 - SWAP 10 * + ;
\ Wait for user to input a number. Make sure that only numeric
\ keycodes are taken for input. This word uses an infinite loop
\ and uses EXIT to escape when the enter key is pressed.
: #IN ( -- num )
0 BEGIN KEY \ Fetch a key press.
DUP 13 ( enter ) =
IF DROP EXIT THEN \ Exit if done.
DUP 8 ( backspace ) =
IF DROP RUBOUT -DIGIT \ Erase and correct.
ELSE DUP DIGIT? \ Was digit pressed?
IF DUP EMIT \ Echo digit
+DIGIT \ Convert digit.
ELSE DROP \ Invalid key.
7 ( bell) EMIT \ Sound bell
THEN
THEN
AGAIN ;
COMMENT:
Problem 3.25
Use the new #IN to program this simple number guessing game.
The computer picks a secret number between 1 and 100. You try
to guess the number. With each guess the computer responds
"WARMER" if the guess is closer than the old guess,
"COLDER" if the guess is it is not closer,
"HOT!" if the guess is within 2 of the actual number.
"YOU GOT IT" if the guess is correct.
Hints:
1) Keep game info on the stack ( secret old# new# )
2) Use #IN
3) Use the random number generator below. Don't try to figure out
how it works. It uses one of those VARIABLES that we have been
avoiding.
COMMENT;
VARIABLE SEED 12345 SEED !
: (RND) SEED @ 259 * 3 + 32767 AND DUP SEED ! ;
\ r is a random number 0 <= r < n
: RND ( n r )
(RND) 32767 */ ;
\ Solution to problem 3.5 without any comments. If you are going to
\ borrow any thing from what you see below be sure to add the comments.
: WINNER? 2 PICK OVER = ;
: HOT? 2 PICK OVER - ABS 3 < ;
: WARMER? 2 PICK OVER - ABS
3 PICK 3 PICK - ABS < ;
: GAME
100 RND 1+ 0
BEGIN CR ." GUESS " #IN SPACE
WINNER? IF ." GOT IT" DROP 2DROP EXIT THEN
HOT? IF ." HOT " ELSE
WARMER? IF ." WARMER" ELSE ." COLDER" THEN
THEN NIP
AGAIN ;