Penney's game: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(21 intermediate revisions by 10 users not shown)
Line 29:
* [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video).
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V first = random:choice([1B, 0B])
 
V you = ‘’
V me = ‘’
V ht = ‘HT’ // to get round ‘bug in MSVC 2017’[https://developercommunity.visualstudio.com/t/bug-with-operator-in-c/565417]
I first
me = random:sample(Array(‘HT’ * 3), 3).join(‘’)
print(‘I choose first and will win on first seeing #. in the list of tosses’.format(me))
L you.len != 3 | any(you.map(ch -> ch !C :ht)) | you == me
you = input(‘What sequence of three Heads/Tails will you win with: ’)
E
L you.len != 3 | any(you.map(ch -> ch !C :ht))
you = input(‘After you: What sequence of three Heads/Tails will you win with: ’)
me = (I you[1] == ‘T’ {‘H’} E ‘T’)‘’you[0.<2]
print(‘I win on first seeing #. in the list of tosses’.format(me))
 
print("Rolling:\n ", end' ‘’)
V rolled = ‘’
L
rolled ‘’= random:choice(‘HT’)
print(rolled.last, end' ‘’)
I rolled.ends_with(you)
print("\n You win!")
L.break
I rolled.ends_with(me)
print("\n I win!")
L.break
sleep(1)</syntaxhighlight>
 
{{out}}
<pre>
I choose first and will win on first seeing THH in the list of tosses
What sequence of three Heads/Tails will you win with: THT
Rolling:
THT
You win!
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Gui, font, s12
Gui, add, text, w90, Computer:
loop, 3
Line 111 ⟶ 152:
gosub, RandomStart
return
;-----------------------------------------------</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
{{trans|Sinclair ZX81 BASIC}}
<syntaxhighlight lang="Amazing Hopper">
#include <jambo.h>
 
#define Getanuppercasecharinto(_X_) Getchar(_X_),Let( _X_ := Ucase(_X_) )
#define Isnotvalidin(_X_) Not( Occurs in (_X_) )
#define NOELIGEPCDESPUESDETI 0
#define ELIGEPCDESPUESDETI 1
 
Main
Set break
Get total args
If ( Is equal to '2' )
largo=0
Let ( largo := Get if( Argnum(2) Is less than '3', 3, Argnum(2) ) )
OTRO="S"
Cursor off
Loop
P="", C="", S="", L=0
Cls
Locate(1,1), Printnl ("***** Penney's Game *****")
If ( Geq( Rand(1), 0.5) )
Gosub ' Yo tiro ', Set 'NO ELIGE PC DESPUES DE TI',Gosub ' Tú tiras '
Else
Set 'ELIGE PC DESPUES DE TI', Gosub ' Tú tiras '
End If
 
// a jugar:
G="", SW=1
Loop
Let( G := Cat( G, Get if( Geq( Rand(1), 0.5), "T", "H" ) ) )
Locate( 6, 1 ), Printnl( "Tiradas: ", G )
Continue if ( Less ( Len (G) ---Backup to 'L'---, 3) )
Let ( S := Right( Sub(L, Minus one 'largo') , G) )
 
If ( Eq( S, P ) )
Set ("TU GANAS!!"), SW=0
Else If (Eq( S, C ) )
Set ("YO GANO!!"), SW=0
End If
Prnl
Sleep(1)
Back if( SW ) is not zero
Printnl ( Utf8("¿Otro juego? S/* ") )
Getchar(OTRO)
While( Eq (OTRO, "S") )
Cursor on
Else
Printnl("Modo de uso: hopper penny.jambo <n>\ndonde \"n\" es el largo de la secuencia")
End If
End
 
Subrutines
 
Define ' Yo tiro '
Locate(4,1), Print( "Yo elijo... " )
i=largo
Loop
Let( C := Cat( C, Get if( Geq( Rand(1), 0.5), "T", "H" ) ) )
--i
Back if (i) is positive
Printnl (C)
Return
 
Define ' Tú tiras, elige pc '
Locate(3,1), Printnl ( Utf8("Tú eliges...") )
i=largo, c=0
Loop
Get an uppercase char into 'c'
Continue if ( var(c) Is not valid in ("HT") )
Let( P:=Cat(P,c) )
Loccol(13), Printnl(P)
--i
Back if (i) is positive
 
If ( elige pc )
Let (C := P)
[2] Get from (C)
Set if( Is equal to ("H"), "T", "H" )
Cput (C)
Locate(4,1), Print( "Yo elijo... ", C )
End If
Return
</syntaxhighlight>
{{out}}
<pre>
$ hopper penney.jambo
Modo de uso: hopper penny.jambo <n>
donde "n" es el largo de la secuencia
 
$ hopper penney.jambo 5
***** Penney's Game *****
 
Tú eliges...HTHHT
Yo elijo... HHHHT
 
Tiradas: TTHTTTTHHTTHHTTHTHTHHT
TU GANAS!!
¿Otro juego? S/*
 
***** Penney's Game *****
 
Tú eliges...HTHTT
Yo elijo... HHHTT
 
Tiradas: THHHHTHHHHTT
YO GANO!!
¿Otro juego? S/*
$
</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|Pascal}}
<syntaxhighlight lang="gwbasic"> 100 R = RND ( - 1 * ( PEEK (78) + 256 * PEEK (79))): REM RANDOMIZE
110 DEF FN R(R) = INT ( RND (1) * R) * (3 ^ (R = 8)) + 1
120 READ P$
130 DATA HTHHHHHHTHTTTHHTHTTTHTTT
140 LET M$ = CHR$ (13)
150 PRINT "WELCOME TO PENNEY'S GAME!"M$
160 INPUT "HOW MANY ROUNDS WOULD YOU LIKE TO PLAY? ";ROUNDS%
170 PRINT M$"OK, LET'S PLAY "ROUNDS%" ROUNDS."
180 FOR COUNT = 1 TO ROUNDS%
190 PRINT M$"*** ROUND #"COUNT" ***"M$
200 ON FN R(2) GOSUB 300,400
210 PRINT "LET'S GO!"M$
220 GOSUB 450"PLAY ROUND
230 INPUT "PRESS RETURN TO GO ON...";N$
240 NEXT COUNT
250 PRINT M$"*** END RESULT ***"M$
260 IF YOU > ME THEN PRINT "CONGRATULATIONS! YOU WON!"
270 IF ME > YOU THEN PRINT "HOORAY! I WON"
280 IF ME = YOU THEN PRINT "COOL, WE TIED."
290 END
 
300 ME$ = MID$ (P$, FN R(8),3): REM RANDOM SEQUENCE
310 PRINT "I'LL PICK FIRST THIS TIME."M$" MY SEQUENCE IS "ME$"."
320 FOR REP = 0 TO 1 STEP 0
330 PRINT "WHAT SEQUENCE DO YOU WANT?"
340 GOSUB 590"GET YOUR SEQUENCE
350 LET REP = YOU$ < > ME$
360 IF NOT REP THEN PRINT "HEY, THAT'S MY SEQUENCE! THINK FOR YOURSELF!"
370 NEXT REP
380 PRINT YOU$", HUH? SOUNDS OK TO ME."
390 RETURN
 
400 PRINT "YOU PICK FIRST THIS TIME."
410 GOSUB 590"GET YOUR SEQUENCE
420 LET ME$ = MID$ ("HT",( MID$ (YOU$,2,1) = "H") + 1,1) + LEFT$ (YOU$,2)
430 PRINT "OK, SO YOU PICKED "YOU$M$M$"MY SEQUENCE WILL BE "ME$M$
440 RETURN
 
450 T0SSE$ = MID$ (P$, FN R(8),3): REM RANDOM SEQUENCE
460 PRINT "TOSSING THE COIN: "M$ MID$ (T0SSE$,2);
470 FOR T0SS = 0 TO 1 STEP 0
480 LET T0SSE$ = RIGHT$ (T0SSE$,2) + MID$ ("HT", FN R(2),1)
490 PRINT MID$ (T0SSE$,3);
500 IF YOU$ = T0SSE$ THEN 530"YOU WON
510 IF ME$ = T0SSE$ THEN 560"I WON
520 NEXT T0SS
 
530 YOU = YOU + 1
540 PRINT M$M$"CONGRATULATIONS! YOU WON THIS ROUND."M$"YOUR NEW SCORE IS "YOU"."
550 RETURN
 
560 ME = ME + 1
570 PRINT M$M$"YAY, I WON THIS ROUND!"M$"MY NEW SCORE IS "ME"."
580 RETURN
 
590 YOU$ = ""
600 PRINT "TYPE 3 LETTERS H OR T: "
610 FOR I = 1 TO 3
620 LET V$ = "HT"
630 GOSUB 670"GET VALID KEYPRESS
640 LET YOU$ = YOU$ + C$
650 NEXT I
660 LET V$ = M$ + M$
670 FOR C = 0 TO 1 STEP 0
680 GET C$
690 IF ASC (C$) > 95 THEN C$ = CHR$ ( ASC (C$) - 32)
700 LET C = C$ = LEFT$ (V$,1) OR C$ = MID$ (V$,2)
710 NEXT C
720 PRINT C$;
730 RETURN</syntaxhighlight>
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
global jugador, computador, secuencia
jugador = "" : computador = ""
 
function SecuenciaJugador(secuencia)
do
valido = TRUE
print chr(10) + "Ingresa una secuencia de 3 opciones, cada una de ellas H o T:";
input " > ", secuencia
secuencia = upper(secuencia)
if length(secuencia) <> 3 then valido = FALSE
if secuencia = computador then print "Pero no la misma que yo..."+ chr(10): valido = FALSE
if valido then
for i = 1 to 3
opcion = mid(secuencia, i, 1)
if opcion <> "H" and opcion <> "T" then valido = FALSE
next i
end if
until valido
SecuenciaJugador = secuencia
end function
 
function LanzamientoCPU()
secuencia = ""
computador =""
for i = 1 to 3
opcion = rand
if opcion < .5 then secuencia += "H" else secuencia += "T"
next i
LanzamientoCPU = secuencia
end function
 
do
cls
print "*** Penney's Game ***" + chr(10)
if rand < .5 then
print "Empiezas... ";
jugador = SecuenciaJugador(jugador)
computador = LanzamientoCPU()
if jugador = computador then computador = LanzamientoCPU()
print "Yo gano al ver "; computador; " por primera vez en la lista de lanzamientos..."
else
computador = LanzamientoCPU()
print "Elijo primero y gano al ver "; computador; " por primera vez en la lista de lanzamientos..."
jugador = SecuenciaJugador(jugador)
end if
print: print "Lanzamientos..."
secuencia = ""
winner = FALSE
do
pause 1
if rand <= .5 then
secuencia += "H"
print "H ";
else
print "T ";
secuencia += "T"
end if
if right(secuencia, 3) = jugador then print: print "¡Felicidades! ¡Ganaste!": winner = TRUE
if right(secuencia, 3) = computador then print: print "¡Yo gano!": winner = TRUE
until winner
do
valido = FALSE
print
input "¿Otra partida? (S/N) ", otra
if instr("SsNn", otra) then valido = TRUE
until valido
until upper(otra) = "N"
print "¡Gracias por jugar!"
end
</syntaxhighlight>
 
 
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
<langsyntaxhighlight lang="basic"> 10 IF RND>=.5 THEN GOTO 100
20 PRINT "YOU PICK FIRST."
30 INPUT P$
Line 145 ⟶ 452:
290 PRINT "YOU WIN"
300 STOP
310 PRINT "I WIN"</langsyntaxhighlight>
{{out}}
<pre>YOU PICK FIRST.
Line 156 ⟶ 463:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">::
::Penney's Game Task from Rosetta Code Wiki
::Batch File Implementation
Line 258 ⟶ 565:
if /i "!you_bet!"=="%cpu_bet%" (echo [Bet something different...]&echo.&goto %1)
for %%i in ("t=T" "h=H") do set "you_bet=!you_bet:%%~i!"
goto :EOF</langsyntaxhighlight>
{{out}}
Note: The outputs of tosses are 'delayed' just to make the game a little more dramatic.
Line 299 ⟶ 606:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">REM >penney
PRINT "*** Penney's Game ***"
REPEAT
Line 379 ⟶ 686:
ELSE
= "H" + LEFT$(sequence$, 2)
ENDIF</langsyntaxhighlight>
{{out}}
<pre>*** Penney's Game ***
Line 406 ⟶ 713:
=={{header|C}}==
This solution stores the sequences in bit-packed integers. With minor adjustments, this can be extended to allow larger sequence lengths beyond the required 3. However, the ai's algorithm for the perfect choice would need to be altered. More robust methods of input could be chosen, as scanf is generally fairly unsafe. A safer alternative would be to use something like fgets, and parse the input string ourselves.
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 528 ⟶ 835:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 550 ⟶ 857:
=={{header|C sharp}}==
{{works with|C sharp|7}}
<langsyntaxhighlight lang="csharp">using static System.Console;
using static System.Threading.Thread;
using System;
Line 653 ⟶ 960:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 681 ⟶ 988:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <time.h>
#include <iostream>
Line 768 ⟶ 1,075:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 787 ⟶ 1,094:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns penney.core
(:gen-class))
 
Line 850 ⟶ 1,157:
(println "Penney's Game.")
(play-game {:first-player (flip-coin)
:human 0, :computer 0}))</langsyntaxhighlight>
 
{{out}}
Line 879 ⟶ 1,186:
Thanks for playing!
</pre>
 
=={{header|Common Lisp}}==
{{trans|UNIX Shell}}
<syntaxhighlight lang="lisp">(setf *random-state* (make-random-state t))
 
(defparameter *heads* #\H)
(defparameter *tails* #\T)
 
(defun main ()
(format t "Penney's Game~%~%")
(format t "Flipping to see who goes first ...")
 
(setq p2 nil)
(if (string= (flip) *heads*)
(progn (format t " I do.~%")
(setq p2 (choose-random-sequence))
(format t "I choose: ~A~%" p2))
(format t "You do.~%"))
 
(setq p1 nil)
(loop while (null p1) doing
(format t "Enter your three-flip sequence: ")
(setq p1 (string (read)))
(cond ((/= (length p1) 3)
(format t "Sequence must consist of three flips.~%")
(setq p1 nil))
((string= p1 p2)
(format t "Sequence must be different from mine.~%")
(setq p1 nil))
((notevery #'valid? (coerce p1 'list))
(format t "Sequence must be contain only ~A's and ~A's.~%" *heads* *tails*)
(setq p1 nil))))
(format t "You picked: ~A~%" p1)
 
(if (null p2)
(progn
(setq p2 (choose-optimal-sequence p1))
(format t "I choose: ~A~%" p2)))
 
(format t "Here we go. ~A, you win; ~A, I win.~%" p1 p2)
(format t "Flips:")
(let ((winner nil)
(flips '()))
(loop while (null winner) doing
(setq flips (cons (flip) flips))
(format t " ~A" (car flips))
(if (>= (length flips) 3)
(let ((trail (coerce (reverse (subseq flips 0 3)) 'string)))
(cond ((string= trail p1) (setq winner "You"))
((string= trail p2) (setq winner "I"))))))
(format t "~&~A win!" winner)))
 
(defparameter *sides* (list *heads* *tails*))
(defun flip () (nth (random 2 *random-state*) *sides*))
 
(defun valid? (flip) (not (null (member flip *sides*))))
 
(defun opposite (flip) (if (string= flip *heads*) *tails* *heads*))
 
(defun choose-random-sequence () (coerce (list (flip) (flip) (flip)) 'string))
 
(defun choose-optimal-sequence (against)
(let* ((opposed (coerce against 'list))
(middle (cadr opposed))
(my-list (list (opposite middle) (car opposed) middle)))
(coerce my-list 'string)))
 
(main)</syntaxhighlight>
 
{{Out}}
Computer player first:
<pre>Penney's Game
 
Flipping to see who goes first ... I do.
I choose: THH
Enter your three-flip sequence: TTH
You picked: TTH
Here we go. TTH, you win; THH, I win.
Flips: T T T H
You win!</pre>
 
Human player first:
<pre>Penney's Game
 
Flipping to see who goes first ...You do.
Enter your three-flip sequence: HTT
You picked: HTT
I choose: HHT
Here we go. HTT, you win; HHT, I win.
Flips: H T T
You win!</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.algorithm, std.string,
std.conv, std.range, core.thread;
Line 916 ⟶ 1,314:
Thread.sleep(1.seconds);
}
}</langsyntaxhighlight>
The output is the same as the Python entry.
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Penney do
@toss [:Heads, :Tails]
Line 977 ⟶ 1,375:
end
 
Penney.game</langsyntaxhighlight>
 
{{out}}
Line 1,003 ⟶ 1,401:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays ascii io kernel math prettyprint random sequences
strings ;
IN: rosetta-code.penneys-game
Line 1,090 ⟶ 1,488:
[ computer-first human-second ] if flip-coins ;
start-game</langsyntaxhighlight>
{{out}}
<pre>
Line 1,138 ⟶ 1,536:
The computer won.
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="freebasic">
Sub Jugador_elige(secuencia As String)
Dim As String eleccion
Dim As Byte valido, i
Do
valido = True
Print !"\nIngresa una secuencia de 3 opciones, cada una de ellas H o T:";
Input " > ", secuencia
If Len(secuencia) <> 3 Then valido = False
If valido Then
For i = 1 To 3
eleccion = Mid(Ucase(secuencia), i, 1)
If eleccion <> "H" And eleccion <> "T" Then valido = False
Next
End If
Loop Until valido
End Sub
 
Function Aleatorio() As String
Dim As Byte eleccion, i
Dim As String tirada
tirada = ""
For i = 1 To 3
eleccion = Rnd And 1
If eleccion Then tirada += "H" Else tirada += "T"
Next
Return tirada
End Function
 
Function Optima(secuencia As String) As String
If Mid(secuencia, 2, 1) = "H" Then
Optima = "T" + Left(secuencia, 2)
Else
Optima = "H" + Left(secuencia, 2)
End If
End Function
 
Randomize Timer
Dim As String jugador, computador, otro
Dim Shared As String secuencia
Dim As Boolean ganador, valido
Do
Cls
Color 11
Print "*** Penney's Game ***" & Chr(10)
Color 7
Print "Cara eliges primero, cruz yo elijo primero."
Print "Y es... ";
Sleep 300
Dim As Double ht: ht = Rnd(0 - Timer) And 1
If ht Then
Print "­cara!"
Jugador_elige(jugador)
computador = Optima(jugador)
Print !"\nYo elijo "; computador; !".\n"
Else
Print "­cruz!"
computador = Aleatorio
Print !"\nYo elijo "; computador; !".\n"
Jugador_elige(jugador)
End If
Print "Comenzando el juego ..."
secuencia = ""
ganador = False
Do
Sleep 200
Dim As Integer lanzar = Rnd And 1
If lanzar Then
secuencia += "H"
Print "H ";
Else
Print "T ";
secuencia += "T"
End If
If Right(secuencia, 3) = computador Then
Print !"\n­Gan‚!\n"
ganador = True
Else
If Right(secuencia, 3) = jugador Then
Print !"\n­Felicidades! Ganaste.\n"
ganador = True
End If
End If
Loop Until ganador
Do
valido = False
Input "¨Otra ronda? (S/N) ", otro
If Instr("SYN", Ucase(otro)) Then valido = True
Loop Until valido
Loop Until Ucase(otro) = "N"
Print !"\n­Gracias por jugar!"
Sleep
End
</syntaxhighlight>
 
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang Go>
package main
import "fmt"
Line 1,228 ⟶ 1,726:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,243 ⟶ 1,741:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import qualified Data.List as L
import System.IO
import System.Random
Line 1,333 ⟶ 1,831:
stdgen <- getStdGen
let (cpuFirst, genA) = random stdgen
game cpuFirst 0 0 genA</langsyntaxhighlight>
{{out}}
<pre>
Line 1,356 ⟶ 1,854:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight Jlang="j">require 'format/printf numeric'
 
randomize '' NB. randomize seed for new session
Line 1,383 ⟶ 1,881:
'Toss sequence is %s' printf < (3 + <./ Result) {. Tosses
echo ('No result';'You win!';'Computer won!') {::~ *-/ Result
)</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight Jlang="j"> playPenney''
Computer chose TTT
Choose a sequence of three coin tosses (H/T):
Line 1,396 ⟶ 1,894:
Computer chose HHT
Toss sequence is HTHTT
You win!</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.*;
 
public class PenneysGame {
Line 1,450 ⟶ 1,948:
return s;
}
}</langsyntaxhighlight>
 
<pre>Computer chooses HTH
Line 1,471 ⟶ 1,969:
=={{header|Julia}}==
'''Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
const SLEN = 3
 
Line 1,504 ⟶ 2,002:
return b
end
</syntaxhighlight>
</lang>
 
'''Game Setup'''
<syntaxhighlight lang="julia">
<lang Julia>
println("Playing Penney's Game Against the computer.")
 
Line 1,522 ⟶ 2,020:
print(@sprintf "You bet %s " pgdecode(human))
println(@sprintf "and the computer bet %s." pgdecode(mach))
</syntaxhighlight>
</lang>
 
'''Game Play'''
<syntaxhighlight lang="julia">
<lang Julia>
pg = randbool(SLEN)
pgtail = copy(pg)
Line 1,543 ⟶ 2,041:
println("so you won.")
end
</syntaxhighlight>
</lang>
 
{{output}}
Line 1,596 ⟶ 2,094:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import java.util.Random
Line 1,665 ⟶ 2,163:
}
}
</syntaxhighlight>
</lang>
 
Sample game where computer goes first:
Line 1,702 ⟶ 2,200:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function penny_game()
local player, computer = "", ""
Line 1,791 ⟶ 2,289:
r = io.read()
until( r == "N" or r == "n" )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,817 ⟶ 2,315:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">randomTorH = function()
if rnd < 0.5 then return "T" else return "H"
end function
Line 1,846 ⟶ 2,344:
end if
wait
end while</langsyntaxhighlight>
 
{{out}}
Line 1,872 ⟶ 2,370:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight Nimlang="nim">import os, random, sequtils, strutils
 
randomize()
Line 1,904 ⟶ 2,402:
echo "\n I win!"
break
sleep(1000)</langsyntaxhighlight>
 
{{out}}
Line 1,915 ⟶ 2,413:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">PROGRAM Penney;
 
TYPE
Line 2,110 ⟶ 2,608:
readln
 
END.</langsyntaxhighlight>
 
{{out}}
Line 2,172 ⟶ 2,670:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">
#!usr/bin/perl
use 5.020;
Line 2,283 ⟶ 2,781:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,306 ⟶ 2,804:
{{trans|C}}
Robert's robot's name is Robort.
<langsyntaxhighlight Phixlang="phix">function trio(integer pick)
return substitute_all(sprintf("%03b",pick),"10","HT")
end function
Line 2,385 ⟶ 2,883:
end procedure
main()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,434 ⟶ 2,932:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(seed (in "/dev/urandom" (rd 8)))
 
(setq *S (list 0 0))
Line 2,478 ⟶ 2,976:
(= "N" (uppc (in NIL (char)))) ) ) ) )
 
(go)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,516 ⟶ 3,014:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">play :- rand1(R), game(R).
 
game(h) :-
Line 2,552 ⟶ 3,050:
coin(0,h). coin(1,t).
coin_s(h, 'H'). coin_s(t, 'T').
opp(h, t). opp(t, h).</langsyntaxhighlight>
Output:
Line 2,572 ⟶ 3,070:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from __future__ import print_function
import random
from time import sleep
Line 2,601 ⟶ 3,099:
print('\n I win!')
break
sleep(1) # For dramatic effect</langsyntaxhighlight>
 
{{out}}
Line 2,618 ⟶ 3,116:
You win!
>>> </pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ 2 random iff char H else char T ] is flip ( --> c )
 
[ 3 times flip join join ] is randstart ( --> $ )
 
[ -1 split drop
dup -1 peek
char T = iff char H else char T
swap join ] is beststart ( $ --> $ )
 
[ stack ] is playergoal ( --> s )
[ stack ] is computergoal ( --> s )
 
[ say "This is Penney's game."
cr cr
say "We each guess a different "
say "sequence of three coin "
say "flips."
cr
say "I will releatedly flip "
say "a coin until one of the "
say "sequences happens."
cr
say "The winner is the one who "
say "guesses the sequence that "
say "happens first."
cr cr
say "Please enter your sequence "
say "carefully as there is no "
say "error checking."
cr
say 'For example, for "heads '
say 'tails heads" type "HTH".'
cr cr ] is intro ( --> )
 
[ intro
randomise
flip char H = iff
[ say "I start. My guess is: "
randstart dup echo$
computergoal put
cr
$ "Please enter your guess: "
input playergoal put ]
else
[ say "You start. "
$ "Please enter your guess: "
input dup playergoal put
beststart dup
say "I guess: " echo$
computergoal put
cr ]
cr
$ ""
[ flip join
dup -3 split nip dup
computergoal share = iff
[ drop say "I win." ] done
playergoal share = iff
[ say "You win." ] done
again ]
cr
say "The complete sequence was: "
echo$ cr
computergoal release
playergoal release ] is play ( --> )</syntaxhighlight>
 
{{out}}
As a dialogue in the Quackery shell (REPL).
 
<pre>/O> play
...
This is Penney's game.
 
We each guess a different sequence of three coin flips.
I will releatedly flip a coin until one of the sequences happens.
The winner is the one who guesses the sequence that happens first.
 
Please enter your sequence carefully as there is no error checking.
For example, for "heads tails heads" type "HTH".
 
You start. Please enter your guess: HTH
I guess: HHT
 
You win.
The complete sequence was: TTHTH
 
Stack empty.
 
/O> play
...
This is Penney's game.
 
We each guess a different sequence of three coin flips.
I will releatedly flip a coin until one of the sequences happens.
The winner is the one who guesses the sequence that happens first.
 
Please enter your sequence carefully as there is no error checking.
For example, for "heads tails heads" type "HTH".
 
I start. My guess is: HTT
Please enter your guess: HHT
 
You win.
The complete sequence was: HTHTHHHT
 
Stack empty.
 
/O> </pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">#===============================================================
# Penney's Game Task from Rosetta Code Wiki
# R implementation
Line 2,683 ⟶ 3,292:
}
}
</syntaxhighlight>
</lang>
{{out}}
Human first.
Line 2,724 ⟶ 3,333:
This does what's required of it from the task... just don't input anything outside the alphabet "htHT" for the human move.
 
<langsyntaxhighlight lang="racket">#lang racket
;; Penney's Game. Tim Brown 2014-10-15
(define (flip . _) (match (random 2) (0 "H") (1 "T")))
Line 2,760 ⟶ 3,369:
(printf "~a chooses: ~a~%" (car p1) (flips->string (cdr p1)))
(values p1 (cons 'Hom-Sap (get-human-sequence)))]))
(printf "~a wins!~%" (game-on player-1 player-2)))</langsyntaxhighlight>
 
{{out}}
Line 2,799 ⟶ 3,408:
{{works with|Rakudo|2018.02}}
 
<syntaxhighlight lang="raku" perl6line>enum Coin <Heads Tails>;
enum Yay <Yay Good Super Hah Ooh Yipee Sweet Cool Yes Haha>;
enum Boo <Drat Darn Crumb Oops Rats Bah Criminy Argh Shards>;
Line 2,870 ⟶ 3,479:
print "$_ ";
}
}</langsyntaxhighlight>
{{out}}
Note: the actual run displays a little coin-flipping animation, but that won't show up here:
Line 2,920 ⟶ 3,529:
 
A feature also added was to allow a seed for the &nbsp; '''random''' &nbsp; BIF to allow repeatability for a game.
<langsyntaxhighlight lang="rexx">/*REXX program plays/simulates Penney's Game, a two─player coin toss sequence game. */
__= copies('─', 9) /*literal for eye─catching fence. */
signal on halt /*a clean way out if CLBF quits. */
Line 2,987 ⟶ 3,596:
do until g\==@.CBLF!; g= r(#); end /*otherwise, generate a choice. */
@.comp= translate(g, 'HT', 10)
return</langsyntaxhighlight>
{{out|output|text=&nbsp; of a six-game session &nbsp; (ended by user entering a '''quit'''):}}
<pre>
Line 3,097 ⟶ 3,706:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">Toss = [:Heads, :Tails]
 
def yourChoice
Line 3,131 ⟶ 3,740:
print " #{seq[-1]}"
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,150 ⟶ 3,759:
Heads Heads Tails Heads Tails Heads Tails Tails Tails Tails Tails Tails Tails Heads Heads
You win!
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
extern crate rand;
 
use std::io::{stdin, stdout, Write};
use std::thread;
use std::time::Duration;
 
use rand::Rng;
 
fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char {
let c = if rng.gen() { 'H' } else { 'T' };
if print {
print!("{}", c);
stdout().flush().expect("Could not flush stdout");
}
c
}
 
fn gen_sequence<R: Rng>(rng: &mut R, seed: Option<&str>) -> String {
let mut seq = String::new();
match seed {
Some(s) => {
let mut iter = s.chars();
let c0 = iter.next().unwrap();
let next = if c0 == 'H' { 'T' } else { 'H' };
seq.push(next);
seq.push(c0);
seq.push(iter.next().unwrap());
}
None => {
for _ in 0..3 {
seq.push(toss_coin(rng, false))
}
}
}
seq
}
 
fn read_sequence(used_seq: Option<&str>) -> String {
let mut seq = String::new();
loop {
seq.clear();
println!("Please, enter sequence of 3 coins: H (heads) or T (tails): ");
stdin().read_line(&mut seq).expect("failed to read line");
seq = seq.trim().to_uppercase();
// do the cheapest test first
if seq.len() == 3
&& seq.chars().all(|c| c == 'H' || c == 'T')
&& seq != used_seq.unwrap_or("")
{
return seq;
}
 
println!("Please enter correct sequence!");
}
}
 
fn main() {
let mut rng = rand::thread_rng();
 
println!("--Penney's game--");
loop {
let useq: String;
let aiseq: String;
if rng.gen::<bool>() {
println!("You choose first!");
useq = read_sequence(None);
println!("Your sequence: {}", useq);
aiseq = gen_sequence(&mut rng, Some(&useq));
println!("My sequence: {}", aiseq);
} else {
println!("I choose first!");
aiseq = gen_sequence(&mut rng, None);
println!("My sequence: {}", aiseq);
useq = read_sequence(Some(&aiseq));
println!("Your sequence: {}", useq);
}
println!("Tossing coins...");
let mut coins = String::new();
for _ in 0..2 {
// toss first 2 coins
coins.push(toss_coin(&mut rng, true));
thread::sleep(Duration::from_millis(500));
}
loop {
coins.push(toss_coin(&mut rng, true));
thread::sleep(Duration::from_millis(500));
if coins.contains(&useq) {
println!("\nYou win!");
break;
}
if coins.contains(&aiseq) {
println!("\nI win!");
break;
}
}
 
println!(" Play again? 'Y' to play, 'Q' to exit.");
let mut input = String::new();
stdin().read_line(&mut input).expect("failed to read line");
match input.trim_start().chars().next().unwrap() {
'Y' | 'y' => continue,
_ => break,
}
}
}
 
</syntaxhighlight>
{{out}}
<pre>
--Penney's game--
You choose first!
Please, enter sequence of 3 coins: H (heads) or T (tails):
hht
Your sequence: HHT
My sequence: THH
Tossing coins...
TTTTHTTHTHTHTTTHH
I win!
Play again? 'Y' to play, 'Q' to exit.
</pre>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create Player {
Line 3,251 ⟶ 3,983:
}
 
game 3 HumanPlayer RobotPlayer</langsyntaxhighlight>
{{out|Sample Game}}
<!-- Huh! This was a long one… -->
Line 3,284 ⟶ 4,016:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<langsyntaxhighlight lang="sh">#!/bin/bash
main() {
echoprintf "$'Penney\'s Game"\n\n'
echoprintf -n "'Flipping to see who goes first ... "'
 
if [[ $(flip) == H ]]; then
echoprintf "'I do."\n'
p2=$(choose_sequence)
echoprintf "'I choose: %s\n' "$p2"
else
echoprintf "'You do."\n'
fi
 
while true; do
echoread "-p 'Enter your three-flip sequence:" ' p1
readp1=$(tr a-z A-Z <<<"$p1")
case "$p1" in
"$p2") echoprintf "'Sequence must be different from mine"\n';;
[hHTtHT][hHtTHT][hHtTHT]) break;;
*) echoprintf "$'Sequence must be three H\'s or T\'s"\n';;
esac
done
p1=$(tr a-z A-Z <<<"$p1")
 
if [ -z "$p2" ]; then
p2=$(choose_sequence "$p1")
echoprintf "'I choose: %s\n' "$p2"
fi
 
printf '\nHere we go. %s, you win; %s, I win.\n' "$p1" "$p2"
echo
printf 'Flips:'
echo "Here we go. $p1, you win; $p2, I win."
flips=
 
flips=
while true; do
flip=$(flip)
echoprintf -n' %s' "$flip"
flips+=$flip
while (( ${#flips} > 3 )); do
flips="${flips#?}"
done
case "$flips" in
*$p1) echoprintf $'\nYou win!\n'; exit 0;;
*$p2) echoprintf $'\nI win!\n'; exit 1;;
esac
done
Line 3,335 ⟶ 4,063:
if (( $# )); then
case "$1" in
?[Hh]?) result=T;;
*) result=H;;
esac
Line 3,342 ⟶ 4,070:
result=$(flip)$(flip)$(flip)
fi
echoprintf '%s\n' "$result"
}
 
flip() {
if (( RANDOM % 2 )); then
echoprintf '%s\n' H
else
echoprintf '%s\n' T
fi
}
 
main "$@"</lang>
</syntaxhighlight>
 
{{Output}}
Line 3,368 ⟶ 4,097:
 
Human first:
<pre>penneyPenney's Game
 
Penney's Game
Flipping to see who goes first ... I do.
I choose: HHH
Enter your three-flip sequence: THH
 
Here we go. THH, you win; HHH, I win.
Flips: H H T H H
You win!</pre>
 
Human first:
<pre>Penney's Game
 
Flipping to see who goes first ... You do.
Enter your three-flip sequence: THH
I choose: TTH
HTH
I choose: HHT
 
Here we go. HTHTHH, you win; HHTTTH, I win.
Flips: H H T T T H
HHHT
I win!</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 3,461 ⟶ 4,200:
End If
End If
End Function</langsyntaxhighlight>
{{out}}
<pre>You start
Line 3,482 ⟶ 4,221:
 
Game over</pre>
 
=={{header|V (Vlang)}}==
{{trans|Kotlin}}
<syntaxhighlight lang="v (vlang)">
import rand
import os
import time
 
const optimum = {
"HHH": "THH", "HHT": "THH", "HTH": "HHT", "HTT": "HHT",
"THH": "TTH", "THT": "TTH", "TTH": "HTT", "TTT": "HTT"
}
 
fn main() {
r := rand.intn(2) or {exit(1)}
mut user_seq :=''
mut comp_seq :=''
mut coin :=''
mut coins :=''
mut len := 0
mut seq :=''
 
if r == 0 {
println("You go first")
user_seq = user_sequence()
println('\n')
comp_seq = computer_sequence(user_seq)
}
else {
println("Computer goes first")
comp_seq = computer_sequence(user_seq)
println('\n')
user_seq = user_sequence()
}
println('\n')
for true {
if (rand.intn(2) or {exit(1)}) == 0 {coin = 'H'} else {coin = 'T'}
coins += coin
println("Coins flipped: $coins")
len = coins.len
if len >= 3 {
seq = coins.substr(len - 3, len)
if seq == user_seq {
println("\nYou win!")
exit(0)
}
if seq == comp_seq {
println("\nComputer wins!")
exit(0)
}
}
time.sleep(1 * time.second) // extraneous
}
}
 
fn user_sequence() string {
mut user_seq :=''
println("A sequence of three H or T should be entered")
for (user_seq.len != 3) || (user_seq.to_upper().split('').any(it != 'H' && it != 'T') == true) {
user_seq = os.input('Enter your sequence: ').str().to_upper()
}
return user_seq
}
 
fn computer_sequence(user_seq string) string {
mut char_array := []string{len:3}
mut comp_seq :=''
if user_seq == '' {
for _ in 0..2 {
if (rand.intn(2) or {exit(1)}) == 0 {char_array << 'T'} else {char_array << 'H'}
comp_seq = char_array.join('')
}
}
else {
comp_seq = optimum[user_seq]
}
println("Computer's sequence: $comp_seq")
return comp_seq
}
</syntaxhighlight>
 
{{out}}
<pre>
Computer goes first
Computer's sequence: TH
 
 
A sequence of three H or T should be entered
Enter your sequence: thh
 
 
Coins flipped: H
Coins flipped: HT
Coins flipped: HTT
Coins flipped: HTTH
Coins flipped: HTTHT
Coins flipped: HTTHTH
Coins flipped: HTTHTHT
Coins flipped: HTTHTHTT
Coins flipped: HTTHTHTTH
Coins flipped: HTTHTHTTHT
Coins flipped: HTTHTHTTHTH
Coins flipped: HTTHTHTTHTHT
Coins flipped: HTTHTHTTHTHTH
Coins flipped: HTTHTHTTHTHTHT
Coins flipped: HTTHTHTTHTHTHTH
Coins flipped: HTTHTHTTHTHTHTHH
 
You win!
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "io" for Stdin, Stdout
import "timer" for Timer
import "./str" for Str
 
var rand = Random.new()
Line 3,555 ⟶ 4,404:
}
Timer.sleep(2000) // wait two seconds for next flip
}</langsyntaxhighlight>
 
{{out}}
Line 3,591 ⟶ 4,440:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn coinToss{ (0).random(2) and "H" or "T" } // (0).random(2) --> 0<=r<2
reg myBet, yourBet;
if(coinToss()=="H"){ // The toss says I go first
Line 3,608 ⟶ 4,457:
if(Void!=coins.find(myBet)) { println(" I win!"); break; }
// ignore we both won
}</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits