fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int findBestMove(int stones) {
  5. if (stones == 1 || stones == 2)
  6. return stones;
  7.  
  8. for (int move = 1; move <= 2; move++) {
  9. int remaining = stones - move;
  10.  
  11. if (remaining % 3 == 0) {
  12. return move;
  13. }
  14. }
  15.  
  16. return 1;
  17. }
  18.  
  19. int main() {
  20. int stones;
  21.  
  22. cout << "Enter the number of stones: ";
  23. cin >> stones;
  24.  
  25. cout << "Stone Game - You and the AI will take turns.\n";
  26. cout << "You can take 1 or 2 stones each turn.\n";
  27. cout << "Whoever takes the last stone wins!\n";
  28.  
  29. while (stones > 0) {
  30. cout << "\nStones remaining: " << stones << endl;
  31.  
  32. int playerMove;
  33. cout << "Your turn! Take 1 or 2 stones: ";
  34. cin >> playerMove;
  35.  
  36. if ((playerMove != 1 && playerMove != 2) || playerMove > stones) {
  37. cout << "Invalid move. Try again.\n";
  38. continue;
  39. }
  40.  
  41. stones -= playerMove;
  42.  
  43. if (stones == 0) {
  44. cout << "You win! Congratulations!\n";
  45. break;
  46. }
  47.  
  48. int aiMove = findBestMove(stones);
  49. cout << "AI takes " << aiMove << " stones.\n";
  50. stones -= aiMove;
  51.  
  52. if (stones == 0) {
  53. cout << "AI wins! Better luck next time.\n";
  54. break;
  55. }
  56. }
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 5308KB
stdin
4
1
2
stdout
Enter the number of stones: Stone Game - You and the AI will take turns.
You can take 1 or 2 stones each turn.
Whoever takes the last stone wins!

Stones remaining: 4
Your turn! Take 1 or 2 stones: AI takes 1 stones.

Stones remaining: 2
Your turn! Take 1 or 2 stones: You win! Congratulations!