awk Rock-Paper-Scissors
Rock-Paper-Scissors
Rock-paper-scissors is a popular hand game in which each player simultaneously forms one of three shapes with an outstretched hand. We create this game in AWK.
# This program creates a rock-paper-scissors game.
BEGIN {
srand()
opts[1] = "rock"
opts[2] = "paper"
opts[3] = "scissors"
do {
print "1 - rock"
print "2 - paper"
print "3 - scissors"
print "9 - end game"
ret = getline < "-"
if (ret == 0 || ret == -1) {
exit
}
val = $0
if (val == 9) {
exit
} else if (val != 1 && val != 2 && val != 3) {
print "Invalid option"
continue
} else {
play_game(val)
}
} while (1)
}
function play_game(val) {
r = int(rand()*3) + 1
print "I have " opts[r] " you have " opts[val]
if (val == r) {
print "Tie, next throw"
return
}
if (val == 1 && r == 2) {
print "Paper covers rock, you loose"
} else if (val == 2 && r == 1) {
print "Paper covers rock, you win"
} else if (val == 2 && r == 3) {
print "Scissors cut paper, you loose"
} else if (val == 3 && r == 2) {
print "Scissors cut paper, you win"
} else if (val == 3 && r == 1) {
print "Rock blunts scissors, you loose"
} else if (val == 1 && r == 3) {
print "Rock blunts scissors, you win"
}
}
We play the game against the computer, which chooses its options randomly.
srand()
We seed the random number generator with the srand()
function.
opts[1] = "rock"
opts[2] = "paper"
opts[3] = "scissors"
The three options are stored in the opts array.
do {
print "1 - rock"
print "2 - paper"
print "3 - scissors"
print "9 - end game"
...
The cycle of the game is controlled by the do-while loop. First, the options are printed to the terminal.
ret = getline < "-"
if (ret == 0 || ret == -1) {
exit
}
val = $0
A value, our choice, is read from the command line using the getline
command; the value is stored in the val
variable.
if (val == 9) {
exit
} else if (val != 1 && val != 2 && val != 3) {
print "Invalid option"
continue
} else {
play_game(val)
}
We exit the program if we choose option 9. If the value is outside the printed menu options, we print an error message and start a new loop with the continue
command. If we have choosen one of the three options correctly, we call the play_game()
function.
r = int(rand()*3) + 1
A random value from 1..3 is chosen with the rand()
function. This is the choice of the computer.
if (val == r) {
print "Tie, next throw"
return
}
In case both players choose the same option there is a tie. We return from the function and a new loop is started.
if (val == 1 && r == 2) {
print "Paper covers rock, you loose"
} else if (val == 2 && r == 1) {
...
We compare the chosen values of the players and print the result to the console.
$ awk -f rock_scissors_paper.awk
1 - rock
2 - paper
3 - scissors
9 - end game
1
I have scissors you have rock
Rock blunts scissors, you win
1 - rock
2 - paper
3 - scissors
9 - end game
3
I have paper you have scissors
Scissors cut paper, you win
1 - rock
2 - paper
3 - scissors
9 - end game
A sample run of the game.