Penney's game: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|REXX}}: added section header comment about using a seed for the RANDOM BIF (for repeatability).)
m (→‎{{header|REXX}}: added some comments, changed others.)
Line 66: Line 66:
The REXX program keeps a running score (number of wins out of so many games played)
The REXX program keeps a running score (number of wins out of so many games played)
<br>as well as allowing the human to pick the number (lenfth) of the coin toss sequence.
<br>as well as allowing the human to pick the number (lenfth) of the coin toss sequence.
<br>Extra code was added to ensure a valid responce from the human player.
<br>Extra code was added to ensure a valid response from the human player as well as give an informative error message.
<br>A feature also added was to allow a seed for the &nbsp; '''random''' &nbsp; BIF to cause repeatability.
<br>A feature also added was to allow a seed for the &nbsp; '''random''' &nbsp; BIF to cause repeatability.
<lang rexx>/*REXX program plays Penney's Game, a 2 player coin toss sequence game.*/
<lang rexx>/*REXX program plays Penney's Game, a 2 player coin toss sequence game.*/
Line 85: Line 85:
isMix: return datatype(arg(1),'Mixed') /*verify arg is alpha. */
isMix: return datatype(arg(1),'Mixed') /*verify arg is alpha. */
r: parse arg _,$; do word(arg(1) 3,1); $=$||random(0,1); end; return $
r: parse arg _,$; do word(arg(1) 3,1); $=$||random(0,1); end; return $
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1)
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/
/*──────────────────────────────────GAME subroutine─────────────────────*/
/*──────────────────────────────────GAME subroutine─────────────────────*/
@.= /*choices made by computer,human.*/
game: tosses= /*the coin toss sequence so far. */
game: tosses= /*the coin toss sequence so far. */
toss1=r(1) /*result: 0=computer, 1=CBLF.*/
toss1=r(1) /*result: 0=computer, 1=CBLF.*/
@.= /*CBLF: carbon-based life form. */
@.= /*CBLF: carbon-based life form. */
if \toss1 then call randComp
if \toss1 then call randComp /*maybe let the computer go first*/
if toss1 then say __ "You win the first toss, so you pick your sequence first."
if toss1 then say __ "You win the first toss, so you pick your sequence first."
else say __ "The computer won first toss, the pick was: " @.comp
else say __ "The computer won first toss, the pick was: " @.comp
call prompter
call prompter /*get the human's guess from C.L.*/
call randComp
call randComp /*get computer's guess if needed.*/
say
say __ " your pick:" @.CBLF
say __ "computer's pick:" @.comp
say
say
say __ " your pick:" @.CBLF /*echo human's pick to terminal. */
say __ "computer's pick:" @.comp /* " comp.'s " " " */
say /* [↓] flip the coin 'til a win.*/
do flips=1 until pos(@.CBLF,tosses)\==0 | pos(@.comp,tosses)\==0
do flips=1 until pos(@.CBLF,tosses)\==0 | pos(@.comp,tosses)\==0
tosses=tosses || translate(r(1),'HT',10)
tosses=tosses || translate(r(1),'HT',10)
end /*flips*/
end /*flips*/ /* [↑] this is a flipping coin,*/
/* [↑] humorous comment there. */

@@@="won this toss with " flips ' coin tosses.'
@@@="won this toss with " flips ' coin tosses.' /*handy literal.*/
if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end
if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end
else say __ "The computer" @@@
else say __ "The computer" @@@
say /* [↓] series of tosses*/
say
say __ "The tossed coin series was: " tosses /*show the tossed coin.*/
say __ "The tossed coin series was: " tosses /*show the coin tosses.*/
say /* [↓] (sic) */
say
_=wins; if _==0 then _='no'
_=wins; if _==0 then _='no' /*use gooder English. */
say __ "You've won" _ "game"s(wins) 'out of ' games"."
say __ "You've won" _ "game"s(wins) 'out of ' games"."
say; say copies('╩╦',79%2)'╩'; say
say; say copies('╩╦',79%2)'╩'; say /*display eyeball fence*/
return
return
/*──────────────────────────────────PROMPTER subroutine─────────────────*/
/*──────────────────────────────────PROMPTER subroutine─────────────────*/
Line 132: Line 131:
end /*select*/
end /*select*/
end /*until ok*/
end /*until ok*/
@.CBLF=a /*we have the human's guess now. */
@.CBLF=a
return
return
/*──────────────────────────────────RANDCOMP subroutine─────────────────*/
/*──────────────────────────────────RANDCOMP subroutine─────────────────*/
Line 140: Line 139:
else @.comp='T'
else @.comp='T'
do k=2 to #; _=right(@.comp,1) /*flush out.*/
do k=2 to #; _=right(@.comp,1) /*flush out.*/
if _=='T' then @.comp=@.comp'H'
if _=='T' then @.comp=@.comp'H' /*anti-guess*/
else @.comp=@.comp'T'
else @.comp=@.comp'T' /*alternate.*/
end /*k*/
end /*k*/
return
return /*done: have an optimized guess.*/
end
end



Revision as of 20:24, 27 September 2014

Penney's game is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Penneys game is a game where two players bet on being the first to see a particular sequence of Heads and Tails in consecutive tosses of a fair coin.

It is common to agree on a sequence length of three then one player will openly choose a sequence, for example Heads, Tails, Heads, or HTH for short; then the other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.

For example: One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.

The Task

Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.

  • Who chooses and shows their sequence of three should be chosen randomly.
  • If going first, the computer should choose its sequence of three randomly.
  • If going second, the computer should automatically play the optimum sequence.
  • Successive coin tosses should be shown.

Show output of a game where the computer choses first and a game where the user goes first here on this page.

Python

<lang python>from __future__ import print_function import random from time import sleep

first = random.choice([True, False])

you = if first:

   me = .join(random.sample('HT'*3, 3))
   print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
   while len(you) != 3 or any(ch not in 'HT' for ch in you) or you == me:
       you = input('What sequence of three Heads/Tails will you win with: ')

else:

   while len(you) != 3 or any(ch not in 'HT' for ch in you):
       you = input('After you: What sequence of three Heads/Tails will you win with: ')
   me = ('H' if you[1] == 'T' else 'T') + you[:2]
   print('I win on first seeing {} in the list of tosses'.format(me))
   

print('Rolling:\n ', end=) rolled = while True:

   rolled += random.choice('HT')
   print(rolled[-1], end=)
   if rolled.endswith(you):
       print('\n  You win!')
       break
   if rolled.endswith(me):
       print('\n  I win!')
       break
   sleep(1)    # For dramatic effect</lang>
Output:
>>> 
After you: What sequence of three Heads/Tails will you win with: TTH
I win on first seeing HTT in the list of tosses
Rolling:
  THHTHHTT
  I win!
>>> ================================ RESTART ================================
>>> 
I choose first and will win on first seeing HHT in the list of tosses
What sequence of three Heads/Tails will you win with: THH
Rolling:
  HTHTHTTTHTTTTTTHH
  You win!
>>> 

REXX

The REXX program keeps a running score (number of wins out of so many games played)
as well as allowing the human to pick the number (lenfth) of the coin toss sequence.
Extra code was added to ensure a valid response from the human player as well as give an informative error message.
A feature also added was to allow a seed for the   random   BIF to cause repeatability. <lang rexx>/*REXX program plays Penney's Game, a 2 player coin toss sequence game.*/ __=copies('─',9) /*used for eyecatcher fence. */ signal on halt /*a clean way out if CLBF quits. */ parse arg # ? . /*default coin sequence length. */ if #== | #=="," then #=3 /*default coin sequence length. */ if ?\== & ?\==',' then call random ,,? /*use seed for RANDOM #s ?*/ comp=0; CBLF=1 /*"names for computer and human. */ wins=0; do games=1 /*execute any number of games. */

          call game                   /*process a single inning of game*/
          end   /*games*/             /*keep at it 'til  QUIT  or halt.*/

exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────one-line subroutines────────────────*/ $: parse arg _,$; do word(arg(1) 3,1); $=$||random(0,1); end; return $ halt: say; say __ "Penney's Game was halted."; say; exit 13 isBin: return datatype(arg(1),'Binary') /*verify if arg is bin.*/ isMix: return datatype(arg(1),'Mixed') /*verify arg is alpha. */ r: parse arg _,$; do word(arg(1) 3,1); $=$||random(0,1); end; return $ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ /*──────────────────────────────────GAME subroutine─────────────────────*/ game: tosses= /*the coin toss sequence so far. */ toss1=r(1) /*result: 0=computer, 1=CBLF.*/ @.= /*CBLF: carbon-based life form. */ if \toss1 then call randComp /*maybe let the computer go first*/ if toss1 then say __ "You win the first toss, so you pick your sequence first."

          else say __ "The computer won first toss, the pick was: " @.comp
               call prompter          /*get the human's guess from C.L.*/
               call randComp          /*get computer's guess if needed.*/

say say __ " your pick:" @.CBLF /*echo human's pick to terminal. */ say __ "computer's pick:" @.comp /* " comp.'s " " " */ say /* [↓] flip the coin 'til a win.*/

     do  flips=1  until pos(@.CBLF,tosses)\==0  |  pos(@.comp,tosses)\==0
     tosses=tosses || translate(r(1),'HT',10)
     end   /*flips*/                  /* [↑]   this is a flipping coin,*/
                                      /* [↑]   humorous comment there. */

@@@="won this toss with " flips ' coin tosses.' /*handy literal.*/ if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end

                          else      say __  "The computer"  @@@

say /* [↓] series of tosses*/ say __ "The tossed coin series was: " tosses /*show the coin tosses.*/ say /* [↓] (sic) */ _=wins; if _==0 then _='no' /*use gooder English. */ say __ "You've won" _ "game"s(wins) 'out of ' games"." say; say copies('╩╦',79%2)'╩'; say /*display eyeball fence*/ return /*──────────────────────────────────PROMPTER subroutine─────────────────*/ prompter: oops=__ 'Oops! '; a= p=__ 'Pick a sequence of' # "coin tosses of H or T (Heads or Tails) or Quit:"

         do  until  ok;   say;  say p;  pull a  /*uppercase the answer.*/
         a=space(a,0);    L=length(a)           /*squish blanks, get L.*/
         if abbrev('QUIT',a,1)  then exit 1     /*human wants to quit. */
         b=translate(a,10,'HT')                 /*translate to binary. */
         ok=0                                   /*response is OK so far*/
             select                             /*verify user response.*/
             when \isBin(b)  then say oops "Illegal response."
             when \isMix(a)  then say oops "Illegal characters in response."
             when L==0       then say oops "No choice was given."
             when L<#        then say oops "Not enough coin choices."
             when L>#        then say oops "Too many coin choices."
             when a==@.comp  then say oops "You can't choose the computer's choice: " @.comp
             otherwise            ok=1
             end   /*select*/
         end       /*until ok*/

@.CBLF=a /*we have the human's guess now. */ return /*──────────────────────────────────RANDCOMP subroutine─────────────────*/ randComp: if @.comp\== then return /*the computer already has a pick*/ if @.CBLF\== then do /*use a best-choice algorithm. */

                    if left(@.CBLF,1)=='T'  then @.comp='H'
                                            else @.comp='T'
                      do k=2  to #;   _=right(@.comp,1)    /*flush out.*/
                      if _=='T'  then @.comp=@.comp'H'     /*anti-guess*/
                                 else @.comp=@.comp'T'     /*alternate.*/
                      end   /*k*/
                    return            /*done:  have an optimized guess.*/
                    end
       do  until  @.comp\==@.CBLF
       @.comp=translate(r(3),'HT',10)
       end   /*while @.comp ···*/

return</lang> output of a six-game session   (ended by user entering a quit):

───────── The computer won first toss, the pick was:  HHH

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
ttt

─────────       your pick: TTT
───────── computer's pick: HHH

───────── The computer won this toss with  12  coin tosses.

───────── The tossed coin series was:  HHTTHHTHTHHH

───────── You've won no games out of  1.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── You win the first toss, so you pick your sequence first.

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
hht

─────────       your pick: HHT
───────── computer's pick: THT

───────── The computer won this toss with  5  coin tosses.

───────── The tossed coin series was:  TTTHT

───────── You've won no games out of  2.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── The computer won first toss, the pick was:  HHT

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
hhh

─────────       your pick: HHH
───────── computer's pick: HHT

───────── The computer won this toss with  3  coin tosses.

───────── The tossed coin series was:  HHT

───────── You've won no games out of  3.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── The computer won first toss, the pick was:  HTH

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
tth

─────────       your pick: TTH
───────── computer's pick: HTH

───────── You won this toss with  3  coin tosses.

───────── The tossed coin series was:  TTH

───────── You've won 1 game out of  4.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── You win the first toss, so you pick your sequence first.

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
thh

─────────       your pick: THH
───────── computer's pick: HTH

───────── You won this toss with  4  coin tosses.

───────── The tossed coin series was:  TTHH

───────── You've won 2 games out of  5.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── The computer won first toss, the pick was:  TTH

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
tth
───────── Oops!   You can't choose the computer's choice:  TTH

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
tht

─────────       your pick: THT
───────── computer's pick: TTH

───────── The computer won this toss with  3  coin tosses.

───────── The tossed coin series was:  TTH

───────── You've won 2 games out of  6.

╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩╦╩

───────── You win the first toss, so you pick your sequence first.

───────── Pick a sequence of 3 coin tosses of  H or T (Heads or Tails) or Quit:
quit