Scissors, Paper or Rock?

In this article, I'm going to tackle a children's game that's extraordinarily
complicated, with many variations, and the programming task is going to be quite
tricky. Just kidding! Rock Paper Scissors (or RPS, as it's known) is
pretty darn easy to simulate because there aren't really many variants or
possible outcomes.

If you've never played it before, it's a one-vs.-one game where each person
secretly chooses one of three possible options (rock, paper or, you guessed it,
scissors). The players reveal their choices simultaneously, and then there are rules about
what beats what. For example, scissors beats paper because "scissors cut
paper", and rock beats scissors because "rock beats scissors". If both
players pick the same option, it's a tie and the game proceeds.

Although you can play it as a one-off, it's also generally played as a best of
three to even things out slightly, although if everything's completely random,
you'll win 33.33% of the time. For any given choice, there's a 1/3 chance
that you'll have a tie, where both players pick the same thing, a 1/3 chance that
you'll win, and a 1/3 chance that you'll lose.

The World Rock Paper Scissors Society

Except, in the real game, it turns out that there's psychology involved too. In
fact, according to the World Rock, Paper, Scissors
Society,
rock is chosen 35.4%, paper 35% of the time and scissors only 29.6% of the time. Got
it?

For the first version of the program, however, let's stick with a completely
random choice. The easy way to choose a random number between 1 and 3 in a Linux shell
script is to use the variable $RANDOM like this:

compchoice=$(( ($RANDOM % 3) + 1 ))

The % is a modulus function and causes the random integer to be divided by
3, resulting in a 0..2 value. Add one, and you've got the 1...3 value. Easy
enough.

With a simple shell array, you can add the name of the choice (remember, arrays
start at index 0):

declare -a RPS; RPS=(nothing rock paper scissors)

Then the choice name is specified simply as:

choicename=${RPS[$compchoice]}

Those three lines are good enough for a tiny script where the computer can
choose randomly between rock, paper and scissors:

Dave Taylor has been hacking shell scripts for over thirty years. Really.
He's the author of the popular "Wicked Cool Shell Scripts" and
can be found on Twitter as @DaveTaylor and more generally at
www.DaveTaylorOnline.com.