• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

RAND.BAT

One of the best functions a sample program can perform is to play a game. This makes it fun for everyone to figure out how the sample works, and modify it for different variations. For this reason, our first example (shown in Code Listing C.1) is a simple Guess-the-Number game. Note that this batch file will run only on Windows 2000 and later, although it doesn't test to see whether this is the case.

Code Listing C.1. The RAND.BAT Game

01 @ECHO OFF
02 REM Guess the Number Game
03
04 REM Begin by picking the random number.
05 SET /A ONES=%RANDOM:~–1%
06 SET /A TENS=%RANDOM:~–1%
07 IF %TENS%==0 SET TENS=
08 SET ANSWER=%TENS%%ONES%
09
10 REM Initialize variables.
11 SET GUESSES=0
12 SET GUESS=0
13
14 ECHO Guess the number!
15 :TOP
16 ECHO.
17 SET /P GUESS=Pick a number between 0 and 99:
18
19 REM Validate the input's length
20 IF NOT %GUESS%==%GUESS:~–2% GOTO BADANSWER
21
22 REM Validate that the input is a number
23 SET /A ONES=%GUESS% %% 10 2>NUL
24 SET /A TENS=%GUESS% / 10 2>NUL
25 IF %TENS%==0 GOTO ONESCHK
26 IF NOT %GUESS%==%TENS%%ONES% GOTO BADANSWER
27 GOTO VALID
28
29 :ONESCHK
30 IF NOT %GUESS%==%ONES% GOTO BADANSWER
31
32 :VALID
33 SET /A GUESSES=%GUESSES% + 1
34 IF %GUESS%==%ANSWER% GOTO YOUWIN
35 IF %GUESS% LSS %ANSWER% GOTO TOOLOW
36 GOTO TOOHIGH
37
38 :TOOLOW
39 ECHO Your guess of %GUESS% was too low. Try again.
40 GOTO :TOP
41
42 :TOOHIGH
43 ECHO Your guess of %GUESS% was too high. Try again.
44 GOTO :TOP
45
46 :BADANSWER
47 ECHO Invalid input.
48 ECHO Your guess must be an integer between 0 and 99.
49 ECHO.
50 GOTO TOP
51
52 :YOUWIN
53 ECHO.
54 ECHO YOU WIN!
55 ECHO %GUESS% was the right answer.
56 ECHO It took you %GUESSES% trys.
57 ECHO.
58 GOTO :EOF


					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint