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() {
echo "Penney's Game"
printf $'Penney\'s Game\n\n'
echo -n "Flipping to see who goes first ... "
printf 'Flipping to see who goes first ... '


if [[ $(flip) == H ]]; then
if [[ $(flip) == H ]]; then
echo "I do."
printf 'I do.\n'
p2=$(choose_sequence)
p2=$(choose_sequence)
echo "I choose: $p2"
printf 'I choose: %s\n' "$p2"
else
else
echo "You do."
printf 'You do.\n'
fi
fi


while true; do
while true; do
echo "Enter your three-flip sequence:"
read -p 'Enter your three-flip sequence: ' p1
read p1
p1=$(tr a-z A-Z <<<"$p1")
case "$p1" in
case "$p1" in
"$p2") echo "Sequence must be different from mine";;
"$p2") printf 'Sequence must be different from mine\n';;
[hHTt][hHtT][hHtT]) break;;
[HT][HT][HT]) break;;
*) echo "Sequence must be three H's or T's";;
*) 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")
echo "I choose: $p2"
printf 'I choose: %s\n' "$p2"
fi
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
while true; do
flip=$(flip)
flip=$(flip)
echo -n $flip
printf ' %s' "$flip"
flips+=$flip
flips+=$flip
while (( ${#flips} > 3 )); do
flips="${flips#?}"
done
case "$flips" in
case "$flips" in
*$p1) echo $'\nYou win!'; exit 0;;
*$p1) printf $'\nYou win!\n'; exit 0;;
*$p2) echo $'\nI win!'; exit 1;;
*$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
echo "$result"
printf '%s\n' "$result"
}
}


flip() {
flip() {
if (( RANDOM % 2 )); then
if (( RANDOM % 2 )); then
echo H
printf '%s\n' H
else
else
echo T
printf '%s\n' T
fi
fi
}
}


main "$@"</lang>
main "$@"
</lang>


{{Output}}
{{Output}}
Line 3,668: Line 3,665:


Human first:
Human first:
<pre>penney
<pre>Penney'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.
Flipping to see who goes first ... You do.
Enter your three-flip sequence:
Enter your three-flip sequence: THH
I choose: TTH
HTH
I choose: HHT


Here we go. HTH, you win; HHT, I win.
Here we go. THH, you win; TTH, I win.
Flips: H H T T T H
HHHT
I win!</pre>
I win!</pre>