Created
June 1, 2017 14:44
-
-
Save luelista/ab6a3139b32a736d14b4b3b9ebf0ca65 to your computer and use it in GitHub Desktop.
Rock Paper Scissors Lizard Spock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
CHOICES="Rock Paper Scissors Lizard Spock" | |
check_rule() { | |
user="$1"; computer="$2"; draw="yes" | |
while read rulestr ; do | |
rule="$rulestr" | |
winner="${rule%% *}"; rule="${rule#* }" | |
verb="${rule%% *}"; rule="${rule#* }" | |
loser="${rule%% *}"; rule="${rule#* }" | |
if [ \( "$user" = "$winner" \) -a \( "$computer" = "$loser" \) ]; then | |
echo "$rulestr. You win!" | |
USER_WINS=$(($USER_WINS+1)) | |
draw="" | |
elif [ \( "$user" = "$loser" \) -a \( "$computer" = "$winner" \) ]; then | |
echo "$rulestr. You lose!" | |
COMPUTER_WINS=$(($COMPUTER_WINS+1)) | |
draw="" | |
fi | |
done <<RULEZ | |
Scissors cuts Paper | |
Paper covers Rock | |
Rock crushes Lizard | |
Lizard poisons Spock | |
Spock smashes Scissors | |
Scissors decapitates Lizard | |
Lizard eats Paper | |
Paper disproves Spock | |
Spock vaporizes Rock | |
Rock crushes Scissors | |
RULEZ | |
if [ -n "$draw" ]; then | |
echo "It's a draw." | |
DRAW_COUNT=$(($DRAW_COUNT+1)) | |
fi | |
} | |
ask_user_choice() { | |
i=0 | |
for choice in $CHOICES; do | |
i=$((i+1)) | |
echo "$i. $choice" | |
done | |
choice="" | |
while [ -z "$choice" ]; do | |
echo -n "Choose your choice [1-5]: " | |
read choice_index | |
get_choice_by_index "$choice_index" | |
done | |
user_choice="$choice" | |
} | |
get_choice_by_index() { | |
choice_index="$1" | |
i=0 | |
for choice in $CHOICES; do | |
i=$(($i+1)) | |
if [ "$i" -eq "$choice_index" ]; then | |
return | |
fi | |
done | |
choice="" | |
} | |
random_choice() { | |
rand=`awk 'BEGIN{srand();print int(rand()*5)+1}'` | |
get_choice_by_index "$rand" | |
} | |
show_stats_and_exit() { | |
echo "" | |
echo "*** STATISTICS ***" | |
echo "You played $GAME_COUNT times" | |
echo "You won $USER_WINS times" | |
echo "Computer won $COMPUTER_WINS times" | |
echo "We had $DRAW_COUNT draws" | |
echo "" | |
echo "Bye." | |
exit 0 | |
} | |
GAME_COUNT=0; COMPUTER_WINS=0; USER_WINS=0; DRAW_COUNT=0 | |
trap show_stats_and_exit INT | |
echo "Welcome to $CHOICES" | |
echo "Enter your choice to play, press CTRL+C to exit." | |
echo "" | |
while true; do | |
random_choice; computer_choice="$choice" | |
ask_user_choice | |
GAME_COUNT=$(($GAME_COUNT+1)) | |
echo "" | |
echo "You chose $user_choice, computer chose $computer_choice." | |
check_rule "$user_choice" "$computer_choice" | |
echo "" | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment