0
請看看下面的代碼沒有贏家和十字架遊戲
#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;
}
}
在這段代碼中,我從來沒有得到「贏」的消息。而且,一個單元總是空閒的,沒有任何符號。 我運行這段代碼有多少次沒有關係,沒有人勝利!爲什麼是這樣?請幫忙!!
'hasWon()'中的邏輯錯誤。 – john
現在將是開始學習如何調試的好時機。 –
我不建議使用可能無限長的循環,因爲當你隨機挑選某些東西時,只會跳出循環。在這種情況下,它不太可能重要,但我建議不要這樣做。跟蹤有多少空閒單元,並從中選擇一個。無需循環。 –