我正在尝试制作TicTacToe游戏,但我的代码中有些东西无效。我创建了一个名为TicTacToeGame
的新类,我有source.cpp
(主文件)。一切都很好,直到我做了一个循环来测试空间是否被占用。
从那时起,它要求我输入X的坐标。我给它一个答案,然后它要求我输入Y坐标。我给它一个答案;但是,它又要求一个Y坐标,如果我给他一个错误的输入,它会开始用这个问题向我发送垃圾邮件,或者告诉我,我引入了一个错误的输入。
我该怎么办?我想知道什么是错的。
TicTacToeGame.h
#pragma once
class TicTacToeGame
{
public:
TicTacToeGame();
void playGame();
private:
bool placeMarker(int x, int y, char currentPlayer);
int getXCoord();
int getYCoord();
char board[3][3];
// Clears the board
void clearBoard();
// Prints the board
void printBoard();
};
TicTacToe.cpp
#include "TicTacToeGame.h"
#include <iostream>
using namespace std;
TicTacToeGame::TicTacToeGame()
{
clearBoard();
};
void TicTacToeGame::playGame()
{
char player1 = 'X';
char player2 = 'Y';
char currentPlayer = 'X';
bool isDone = false;
int x, y;
while (isDone == false) {
printBoard();
x = getXCoord();
y = getYCoord();
if (placeMarker(x, y, currentPlayer) == false) {
cout << "That spot is occupied\n";
}
else
{
// Switch player so every player can put markers
if (currentPlayer == player1) {
currentPlayer = player2;
}
else
{
currentPlayer = player1;
}
}
}
}
int TicTacToeGame::getXCoord()
{
bool isInputBad = true;
int x;
while (isInputBad == true) {
cout << "Enter the X coordinate: ";
cin >> x;
if (x < 1 || x > 3) {
cout << "Invalid coordinate!\n";
}
else
{
isInputBad = false;
}
}
return x - 1;
}
int TicTacToeGame::getYCoord()
{
bool isInputBad = true;
int y;
while (isInputBad == true) {
cout << "Enter the Y coordinate: ";
cin >> y;
}
if (y < 1 || y > 3) {
cout << "Invalid coordinate!\n";
}
else
{
isInputBad = false;
}
return y - 1;
}
bool TicTacToeGame::placeMarker(int x, int y, char currentPlayer)
{
if (board[y][x] != ' ') {
return false;
}
board[y][x] = currentPlayer;
return true;
}
void TicTacToeGame::clearBoard()
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
void TicTacToeGame::printBoard()
{
cout << endl;
cout << " |1 2 3|\n";
for (int i = 0; i < 3; i++) {
cout << "--------\n";
cout << i+1 << "|" << board[i][0] << "|" << board[i][1] << "|" << board[i][2] << "|\n";
}
cout << "--------\n";
}
source.cpp
#include "TicTacToeGame.h"
#include <iostream>
using namespace std;
int main()
{
TicTacToeGame game;
game.playGame();
system("PAUSE");
return 0;
}
答案 0 :(得分:0)
你的while循环永远不会退出,
X Coord While Loop:
while (isInputBad == true) {
cout << "Enter the X coordinate: ";
cin >> x;
if (x < 1 || x > 3) {
cout << "Invalid coordinate!\n";
}
else
{
isInputBad = false;
}
} // end of while loop
Y Coord While循环:
while (isInputBad == true) {
cout << "Enter the Y coordinate: ";
cin >> y;
} // end of while loop
if (y < 1 || y > 3) {
cout << "Invalid coordinate!\n";
}
else
{
isInputBad = false;
}
查看验证码如何在Y Coord的while循环之外?
while条件isInputBad
将始终等于true,因为它将在循环后设置为false。
在if语句之后移动while循环的结尾,它应该可以工作。