Penney's game: Difference between revisions
Content added Content deleted
(Penney's game en BASIC256) |
(→{{header|UNIX Shell}}: Correct logic.) |
||
Line 3,586: | Line 3,586: | ||
<lang sh>#!/bin/bash |
<lang sh>#!/bin/bash |
||
main() { |
main() { |
||
printf $'Penney\'s Game\n\n' |
|||
printf 'Flipping to see who goes first ... ' |
|||
if [[ $(flip) == H ]]; then |
if [[ $(flip) == H ]]; then |
||
printf 'I do.\n' |
|||
p2=$(choose_sequence) |
p2=$(choose_sequence) |
||
printf 'I choose: %s\n' "$p2" |
|||
else |
else |
||
printf 'You do.\n' |
|||
fi |
fi |
||
while true; do |
while true; do |
||
read -p 'Enter your three-flip sequence: ' p1 |
|||
p1=$(tr a-z A-Z <<<"$p1") |
|||
case "$p1" in |
case "$p1" in |
||
"$p2") |
"$p2") printf 'Sequence must be different from mine\n';; |
||
[ |
[HT][HT][HT]) break;; |
||
*) |
*) printf $'Sequence must be three H\'s or T\'s\n';; |
||
esac |
esac |
||
done |
done |
||
p1=$(tr a-z A-Z <<<"$p1") |
|||
if [ -z "$p2" ]; then |
if [ -z "$p2" ]; then |
||
p2=$(choose_sequence "$p1") |
p2=$(choose_sequence "$p1") |
||
printf 'I choose: %s\n' "$p2" |
|||
fi |
fi |
||
⚫ | |||
echo |
|||
printf 'Flips:' |
|||
⚫ | |||
⚫ | |||
⚫ | |||
while true; do |
while true; do |
||
flip=$(flip) |
flip=$(flip) |
||
printf ' %s' "$flip" |
|||
flips+=$flip |
flips+=$flip |
||
while (( ${#flips} > 3 )); do |
|||
flips="${flips#?}" |
|||
done |
|||
case "$flips" in |
case "$flips" in |
||
*$p1) |
*$p1) printf $'\nYou win!\n'; exit 0;; |
||
*$p2) |
*$p2) printf $'\nI win!\n'; exit 1;; |
||
esac |
esac |
||
done |
done |
||
Line 3,635: | Line 3,631: | ||
if (( $# )); then |
if (( $# )); then |
||
case "$1" in |
case "$1" in |
||
?Hh?) result=T;; |
?[Hh]?) result=T;; |
||
*) result=H;; |
*) result=H;; |
||
esac |
esac |
||
Line 3,642: | Line 3,638: | ||
result=$(flip)$(flip)$(flip) |
result=$(flip)$(flip)$(flip) |
||
fi |
fi |
||
printf '%s\n' "$result" |
|||
} |
} |
||
flip() { |
flip() { |
||
if (( RANDOM % 2 )); then |
if (( RANDOM % 2 )); then |
||
printf '%s\n' H |
|||
else |
else |
||
printf '%s\n' T |
|||
fi |
fi |
||
} |
} |
||
main "$@" |
main "$@" |
||
</lang> |
|||
{{Output}} |
{{Output}} |
||
Line 3,668: | Line 3,665: | ||
Human first: |
Human first: |
||
<pre> |
<pre>Penney's Game |
||
⚫ | |||
Flipping to see who goes first ... I do. |
|||
⚫ | |||
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: |
|||
⚫ | |||
Flipping to see who goes first ... You do. |
Flipping to see who goes first ... You do. |
||
Enter your three-flip sequence: |
Enter your three-flip sequence: THH |
||
I choose: TTH |
|||
HTH |
|||
⚫ | |||
Here we go. |
Here we go. THH, you win; TTH, I win. |
||
Flips: H H T T T H |
|||
HHHT |
|||
I win!</pre> |
I win!</pre> |
||