这是一个简单的井字游戏,我敢肯定您已经看过,代码不完整。我不需要别人去看所有的东西,只需要在'.empty'之前格式化2D字符数组就可以知道如何访问它作为参考。如果您可以查看“ int get_row()”内部的内容,那就太好了。
我已经尝试过我的教科书和C ++教程告诉我的所有内容,并且我很确定它们中没有一个是2D数组作为练习的一部分。我的意思是,如果您找不到,可以发送一个很好的链接。
#include <iostream>
#include <string>
#include <array>
using namespace std;
char board[3][3];
void print_board(char board[3][3])
{
cout << " 0 1 2 " << endl;
cout << "0 " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl;
cout << " -----------" << endl;
cout << "1 " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl;
cout << " -----------" << endl;
cout << "2 " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl;
}
void clear_board(char board[][3])
{
}
int get_row(char board[][3], char player)
{
int row;
cout << "Please enter the row move for player " << player << endl;
cin >> row;
if (board.empty())
return row;
}
int get_column(char board[][3], char player)
{
int column;
cout << "Please enter the column move for player " << player << endl;
cin >> column;
return column;
}
bool check_win(char board[][3], char player)
{
return true;
}
bool board_full(char board[][3])
{
return true;
}
bool square_occupied(char board[][3],int row,int column)
{
return true;
}
void get_move(char board[3][3], char player)
{
do
{
do {
int row, column;
get_row(board, player);
get_column(board, player);
square_occupied(board, row, column);
} while (square_occupied);
board_full(board);
} while (!board_full);
}
int main()
{
string play_again = "Y", answer;
int row, column;
char player = 'X';
cout << "Welcome to tic-tac-toe!" << endl;
cout << "Please, use the coordinates for rows and columns to record moves." << endl;
do {
do {
print_board(board);
board_full(board);
get_move(board, player);
check_win(board, player);
if (player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
} while (!check_win);
cout << "Would you like to play again? (Y/N)";
cin >> answer;
}while (answer == play_again);
return 0;
}
我只想能够检查[row]处的数组容器是否为空。我真的不能使用引用数组,仅此而已。
答案 0 :(得分:0)
如果您声明C数组,则它永远不会为空(而且它不会t have a
为空成员函数)。
char board[3][3]; //Never empty - always has 9 values
当然,井字游戏板可以是空的。表示电路板的数组不为空,但是该数组中的值可能设置为0
或其他指示它们为空的值。
我们可以编写一个小类来表示板,并为其提供一个empty
函数:
struct Board {
char board[3][3];
Board() : board() {}
bool empty() const {
char* data = &board[0][0];
for(int i = 0; i < 9; i++) {
if(data[i] != 0) return false;
}
return true;
}
bool rowEmpty(int row) const {
return board[row][0] == 0 && board[row][1] == 0 && board[row][2] == 0;
}
bool colEmpty(int col) const {
return board[0][col] == 0 && board[1][col] == 0 && board[2][col] == 0;
}
void putX(int row, int col) {
board[row][col] = 'X';
}
void putO(int row, int col) {
board[row][col] = 'O';
}
// This function returns a reference so you can modify it if you want
char& getSquare(int row, int col) {
return board[row][col];
}
};
通过创建一个代表董事会的类,您可以添加所需的任何功能和成员功能!