首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 實現「撿樹枝」雙人博弈遊戲完整代碼

     編輯:程式設計綜合問答

遊戲規則

  • 樹枝總數 ≤ 21,用戶輸入。
  • 擲硬幣決定先手。
  • 每回合可取 1 或 2 根。
  • 取走最後一根者輸(誤差遊戲變體)。

核心邏輯

採用模擬對戰,雙方輪流輸入取數,判斷勝負並統計多局勝率。

完整代碼

#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 根被迫取走。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved