Part 4 mini-project: Rock-Paper-Scissors

The second Part 4 project is a classic. You type rock, paper, or scissors; the computer picks at random; the program decides who won. It combines random numbers, if/elseif/else, and and/or — your first program played against the computer.

What to build

A program that, when run:

  1. Asks the player to type rock, paper, or scissors.
  2. Picks the computer's move at random.
  3. Prints what the computer chose.
  4. Prints the result: a tie, win, loss, or invalid-move note.

The winning rules are the usual ones:

  • rock beats scissors,
  • paper beats rock,
  • scissors beats paper.

A typical session:

Choose rock, paper, or scissors: rock
The computer chose scissors.
You win!

Files

Starter and finished versions are in projects/rock-paper-scissors/:

  • starter.lua — the prompt is written, with TODO comments for the three steps.
  • finished.lua — a working version. Read it after you try yours.

Run with:

lua projects/rock-paper-scissors/starter.lua

Hints

  • math.random(1, 3) gives 1, 2, or 3. Turn it into a word with if/elseif/else.
  • Check for an invalid choice first: if the typed word is none of the three, say so and stop. player ~= "rock" and player ~= "paper" and player ~= "scissors" is true only when none match.
  • The win test is three cases joined with or, each an and of the two moves, like player == "rock" and computer == "scissors".

What you cannot use yet

  • Tables (Part 5). Three if branches replace a list of choices.
  • Your own functions (Part 5). The whole game fits in one script.
  • Loops, unless you add the play-again feature in the stretch below.

A bigger challenge (optional)

  • Play again. Wrap the game in a while true do ... end loop and stop when the player types quit instead of a move.
  • Keep score. Track wins and losses in two variables and print the tally after each round.

Neither is required to finish the project.

Done?

When the game takes your move, picks its own, and announces the right result for ties, wins, losses, and invalid input, you are done. On to Chapter 21 — Functions, the start of Part 5.