Advertisement
Spocoman

03. Memory Game

Nov 6th, 2023 (edited)
623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.     string gameLine, command;
  9.     getline(cin, gameLine);
  10.  
  11.     vector<string> game;
  12.  
  13.     for (int i = 0; i < gameLine.length(); i += 2) {
  14.         game.push_back("");
  15.         game[game.size() - 1] += gameLine[i];
  16.     }
  17.  
  18.     int counter = 1;
  19.  
  20.     cin >> command;
  21.  
  22.     while (command != "end") {
  23.         int index1 = stoi(command), index2 = stoi(command);
  24.  
  25.         cin >> command;
  26.  
  27.         if (index1 > stoi(command)) {
  28.             index1 = stoi(command);
  29.         }
  30.         else {
  31.             index2 = stoi(command);
  32.         }
  33.  
  34.         if (index1 >= 0 && index1 < game.size() && index2 >= 0 && index2 < game.size() && index1 != index2) {
  35.             if (game[index1] == game[index2]) {
  36.                 cout << "Congrats! You have found matching elements - " << game[index1] << "!\n";
  37.                 game.erase(game.begin() + index2);
  38.                 game.erase(game.begin() + index1);
  39.                 if (game.size() == 0) {
  40.                     cout << "You have won in " << counter << " turns!\n";
  41.                     return 0;
  42.                 }
  43.             }
  44.             else {
  45.                 cout << "Try again!\n";
  46.             }
  47.         }
  48.         else {
  49.             cout << "Invalid input! Adding additional elements to the board\n";
  50.             string elementValue = '-' + to_string(counter) + 'a';
  51.             game.insert(game.begin() + game.size() / 2, { elementValue, elementValue});
  52.         }
  53.  
  54.         counter++;
  55.         cin >> command;
  56.     }
  57.  
  58.     cout << "Sorry you lose :(\n";
  59.     for (auto& s : game) {
  60.         cout << s << ' ';
  61.     }
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement