You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++问题:如何从orderPlay函数获取playerTurn变量到main函数

解决Chutes and Ladders游戏中main函数无法获取orderPlay返回的playerTurn变量问题

核心问题修复

你的orderPlay()函数已经正确返回了playerTurn字符串,但main函数里只是调用了orderPlay()却没有把返回值存下来,导致后续判断playerTurn时变量未定义。直接在main里定义字符串变量接收返回值即可:

int main()
{
    // ... 其他初始化代码 ...
    string playerTurn; // 定义变量接收返回值
    do{
        playerTurn = orderPlay(); // 接收orderPlay返回的玩家回合标识
        // ... 后续代码 ...

这样main里就能正常使用playerTurn判断当前是哪个玩家回合了。

顺带修复代码里的其他新手常踩坑

  1. getline读取名字失效问题
    用cin >> playerTurn之后,输入缓冲区会残留换行符,后续getline会直接读取空行,导致玩家输入名字时被跳过。在cin >> playerTurn后加一行清空缓冲区:
string orderPlay(){
  string playerTurn;
  cout << "Please initiate which player is going first (P1/P2): ";
  cin >> playerTurn;
  cin.ignore(); // 清空输入缓冲区的换行符
  // ... 后续读取名字的代码 ...
}
  1. 骰子值输出顺序错误
    你现在是先输出dice再调用spin(),此时dice还是上一轮值或初始值,应该先掷骰子再输出:
cout << "Press enter to spin...";
cin.ignore();
spin(); // 先执行掷骰子逻辑
cout << "You threw " << dice << "."; // 再输出结果
  1. CheckChutes/CheckLadders传参无效
    当前这两个函数是传值调用,修改的只是参数副本,不会影响main里的newPos1/newPos2。改成传引用才能真正修改原变量,同时调整提示输出逻辑(只有触发 chute/ladder 时才输出):
void CheckChutes (int& NewPos) // 传引用
{
    bool landedOnChute = false;
    if (NewPos == 98) { NewPos = 78; landedOnChute = true; }
    else if (NewPos == 95) { NewPos = 75; landedOnChute = true; }
    // ... 其他chute判断逻辑 ...
    if (landedOnChute) {
        cout << "You landed on a chute, and have to move down" << endl;
    }
}

void CheckLadders (int& NewPos) // 传引用
{
    bool landedOnLadder = false;
    if (NewPos == 1) { NewPos = 38; landedOnLadder = true; }
    else if (NewPos == 4) { NewPos = 14; landedOnLadder = true; }
    // ... 其他ladder判断逻辑 ...
    if (landedOnLadder) {
        cout << "You landed on a ladder, and get to move up the board!" << endl;
    }
}

之后在main里更新位置后调用这两个函数,并同步当前位置:

if (playerTurn == "p1" || playerTurn == "P1"){ // 修正原判断的拼写错误
    newPos1 = currPos1 + dice;
    cout << playerName1 << " Your new location is: " << newPos1 << endl; 
    CheckChutes(newPos1);
    CheckLadders(newPos1);
    currPos1 = newPos1; // 更新玩家当前位置
}else{
    newPos2 = currPos2 + dice;    
    cout << playerName2 << " Your new location is: " << newPos2 << endl;
    CheckChutes(newPos2);
    CheckLadders(newPos2);
    currPos2 = newPos2; // 更新玩家当前位置
}
  1. 游戏循环逻辑问题
    当前do-while循环每次都会重新调用orderPlay()选玩家,不符合一局游戏只选一次先手的逻辑。把选玩家的逻辑移到循环外,并在回合结束后切换玩家:
int main()
{
    // ... 初始化代码 ...
    string playerTurn;
    playerTurn = orderPlay(); // 仅在开局选一次先手
    do{
        // ... 单回合游戏逻辑 ...
        // 回合结束后切换玩家
        playerTurn = (playerTurn == "P1" || playerTurn == "p1") ? "P2" : "P1";
    } while (choice == YES);
}

内容的提问来源于stack exchange,提问作者i_hate_F_sharp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:40:22