【问题标题】:How to validate player input in tic tac toe?如何验证井字游戏中的玩家输入?
【发布时间】:2014-09-21 06:44:48
【问题描述】:

您好,我正在尝试制作一个玩家与电脑对战的井字游戏。唯一的问题是我无法验证玩家或 pc 的移动,例如,如果 pc 将其移动放在棋盘上,则玩家无法将其移动放置在将被占用的同一位置。 pc 也是如此.我的代码在下面,所以看看它,让我知道如何纠正它。

for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        board[row][col]=' ';
    }
}
cout << endl << endl;
for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        cout << "|" << board[row][col] <<  "|" ;
    }
    cout << endl << "|-||-||-|" ;
    cout << endl;
}
cout << endl << endl << endl;

cout << "Are you player 1 or 2?: ";
cin >> player;
cout << endl << endl << endl;

    if(player==1){
        cout << "Your symbol is 'O'.The computer's is 'X' " << endl;
    }else if(player==2){
        cout << "Your symbol is 'X'.The computer's is 'O' " << endl;
    }
    cout << endl << endl;



while(Gameover==false){

    while(win==false){
    if(player==1){
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;

    srand(time(0));
    x=rand()%3;
    y=rand()%3;

    cout << endl << endl << endl;

    if(board[row][col]!=' '){
    cout << "Invalid move.That spot is already occupied.";
    cout << endl << endl << endl;
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;
    srand(time(0));
    x=rand()%3;
    y=rand()%3;
    }
    board[r][c]='O';
    board[x][y]='X';


}else if(player==2){
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;

    srand(time(0));
    x=rand()%3;
    y=rand()%3;

    if(board[row][col]!=' '){
    cout << "Invalid move.That spot is already occupied.";
    cout << endl << endl << endl;
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;
    srand(time(0));
    x=rand()%3;
    y=rand()%3;
    }
    board[r][c]='X';
    board[x][y]='O';
}
    cout << endl << endl << endl;

for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        cout << "|" << board[row][col]  <<  "|" ;
    }
    cout << endl << "|-||-||-|" ;
    cout << endl;
}
cout << endl << endl << endl;
    }

}

返回 0; }

【问题讨论】:

    标签: tic-tac-toe


    【解决方案1】:

    你在循环中有一个逻辑问题,if(board[row][col]!=' ') 句子应该是While(board[r][c]!=' ' 然后在这个循环之后你必须测试 computer player 值,比如@987654323 @ 在这些 to 循环之后,您将输入值,if 子句将测试一次,如果用户进入您不知道的第二次占用的地方。

    【讨论】:

    • 好的,谢谢,我想通了,但现在我有另一个问题,我无法确定比赛的获胜者。
    • 您可以测试每一种可能的获胜方式,它们是 8 种方式。如果有赢家结束游戏,就像 8 case switch 语句。如果玩家是 X 或 O 来决定游戏乞讨中的获胜者,那么你可以从数组的内容中决定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多