top of page

Building a Rock, Paper, Scissors Game in C++

Updated: Sep 15, 2024


In this blog post, I'm excited to share a project that I’ve recently worked on: a **Rock, Paper, Scissors** game written in C++. This project was a great way to put core C++ programming skills into practice, from using control structures and functions to file handling and object-oriented programming principles.


Let's dive into the details of how I built this fun and interactive game from scratch.


---


Project Overview


The goal of this project is to create a simple **Rock, Paper, Scissors** game where the user plays against the computer. The game asks the player to input their choice (rock, paper, or scissors), compares it with the computer’s random choice, and declares the winner. The game implements the classic rules:


- **Rock vs Scissors**: Rock wins.

- **Rock vs Paper**: Paper wins.

- **Paper vs Scissors**: Scissors wins.


It also keeps track of the player's score, stores the results in a text file, and allows the player to view their previous game performance.


---


Technologies Used


- C++ Programming Language: The entire game logic is written in C++.

- I/O Streams: For input/output between the console and the program.

- File Handling: To store and retrieve the player's past performance.

- Random Number Generation: To simulate the computer's choice.

- Object-Oriented Programming: Implemented using classes and member functions.


---


Game Features


1. Player vs Computer: The user can play multiple rounds of Rock, Paper, Scissors, with the computer randomly selecting its moves.

2. Score Tracking: The game keeps track of the user's score over multiple rounds.

3. File Storage: Player scores are written to a text file at the end of each game, and the user can view their previous scores when starting a new game.

4. Input Validation: The game handles incorrect input and ensures the user can only choose valid options (rock, paper, or scissors).


---


Code Breakdown


The project is divided into three main files: `main.cpp`, `header.hpp`, and `source.cpp`.


1. Main File (main.cpp)


The main file is the entry point of the program. It takes the player's name, initializes the game, and handles the reading and writing of player data to a file.


main.cpp

int main() {

    string playerName;
    srand(time(NULL));

    cout << "Enter player name  : ";
    cin >> playerName;

    Game newGame(playerName);
    newGame.readFromText(playerName); // Load previous game data
    newGame.gameStart(); // Start the game loop
    newGame.writetoText(playerName); // Save the current game data
}

The `Game` class handles most of the game logic. Let’s break that down further.


2. Game Class (header.hpp)


The `Game` class is responsible for managing player choices, determining the winner, and tracking the score.


class Game {
private:
    string playerName;
    vector<int> pointHistory;
    string playerChoice;
    int point;
public:
    Game(string pName) : playerName(pName), point(0) 
	{
        cout << "Welcome, " << playerName << "! Let's play Rock, Paper, Scissors!" << endl;
    }

    void gameStart();
    string computerChoice();
	int displayResult(const string& playerChoice, const string&  		 computer_Choice);
    void writetoText(const string& playerName);
    void readFromText(const string& playerName);
};

- gameStart(): Handles the game loop where the player inputs their choice, and the computer randomly selects one.

- computerChoice(): Generates a random choice of rock, paper, or scissors.

- displayResult(): Compares the choices of the player and the computer, returns the result (win, lose, or draw).

-writetoText(): Writes the player's score and history to a text file.

- readFromText(): Reads the previous score from the text file, if available.


3. Source File (source.cpp)


The logic of how the game runs is in this file. Here's how it works:


-Game Start and Input Validation: The game prompts the player to enter their choice and validates it.


void Game::gameStart() {
    string answer = "yes";
    do {
        for (size_t i = 0; i < 3; i++) {
            string compChoice = computerChoice();
            cout << "Enter Rock, Paper, or Scissors: ";
            cin >> playerChoice;          

            // Validate input
            while (!(playerChoice == "rock" || playerChoice == "paper" || playerChoice == "scissors")) {
                cout << "Invalid choice. Please enter Rock, Paper, or Scissors: ";
              cin >> playerChoice;
            }

            int result = displayResult(playerChoice, compChoice);
            if (result > 0) cout << "You won!" << endl;
            else if (result < 0) cout << "You lost!" << endl;
            else cout << "It's a draw!" << endl;

            point += result;
            pointHistory.push_back(result);
        }
    } while (answer == "yes");
}

- Random Computer Choice: The computer's choice is generated randomly using `rand()`.


string Game::computerChoice() 
{
    int randomNumber = rand() % 3 + 1;
    if (randomNumber == 1) return "rock";
    else if (randomNumber == 2) return "paper";
    else return "scissors";
}

-Write to File:

void Game::writetoText(const string& playerName)
{
	fstream fout;
	fout.open("Game.txt", ios::app);
	if (!fout.is_open())
	{
		cerr << "File cannot open!";
	}

	fout << endl << endl << "PLAYER NAME   : " << playerName << endl;
	fout << "POINT         : " << point << endl;
	fout << "POINT HISTORY : ";

	for (const int& i : pointtHistory)
	{
		fout << i;
	}

	fout.close();
}


-Read from File:

void Game::readFromText(const string& playerName)
{
	fstream fin;
	string line;
	string pointKeyWord = "POINT         :";
	string findPoint;

	string lowName = toLower(playerName);

	fin.open("Game.txt", ios::in);
	if (!fin.is_open())
	{
		cerr << "File cannot open!";
	}
	cout << "Your previous points: "<< endl;
	while (getline(fin, line))
	{
		if (toLower(line) == ("player name   : " + lowName))
		{
			getline(fin, line);
			if (line.find(pointKeyWord) != string::npos)
				findPoint = line.substr(line.find(pointKeyWord) + pointKeyWord.size());
			cout << findPoint << endl;
		}
	}
	if (findPoint.empty())
		cout << "No previous points found! Starting a new game." << endl;
	fin.close();
}


-String to Lower Function

std::string toLower(const std::string& str)
{
	string lowerStr = str;
	std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::tolower);
	return lowerStr;
}

Key Takeaways

This project was a fun way to practice C++ fundamentals, especially in object-oriented programming and file handling. It showcases how a simple game can be built using essential programming concepts such as loops, conditionals, input validation, and randomization.


For those interested in learning C++ or looking for a beginner project, I highly recommend trying to build a Rock, Paper, Scissors game. It’s a simple but effective way to improve your coding skills!


---


Next Steps: You could enhance this project by adding a graphical user interface (GUI), improving file handling (like saving data in JSON or XML), or even adding multiplayer functionality. Happy coding!

---


I hope you enjoyed this breakdown of my **Rock, Paper, Scissors** C++ project! Let me know if you have any questions or suggestions on how I could further improve it!

 
 
 

Comments


bottom of page