Hi all,
I've been going through the tutorials on the site and decided to create a simple tic tac toe program to put them in to context. This is my first attempt at c++ so go easy on me.
In the constructor method for the board class I'm getting the error message "//error: 'newTile' was not declared in this scope" and I can't work out why. Could anyone help with this?Code:#include <iostream>
using namespace std;
//Tile Class
class Tile {
public:
Tile();
~Tile();
void changeValue( int newValue );
void display();
int getValue();
int getX();
int getY();
protected:
int value;
int x;
int y;
};
Tile::Tile() {
value = 0;
}
Tile::~Tile() {
//Destructors do not accept arguments
}
void Tile::changeValue (int newValue) {
value = newValue;
}
int Tile::getValue() {
return value;
}
void Tile::display() {
if (value == 0) {
cout << "| ";
}
if (value == 1) {
cout << "| X ";
}
if (value == -1) {
cout << "| 0 ";
}
}
int Tile::getX() {
return x;
}
int Tile::getY() {
return y;
}
//Board Class
class Board {
public:
Board();
~Board();
void displayBoard();
void changeValue(char ox, int x, int y);
bool isFinished(int moves);
bool boardFull(int moves);
bool isLegal(int x, int y);
protected:
Tile board[3][3];
};
Board::Board() {
int i;
int j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
Tile newTile;
board[i][j] = newTile; //error: 'newTile' was not declared in this scope
}
}
Board::~Board() {
}
void Board::displayBoard() {
int i;
int j;
cout << "Noughts and Crosses: \n";
cout << "_____________\n";
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
board[i][j].display();
cout << "|";
cout << "\n";
cout << "-------------\n";
}
}
void Board::changeValue(char ox, int x, int y) {
if (ox == 'X' || ox == 'x') {
board[x][y].changeValue(1);
}
if (ox == '0' || ox == 'o' || ox == 'O'){
board[x][y].changeValue(-1);
}
displayBoard();
}
bool Board::boardFull(int moves) {
bool isFull;
isFull = 0;
if (moves >= 9) {
isFull = 1;
}
else {
return isFull;
}
return isFull;
}
bool Board::isFinished(int moves) {
bool finished = 0;
if (boardFull(moves)){
finished = 1;
}
return finished;
}
bool Board::isLegal(int x, int y) {
bool isLegal = 0;
if (x > 0 && x <= 3 && y > 0 && y <= 3 && board[x-1][y-1].getValue() == 0){
isLegal = 1;
}
return isLegal;
}
int main () {
char player;
int x;
int y;
int moves;
moves = 0;
Board board;
board.displayBoard();
while (!board.isFinished(moves)){
if (moves % 2 == 0) {
player = '0';
}
else {
player = 'X';
}
cout << "Player " << player << " please enter your next move: \n";
cout << "X Coordinate: " << endl;
cin >> x;
cout << "Y Coordinate: " << endl;
cin >> y;
cin.ignore();
//create is legal method
if (board.isLegal(x, y)) {
board.changeValue(player, x-1, y-1);
moves++;
}
else {
cout << "Invalid Move!\n";
}
}
cin.get();
cout << "Game Over\n";
return 0;
}
Zack