Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 135 ยท Projects

Project: Rock Paper Scissors

Build rock paper scissors in C in three stages: enums and a modular-arithmetic judge, a game loop with safe input and scores, and a computer that learns your favorite move.

Rock paper scissors is a tiny game with a surprising number of things to get right. Who wins? How does the computer choose? What if the player types rock instead of r, or just presses Enter, or types a hundred letters? And can the computer be made a little smarter than a coin flip? You'll answer each question in turn and finish with a program that is about 90 lines long and shrugs off whatever you type.

The project uses enums, random numbers, arrays of strings and safe line input with fgets. It has three stages. Each is a complete program, because a TryIt run starts fresh. Moves come from the Input box, one per line, so any game can be replayed by editing the input.

Stage 1: moves, outcomes and the judge

Naming the values. A move is one of three things, and an enum gives them names while keeping them cheap integers:

C
typedef enum { ROCK, PAPER, SCISSORS } Move;

ROCK is 0, PAPER is 1 and SCISSORS is 2. We also want a type for the result of a round, always seen from one player's side: DRAW, WIN or LOSS. A parallel array move_name[] turns a Move back into text, because enum values do not print as names. Using the enum as the array index works since its values start at 0.

Who wins? A beginner version of judge is nine if cases. There is a much shorter way, hidden in the order we picked for the enum. Paper beats rock, scissors beats paper, rock beats scissors: each move beats the one before it in the list, wrapping around from the first to the last. So the difference mine - theirs, taken modulo 3, says everything:

(mine - theirs + 3) % 3 Meaning
0 same move, a draw
1 my move comes right after theirs in the list, so I win
2 their move comes right after mine, so I lose

The + 3 matters. In C, % keeps the sign of the left operand (see arithmetic operators), so (0 - 1) % 3 is -1, not 2. Adding 3 first keeps the number positive. Because DRAW, WIN and LOSS were declared in the order 0, 1, 2, the formula's result can be cast straight to an Outcome. This kind of trick is cute but fragile: if someone reorders either enum, the program breaks silently. That is why the last line of the program prints all nine combinations. The table is a built-in check you can read at a glance.

C Stage 1: enums and the judge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The srand(2026) line seeds the generator with a constant, so the six sample rounds are the same on every run. Check them against the table at the bottom: paper vs rock is 1, so the first player wins.

Stage 2: a game loop with input you can trust

Now the human joins in. The loop reads one line, turns it into a move, lets the computer pick, judges the round and updates three counters.

Reading a line. Use fgets, never scanf("%s"). It stops at the buffer size, and it returns NULL at the end of the input, which is the loop's natural exit. The loop condition printf("> "), fgets(...) != NULL uses the comma operator: show the prompt, then read. The program also echoes each line back, because the Input box has no terminal to do it for us.

Parsing the choice. The function parse_move accepts one letter, in any case, with spaces around it. That rules out three kinds of bad input, and each deserves its own thought:

  • An empty line. The first character is the null terminator, so we return -1 before looking any further.
  • A word instead of a letter. If rock were accepted by only looking at r, then rubbish would be too. The function checks that the character after the letter is either the end of the string or whitespace.
  • A line that is too long. With a 64-byte buffer, fgets leaves the rest of a long line in the input for the next read, and the leftover text would then be read as "the next move". When there is no newline in the buffer (and the stream has not ended), the program throws away the rest of the line with a small getchar loop and reports the problem.

The function returns an int so it can carry two extra answers beside the three moves: 'q' for quit, and -1 for "not understood". A switch on tolower((unsigned char)*line) does the dispatch. The unsigned char cast matters for every <ctype.h> call, as explained in characters.

The computer's move. rand() % 3 gives 0, 1 or 2, which is exactly the range of Move. The modulo bias is real but far too small to matter for three choices out of 2,147,483,648 values (see random numbers for the unbiased approach when it does matter). Seeding is the part that decides how the game feels. Here srand(7) is fixed so that the page is reproducible. A real game would call srand((unsigned)time(NULL)) once at startup, so each run differs.

C Stage 2: the full loop with validation and scores

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The sample input is deliberately nasty: a lowercase move, an uppercase move, an unknown letter, a whole word, an empty line, a doubled letter, and a letter with spaces in front. Only valid single letters count. Try adding q at a different place, removing it so the input ends on its own, or pasting a very long line.

Stage 3: a computer that learns

Random play is fair but dull, and it is also unbeatable, since no strategy can beat a perfect coin flip. People, however, are not random. Many players repeat a favorite move without noticing. A computer that notices can exploit it.

The idea needs one array and one function:

  • int seen[MOVE_COUNT] counts how often the player has chosen each move.
  • computer_move finds the most frequent move. If there is a single favorite, it plays the move that beats it. If two or more moves tie (including the start, when all counts are 0), it guesses at random.
  • counter(m) returns the move that beats m. The same modular idea gives it directly: the move one position after m, wrapping around.

There is one subtle rule: the computer chooses before the player's new move is added to seen. Updating first would let the computer "see" the move it is supposed to be predicting, which is cheating. The comment in the code marks the order.

This version also changes the structure of the game into a match: the first side to three wins takes it. The loop condition now has three parts: nobody has won yet, the target has not been reached, and there is more input. After the loop, an if chain reports the three possible endings, including the case where the input ran out first.

C Stage 3: a match against an adaptive computer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Run it with the sample input. The player opens with rock. In the first round all counts are zero, so the computer guesses; from the second round on there is a single favorite, and the computer answers rock with paper every time. Then try a mixed sequence: r p s p p p s s s r finishes a close match, because the player's most frequent move keeps changing and the counter-strategy has to follow.

Ideas for going further

  • Add rock, paper, scissors, lizard, Spock. With five moves, the "beats the previous one" rule becomes "beats the previous two", so (mine - theirs + 5) % 5 is 1 or 2 for a win, 3 or 4 for a loss. What does the enum order have to look like?
  • Make the computer remember only the player's last ten moves, using a circular buffer, so it adapts when the player changes habits.
  • Save the score table to a file between runs, as the bank project does with its accounts.
  • Replace the if/switch parsing with a table of { "rock", ROCK } pairs so rock, r and R all work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With ROCK = 0, PAPER = 1 and SCISSORS = 2, what does ((int)mine - (int)theirs + 3) % 3 equal when mine is ROCK and theirs is SCISSORS?

    ROCK - SCISSORS is 0 - 2 = -2. Adding 3 gives 1, and 1 % 3 is 1, which the program reads as a win. Rock does beat scissors. Without the + 3, -2 % 3 would be -2 in C.
  2. 2. Why does parse_move check the character AFTER the first letter?

    Looking only at the first character would accept any word starting with r, p or s. Requiring the end of the string or whitespace next means only a single letter is a valid move.
  3. 3. What goes wrong if fgets reads a 100-character line into a 64-byte buffer and the program does nothing about it?

    fgets never writes past the buffer. It stops early and leaves the remaining characters in the stream, so the next read starts in the middle of the old line. The program detects the missing newline and discards the rest.
  4. 4. In stage 3, why must computer_move run before seen[player]++ ?

    If the current move were counted first, the computer's choice could depend on the player's choice in the same round, which would be cheating. The computer should only know what happened in earlier rounds.

Summary

  • An enum names the three moves; an array of strings turns a value back into text, using the enum as the index.
  • Putting the moves in the right order lets one expression, (mine - theirs + 3) % 3, replace nine cases. Add 3 because C's % keeps the sign of the left operand.
  • Read lines with fgets, handle NULL as the end of input, and deal with empty, too-short, too-long and too-wordy lines on purpose.
  • Seed rand once. Use a constant seed to make a program reproducible and time(NULL) to make it vary.
  • A frequency table plus "play the counter to the favorite" makes a computer opponent that wins against predictable players.
  • A modest game becomes a good project when its edge cases are handled explicitly.

Next: Project: Hangman, where you will reveal a secret word letter by letter and keep track of lives, guesses and a text-art gallows.