RosettaCodeData/Task/24-game/BBC-BASIC/24-game.basic

67 lines
2.1 KiB
Plaintext

REM Choose four random digits (1-9) with repetitions allowed:
DIM digits%(4), check%(4)
FOR choice% = 1 TO 4
digits%(choice%) = RND(9)
NEXT choice%
REM Prompt the player:
PRINT "Enter an equation (using all of, and only, the single digits ";
FOR index% = 1 TO 4
PRINT ; digits%(index%) ;
IF index%<>4 PRINT " " ;
NEXT
PRINT ")"
PRINT "which evaluates to exactly 24. Only multiplication (*), division (/),"
PRINT "addition (+) & subtraction (-) operations and parentheses are allowed:"
INPUT "24 = " equation$
REPEAT
REM Check that the correct digits are used:
check%() = 0
FOR char% = 1 TO LEN(equation$)
digit% = INSTR("0123456789", MID$(equation$, char%, 1)) - 1
IF digit% >= 0 THEN
FOR index% = 1 TO 4
IF digit% = digits%(index%) THEN
IF NOT check%(index%) check%(index%) = TRUE : EXIT FOR
ENDIF
NEXT index%
IF index% > 4 THEN
PRINT "Sorry, you used the illegal digit "; digit%
EXIT REPEAT
ENDIF
ENDIF
NEXT char%
FOR index% = 1 TO 4
IF NOT check%(index%) THEN
PRINT "Sorry, you failed to use the digit " ; digits%(index%)
EXIT REPEAT
ENDIF
NEXT index%
REM Check that no pairs of digits are used:
FOR pair% = 11 TO 99
IF INSTR(equation$, STR$(pair%)) THEN
PRINT "Sorry, you may not use a pair of digits "; pair%
EXIT REPEAT
ENDIF
NEXT pair%
REM Check whether the equation evaluates to 24:
ON ERROR LOCAL PRINT "Sorry, there was an error in the equation" : EXIT REPEAT
result = EVAL(equation$)
RESTORE ERROR
IF result = 24 THEN
PRINT "Congratulations, you succeeded in the task!"
ELSE
PRINT "Sorry, your equation evaluated to " ; result " rather than 24!"
ENDIF
UNTIL TRUE
INPUT '"Play again", answer$
IF LEFT$(answer$,1) = "y" OR LEFT$(answer$,1) = "Y" THEN CLS : RUN
QUIT