我正在試圖製作一個使用2D陣列來玩井字遊戲的程序。我設置了一個while循環,其中兩個while循環來回傳遞,直到勝利條件滿足。基本上,while循環一直持續,直到滿足一個勝利條件(在一次完整的轉場之後立即發生)。其中兩個while循環代表圈數。因此,如果法律參數得到滿足,玩家輪到他們,然後玩家輪到他們,等等。如果參數不符合,那很好,它會回到該回合的頂部,以便他們可以再次嘗試。這裏是我的代碼:如果語句在條件不滿足時觸發?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char TicTacToe [3][3] = {0}; // This initializes an array of "e's" for empty space.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
TicTacToe [i][j] = 'e';
}
}
for (int i = 0; i < 3; i++) // This outputs the game board so the user(s) can get a visual.
{
for (int j = 0; j < 3; j++)
{
cout << TicTacToe [i][j] << " ";
}
cout << "\n";
}
bool flag = true;
bool turn1flag = true;
bool turn2flag = true;
int p1row, p1col, p2row, p2col = 0;
cout << "\n";
cout << "Welcome to Tic-Tac-Toe. The game board is shown above. " << endl;
cout << "The rows are numbered one through three from top to bottom. " << endl;
cout << "The columns are numbered one through three from left to right. " << endl;
cout << "Player one's spaces are indicated by an 'o.'" << endl;
cout << "Player two's spaces are indicated by an 'x.'" << endl;
cout << "Empty spaces are indicated by an 'e.'" << endl << endl;
while (flag == true) // This while loop starts the game
{
while (turn1flag == true)
{
cout << "It is player one's turn. Which row? " << endl;
cin >> p1row;
cout << "And which column? " << endl;
cin >> p1col;
if (TicTacToe[p1row-1][p1col-1] == 'e') // This checks if the selected spot is empty. If not, it's filled with the users symbol.
{
TicTacToe[p1row-1][p1col-1] = 'o';
for (int i = 0; i < 3; i++) // This outputs the game board so the user(s) can see their progress.
{
for (int j = 0; j < 3; j++)
{
cout << TicTacToe [i][j] << " ";
}
cout << "\n";
}
cout << "\n";
turn1flag = false;
}
else // If a position is taken or out of bounds, we're returned to the top of the turn loop.
{
cout << "That position is already taken or out of bounds. Try again. " << endl;
}
}
while (turn2flag == true)
{
cout << "It is player two's turn. Which row? " << endl;
cin >> p2row;
cout << "And which column? " << endl;
cin >> p2col;
if (TicTacToe[p2row-1][p2col-1] == 'e')
{
TicTacToe[p2row-1][p2col-1] = 'x';
for (int i = 0; i < 3; i++) // This outputs the game board so the user(s) can see their progress.
{
for (int j = 0; j < 3; j++)
{
cout << TicTacToe [i][j] << " ";
}
cout << "\n";
}
cout << "\n";
turn2flag = false;
}
else
{
cout << "That position is already taken or out of bounds. Try again. " << endl;
}
}
// All of the following are player one win conditions.
if ((TicTacToe [0][0] = 'o') && (TicTacToe [0][1] = 'o') && (TicTacToe [0][2] = 'o'))
{
cout << "Congratulations player one, you've won!" << endl;
flag = false;
}
... // the other 15 winning conditions for either player 1 or 2.
你知道哪些if語句觸發嗎?或者它是全部。另外,將代碼切入函數可以提高可重用性和可讀性。 –
'while(flag == true)'可以簡化爲'while(flag)' – fredoverflow
另外你應該確保用戶輸入在範圍[1,3]中,否則你的數組訪問將失敗或者意外行爲。 – maddin45