Revisiting Rock Paper Scissors

Rock paper scissors was one of the first programs I’ve ever written, and I think it would be fun to see how different it would be if I coded it today. Preferably I would like to avoid nested ifs. So, here’s what I came up with:

#include <iostream>
#include <array>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
  int player_points = 0;
  int computer_points = 0;
  const int max_points = 3;
  const char* winner = nullptr;
  const array< char, 3 > choices = { 'r', 'p', 's' };
  while( player_points < max_points && computer_points < max_points )
  {
    cout << "r p s?";
    char player_choice;
    cin >> player_choice;
    if( std::find(
      choices.begin(),
      choices.end(),
      player_choice ) == choices.end() )
    {
      cout << "invalid input" << endl;
      continue;
    }
    char computer_choice = choices[ rand() % choices.size() ];
    cout << "computer choice: " << computer_choice << endl;
    auto get_choice_index = [&]( char choice ){ return std::find(
      choices.begin(),
      choices.end(),
      choice ) - choices.begin(); };
    int player_index = get_choice_index( player_choice );
    int computer_index = get_choice_index( computer_choice );
    if( player_index == computer_index )
    {
      winner = nullptr;
    }
    else if( ( player_index + 1 ) % choices.size() == computer_index )
    {
      winner = "computer";
      computer_points++;
    }
    else
    {
      winner = "player";
      player_points++;
    }
    if( winner )
      cout << "point to " << winner << endl
    else
      cout << "tie" << endl
    cout << "score" << endl
      << "player: " << player_points << endl
      << "computer: " << computer_points << endl << endl;
  }
  cout << "winner: " << winner << endl
    << "game over" << endl;
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *