我正在努力学习C ++并且我已经制作了小型的tictactoe游戏,但有些事情是错误的。我试图让胜利者无论是虚空还是布尔。但是当我键入一个坐标时,它会预先形成类。为了简单起见,你只能赢得如果3在上面是O.什么是错的? 所以如果我输入:0 0它说胜利者
以下是代码:
#include <iostream>
const int rows = 3;
const int elements = 3;
const char Ochar = 'O';
char board[rows][elements];
void Clear()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < elements; j++)
{
board[i][j] = 0;
}
}
}
void Show()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < elements; j++)
{
std::cout << " " << board[i][j] << " |";
}
std::cout << std::endl;
std::cout << "------------" << std::endl;
}
}
bool PlayerAttack(int x, int y)
{
if (board[x][y] == 0)
{
board[x][y] = Ochar;
return true;
}
return false;
}
void Winner()
{
if (board[0][0], board[0][1], board[0][2] = 'O')
{
std::cout << "Winner";
}
}
int main()
{
Clear();
Show();
int pos1 = 0;
int pos2 = 0;
while (1)
{
std::cout << "Please input a coordinate: "; std::cin >> pos1 >> pos2; std::cout << std::endl;
PlayerAttack(pos1, pos2);
Show();
Winner();
}
}
答案 0 :(得分:7)
此行不符合您的想法
if (board[0][0], board[0][1], board[0][2] = 'O')
你必须这样做
if (board[0][0] == 'O' && board[0][1] == 'O' && board[0][2] == 'O')
使用Winner
功能打破循环
bool Winner()
{
// You'll obviously have to check more than just this row
if (board[0][0] == 'O' && board[0][1] == 'O' && board[0][2] == 'O')
{
std::cout << "Winner";
return true;
}
return false;
}
然后在main
int main()
{
Clear();
Show();
int pos1 = 0;
int pos2 = 0;
bool winner = false;
while (!winner)
{
std::cout << "Please input a coordinate: "; std::cin >> pos1 >> pos2; std::cout << std::endl;
PlayerAttack(pos1, pos2);
Show();
winner = Winner(); // Use the returned bool
}
}