Penney's game: Difference between revisions

Content added Content deleted
(→‎{{Header|Ruby}}: optimized the choice of the computer.)
(Added BBC BASIC)
Line 175: Line 175:


[Type Y if U Wanna Beat Me, or Else, Exit...]</pre>
[Type Y if U Wanna Beat Me, or Else, Exit...]</pre>

=={{header|BBC BASIC}}==
<lang bbcbasic>REM >penney
PRINT "*** Penney's Game ***"
REPEAT
PRINT ' "Heads you pick first, tails I pick first."
PRINT "And it is... ";
WAIT 100
ht% = RND(0 - TIME) AND 1
IF ht% THEN
PRINT "heads!"
PROC_player_chooses(player$)
computer$ = FN_optimal(player$)
PRINT "I choose "; computer$; "."
ELSE
PRINT "tails!"
computer$ = FN_random
PRINT "I choose "; computer$; "."
PROC_player_chooses(player$)
ENDIF
PRINT "Starting the game..." ' SPC 5;
sequence$ = ""
winner% = FALSE
REPEAT
WAIT 100
roll% = RND AND 1
IF roll% THEN
sequence$ += "H"
PRINT "H ";
ELSE
PRINT "T ";
sequence$ += "T"
ENDIF
IF RIGHT$(sequence$, 3) = computer$ THEN
PRINT ' "I won!"
winner% = TRUE
ELSE
IF RIGHT$(sequence$, 3) = player$ THEN
PRINT ' "Congratulations! You won."
winner% = TRUE
ENDIF
ENDIF
UNTIL winner%
REPEAT
valid% = FALSE
INPUT "Another game? (Y/N) " another$
IF INSTR("YN", another$) THEN valid% = TRUE
UNTIL valid%
UNTIL another$ = "N"
PRINT "Thank you for playing!"
END
:
DEF PROC_player_chooses(RETURN sequence$)
LOCAL choice$, valid%, i%
REPEAT
valid% = TRUE
PRINT "Enter a sequence of three choices, each of them either H or T:"
INPUT "> " sequence$
IF LEN sequence$ <> 3 THEN valid% = FALSE
IF valid% THEN
FOR i% = 1 TO 3
choice$ = MID$(sequence$, i%, 1)
IF choice$ <> "H" AND choice$ <> "T" THEN valid% = FALSE
NEXT
ENDIF
UNTIL valid%
ENDPROC
:
DEF FN_random
LOCAL sequence$, choice%, i%
sequence$ = ""
FOR i% = 1 TO 3
choice% = RND AND 1
IF choice% THEN sequence$ += "H" ELSE sequence$ += "T"
NEXT
= sequence$
:
DEF FN_optimal(sequence$)
IF MID$(sequence$, 2, 1) = "H" THEN
= "T" + LEFT$(sequence$, 2)
ELSE
= "H" + LEFT$(sequence$, 2)
ENDIF</lang>
{{out}}
<pre>*** Penney's Game ***

Heads you pick first, tails I pick first.
And it is... heads!
Enter a sequence of three choices, each of them either H or T:
> HTT
I choose HHT.
Starting the game...
H H H H H T
I won!
Another game? (Y/N) Y

Heads you pick first, tails I pick first.
And it is... tails!
I choose HTH.
Enter a sequence of three choices, each of them either H or T:
> HHT
Starting the game...
T T H H H H T
Congratulations! You won.
Another game? (Y/N) N
Thank you for playing!</pre>


=={{header|C}}==
=={{header|C}}==