Skip to content

Instantly share code, notes, and snippets.

@nicksspirit
Last active May 14, 2018 08:44
Show Gist options
  • Save nicksspirit/6c6664308f9073446dd8e93badbf093c to your computer and use it in GitHub Desktop.
Save nicksspirit/6c6664308f9073446dd8e93badbf093c to your computer and use it in GitHub Desktop.
A simple Rock Paper Scissors game made in C++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <map>
#include <string>
int randMove() {
return std::rand() % 3;
}
std::map<std::string, int>::iterator serachByValue(std::map<std::string, int> &mapOfWords, int val) {
// Iterate through all elements in std::map and search for the passed element
std::map<std::string, int>::iterator it = mapOfWords.begin();
while (it != mapOfWords.end()) {
if (it->second == val) {
return it;
}
it++;
}
return it;
}
int main() {
srand(time(NULL));
std::string banner = "Rock Paper Scissors Game\n";
std::string playerChoice;
std::map<std::string, int> weaponMap;
weaponMap.insert(std::make_pair("r", 0));
weaponMap.insert(std::make_pair("p", 1));
weaponMap.insert(std::make_pair("s", 2));
int winLoseMatrix[3][3] = {{-1, 1, 0},
     {0, -1, 1},
{1, 0, -1}};
std::cout << banner;
std::cout << "Choose rock (r) paper (p) or scissors (s): ";
std::cin >> playerChoice;
std::cout << "\n" << "Okay, you chose " << playerChoice << "\n";
int computerMove = randMove();
int playerMove = weaponMap.find(playerChoice)->second;
if (winLoseMatrix[playerMove][computerMove] == -1) {
std::cout << "\n" << "It's a draw!" << "\n";
}
else if (winLoseMatrix[playerMove][computerMove] == 1) {
std::cout << "\n" << "You Win!" << "\n";
}
else {
std::cout << "\n" << "You Loose!" << "\n";
}
std::cout << "Computer chose " << serachByValue(weaponMap, computerMove)->first << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment