gpt4 book ai didi

c++ - 在我的 Naughts and Crosses 游戏中没有人赢

转载 作者:行者123 更新时间:2023-11-28 07:52:32 24 4
gpt4 key购买 nike

请看下面的代码

#include <iostream>
#include <stdlib.h>
#include <ctime>

using namespace std;

const char PLAYER_1 = 'O';
const char PLAYER_2 = 'X';


int row = 0;
int col = 0;

int winningStates[8][3][2] = {{{0,0},{0,1},{0,2}},{{1,0},{1,1},{1,2}},{{2,0},{2,1},{2,2}},{{3,0},{3,1},{3,2}},
{{4,0},{4,1},{4,2}},{{5,0},{5,1},{5,2}},{{6,0},{6,1},{6,2}},{{7,0},{7,1},{7,2}}};

//This sets all the elements within the body to '-' to indicate that the square is free
void intialise(char board[][3])
{
for(int i=0;i<3;i++)
{
for(int a=0;a<=3;a++)
{
board[i][a] = '-';

}
}


}

//This displays the board on the screen
void display(char board[][3])
{
for(int i=0;i<3;i++)
{
for(int a=0;a<3;a++)
{
cout << board[i][a] << "\t ";

}
cout << endl;
}
}

//setValue() sets the cell indicated by the parameter to the value that is contained within the symbol parameter
void setValue(int row, int col, char symbol, char board[][3])
{
board[row][col] = symbol;
}

//isFree() returns true if the cell identified by the parameter contains '-'
bool isFree(int row, int col, char board[][3])
{
if(board[row][col]=='-')
{
return (true);
}
else
{
return (false);
}
}

bool hasWon(char symbol,char board[][3])
{
bool match = false;

row = 0;
col = 0;

for(int m=0;m<8;m++)
{
for(int s=0;s<3;s++)
{
row = winningStates[m][s][0];
col = winningStates[m][s][1];

if(board[row][col]==symbol)
{
match = true;
}
else
{
match = false;
break;
}
}
}
return match;
//return false;
}

int main()
{
char board[3][3];

srand(time(0));

bool gameOver = false;

char player = PLAYER_1;

int count = 0;

intialise(board);
// display();

while(gameOver!=true)
{

do
{
row = rand()%3;
col = rand()%3;
}
while(! isFree(row,col,board));


setValue(row,col,player,board);
if(player==PLAYER_1)
{
player = PLAYER_2;
}
else
{
player = PLAYER_1;
}

gameOver = hasWon(player,board);

if(gameOver==true)
{
cout << "WON" << endl;
}
count++;

if(count==9)
{
gameOver = true;
break;
}


display(board);
cout << endl;


}
}

在此代码中,我从未收到“WON”消息。并且,一个单元格总是空闲的,没有任何符号。不管我运行这段代码多少次,没有人赢!!为什么是这样?请帮忙!!

最佳答案

看起来像是逻辑错误,试试这个

bool hasWon(char symbol,char board[][3])
{
for(int m=0;m<8;m++)
{
bool found_line = true;
for(int s=0;s<3;s++)
{
int row = winningStates[m][s][0];
int col = winningStates[m][s][1];

if(board[row][col]!=symbol)
{
found_line = false;
break;
}
}
if (found_line)
return true;
}
return false;
}

我认为为此类任务选择更好的变量名会有所帮助,match 不是很好,因为它没有说明您要匹配什么。这似乎是你的错误。

关于c++ - 在我的 Naughts and Crosses 游戏中没有人赢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13456661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com