Penney's game
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 rolls the dice, 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 dice rolls 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! >>>