採用模擬對戰,雙方輪流輸入取數,判斷勝負並統計多局勝率。
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
char player[2][40];
int rounds, totalSticks, currentPlayer, take, sticks;
int win[2] = {0, 0};
cout << "玩家1姓名: "; cin >> player[0];
cout << "玩家2姓名: "; cin >> player[1];
do { cout << "局數(1-5): "; cin >> rounds; } while (rounds < 1 || rounds > 5);
do { cout << "每局樹枝數(1-21): "; cin >> totalSticks; } while (totalSticks < 1 || totalSticks > 21);
for (int r = 1; r <= rounds; r++) {
srand((unsigned)time(NULL) + r);
currentPlayer = rand() % 2;
sticks = totalSticks;
cout << "\n第 " << r << " 局開始,共 " << sticks << " 根\n";
while (sticks > 0) {
cout << "剩餘: " << sticks << " ";
do { cout << player[currentPlayer] << " 取(1-2): "; cin >> take; } while (take < 1 || take > 2);
sticks -= take;
if (sticks <= 0) {
cout << player[currentPlayer] << " 取走最後一根,輸了!\n";
win[1 - currentPlayer]++; // 對方獲勝
break;
}
currentPlayer = 1 - currentPlayer;
}
}
cout << "\n最終戰績: " << player[0] << " " << win[0] << " 勝, " << player[1] << " " << win[1] << " 勝\n";
return 0;
}
原題「誰拿到最後一根誰輸」屬於誤差遊戲,先手必勝策略為:保持每輪總取數為 3(對方取 1 我取 2,對方取 2 我取 1),使對方面對 1 根被迫取走。