Penney's game: Difference between revisions

(Penney's game en BASIC256)
(→‎{{header|UNIX Shell}}: Correct logic.)
Line 3,586:
<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
 
echoprintf "Here'\nHere we go. $p1%s, you win; $p2%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,635 ⟶ 3,631:
if (( $# )); then
case "$1" in
?[Hh]?) result=T;;
*) result=H;;
esac
Line 3,642 ⟶ 3,638:
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>
</lang>
 
{{Output}}
Line 3,668 ⟶ 3,665:
 
Human first:
<pre>penneyPenney's Game
 
Penney's Game
Flipping to see who goes first ... I do.
I choose: HHTHHH
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>
 
1,480

edits