Write a program that plays a simulated coin toss game and produces the accumulated scores.
RANDOM(0,1)
Compare
the valid input with the value from RANDOM. If they are the same,
the user wins one point; if they are different, the computer wins
one point. Return the result to the main program where results are
tallied./***************************** REXX ********************************/
/* This program plays a simulated coin toss game. */
/* The input can be heads, tails, or null ("") to quit the game. */
/* First an internal subroutine checks input for validity. */
/* An external subroutine uses the RANDOM built-in function to */
/* obtain a simulation of a throw of dice and compares the user */
/* input to the random outcome. The main program receives */
/* notification of who won the round. It maintains and produces */
/* scores after each round. */
/*******************************************************************/
PULL flip /* Gets "HEADS", "TAILS", or "" */
/* from input stream. */
computer = 0; user = 0 /* Initializes scores to zero */
CALL check /* Calls internal subroutine, check */
DO FOREVER
CALL throw /* Calls external subroutine, throw */
IF RESULT = 'machine' THEN /* The computer won */
computer = computer + 1 /* Increase the computer score */
ELSE /* The user won */
user = user + 1 /* Increase the user score */
SAY 'Computer score = ' computer ' Your score = ' user
PULL flip
CALL check /* Call internal subroutine, check */
END
EXIT
/*************************** REXX ************************************/
/* This internal subroutine checks for valid input of "HEADS", */
/* "TAILS", or "" (to quit). If the input is anything else, the */
/* subroutine says the input is not valid and gets the next input. */
/* The subroutine keeps repeating until the input is valid. */
/* Commonly used variables return information to the main program */
/*********************************************************************/
check:
DO UNTIL outcome = 'correct'
SELECT
WHEN flip = 'HEADS' THEN
outcome = 'correct'
WHEN flip = 'TAILS' THEN
outcome = 'correct'
WHEN flip = '' THEN
EXIT
OTHERWISE
outcome = 'incorrect'
PULL flip
END
END
RETURN
/******************************* REXX ********************************/
/* This external subroutine receives the valid input, analyzes it, */
/* gets a random "flip" from the computer, and compares the two. */
/* If they are the same, the user wins. If they are different, */
/* the computer wins. The routine returns the outcome to the */
/* calling program. */
/*********************************************************************/
throw:
ARG input
IF input = 'HEADS' THEN
userthrow = 0 /* heads = 0 */
ELSE
userthrow = 1 /* tails = 1 */
compthrow = RANDOM(0,1) /* choose a random number */
/* between 0 and 1 */
IF compthrow = userthrow THEN
outcome = 'human' /* user chose correctly */
ELSE
outcome = 'machine' /* user chose incorrectly */
RETURN outcome