I am trying to learn C++ and I have made litte tictactoe game but somethings wrong. I've tried to make the winner class both a void and a bool. But when I type in one coordinate it preforms the class. For making it simple you can only win if the 3 on top is O. Whats wrong?
SO if I input: 0 0 it says winner
Here's the code:
#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();
}
}
This line does not do what you think it does
if (board[0][0], board[0][1], board[0][2] = 'O')
You'd have to do
if (board[0][0] == 'O' && board[0][1] == 'O' && board[0][2] == 'O')
To use your Winner function to break your loop
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;
}
Then in 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
}
}
Related
I am trying to create a c++ unbeatable tic tac toe AI. after watching several videos on the topic i thought I had it all figured out. An error pops up on the screen saying "Expression: vector subscript out of range". I believe the error is coming from the availableMoves() function. however I do not know why.
The game itself works fine. any help would be appreciated.
#include <iostream>
#include <vector>
#include <ctime>
bool in(std::vector<int> v, int element)
{
for (int i = 0; i < v.size(); i++)
{
if (element == v[i])
{
return true;
}
}
return false;
}
class Board
{
private:
char board[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
public:
void displayBoard()
{
std::cout << "___________________" << std::endl;
for (int i = 0; i < 3; i++)
{
std::cout << "| ";
for (int j = 0; j < 3; j++)
{
std::cout << board[i][j] << " | ";
}
std::cout << std::endl;
}
std::cout << "___________________" << std::endl;
}
std::vector<int> availableMoves()
{
std::vector<int> moves;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] != 'X' && board[i][j] != 'O')
{
moves.push_back(i * 3 + j);
}
}
}
return moves;
}
void move(int choice, char mark)
{
int y = choice / 3;
int x = choice - y * 3;
board[y][x] = mark;
}
void revert(int choice)
{
int y = choice / 3;
int x = choice - y * 3;
board[y][x] = (char)choice + 48;
}
int checkWin()
{
for (int i = 0; i < 3; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
{
if (board[i][0] == 'X')
{
return 1;
}
else if (board[i][0] == 'O')
{
return -1;
}
}
}
for (int i = 0; i < 3; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
{
if (board[0][i] == 'X')
{
return 1;
}
else if (board[0][i] == 'O')
{
return -1;
}
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
{
if (board[0][0] == 'X')
{
return 1;
}
else if (board[0][0] == 'O')
{
return -1;
}
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
{
if (board[0][2] == 'X')
{
return 1;
}
else if (board[0][2] == 'O')
{
return -1;
}
}
return 0;
}
int evaluate()
{
return (checkWin() * -1) * (availableMoves().size() + 1);
}
Board& operator=(Board& b)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = b.board[i][j];
}
}
return (*this);
}
};
class TicTacToe
{
private:
Board board;
int turn;
int searches = 0;
public:
TicTacToe()
{
std::srand(time(0));
turn = std::rand() % 2;
}
int minimax(int depth, Board curBoard, bool is_max)
{
searches++;
if (depth == 0 || curBoard.checkWin() != 0)
{
return board.evaluate();
}
if (is_max)
{
int max_eval = -2147483647;
for (int i = 0; i < curBoard.availableMoves().size(); i++)
{
curBoard.move(curBoard.availableMoves()[i], 'O');
depth -= 1;
int eval = minimax(depth, curBoard, false);
curBoard.revert(curBoard.availableMoves()[i]);
if (eval > max_eval)
{
max_eval = eval;
}
}
return max_eval;
}
if (!is_max)
{
int min_eval = 2147483647;
for (int i = 0; i < curBoard.availableMoves().size(); i++)
{
curBoard.move(curBoard.availableMoves()[i], 'X');
depth -= 1;
int eval = minimax(depth, curBoard, true);
curBoard.revert(curBoard.availableMoves()[i]);
if (eval < min_eval)
{
min_eval = eval;
}
}
return min_eval;
}
}
void game()
{
while (board.checkWin() == 0 && board.availableMoves().size() != 0)
{
board.displayBoard();
if (turn % 2 == 0)
{
std::cout << std::endl;
int choice;
std::cout << "Enter Your Move: ";
std::cin >> choice;
choice -= 1;
while (!in(board.availableMoves(), choice))
{
std::cout << "Enter A Valid Move: ";
std::cin >> choice;
}
board.move(choice, 'X');
std::cout << std::endl;
turn++;
}
board.displayBoard();
if (board.checkWin() != 0)
{
break;
}
if (turn % 2 == 1)
{
int ai = minimax(9 - (turn % 2), board, true);
std::cout << searches;
std::cin.get();
turn++;
}
}
if (board.checkWin() == 1)
{
std::cout << "You Won" << std::endl;
}
else if (board.checkWin() == -1)
{
std::cout << "You Lost" << std::endl;
}
else
{
std::cout << "Tie" << std::endl;
}
std::cout << "Would You Like To Play Again Y/N: ";
char playAgain;
std::cin >> playAgain;
if (playAgain == 'Y')
{
Board newBoard;
board = newBoard;
game();
}
}
};
int main()
{
TicTacToe ticTacToe;
ticTacToe.game();
}
Do you know how to debug? If not, you should definitely learn this, it's pretty helpful. But here's some things I found out.
The problem is not in availableMoves(), but in minimax(), more precisely in line 215, where the program calls curBoard. revert(curBoard. availableMoves()[i]).
void revert(int choice)
{
int y = choice / 3;
int x = choice - y * 3;
board[y][x] = (char)choice + 48;
}
for (int i = 0; i < curBoard.availableMoves().size(); i++)
{
curBoard.move(curBoard.availableMoves()[i], 'X');
depth -= 1;
int eval = minimax(depth, curBoard, true);
curBoard.revert(curBoard.availableMoves()[i]);
if (eval < min_eval)
{
min_eval = eval;
}
}
The error happens in the function revert, but I am not sure why. Maybe availableMoves also returns something wrong. Variable i is permanently 0 in the for-loop. So it is possible that there is something wrong at position 0 of the vector moves, which revert cannot handle. Try debugging yourself, maybe you'll find the problem.
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.
#include <iostream>
#include <string>
#define GRID_SIZE 3
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void champion() {
const char *possiblities[8]{
"123"
"456"
"789"
"147"
"159"
"258"
"369"
"753"
};
for (int i = 0; i < 8; i++) {
bool winner = true;
char previous_pos = '0';
const char *possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - 1;
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if
(previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char) 'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
tictacToeMap();
playgame();
champion();
}
}
};
int main() {
TicTacToe tic;
tic.playgame();
return 0;
}
The problem is here:
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
You probably meant:
if (winner == true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
First, do what Max Meijer said, by replacing if(winner = true) with if(winner == true). But the program is still broken. The problem is that in your string array, you are not separating each string with a comma, so when my debugger hits const char *possible_moves, it ends up just assigning the entire array concatenated together. So just separate each string in the possibilities array with a comma, like so:
const char *possiblities[8]{
"123",
"456",
"789",
"147",
"159",
"258",
"369",
"753"
};
I want the program to print "You win" when any of the instances in the champion() function are given. It only shows a winner when "123" is inputted. Whenever three X's are displayed anywhere else the program continues. For instance if three X's are given diagonally the program will still continue. Novice programmer so any criticism is greatly appreciated.
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void computers_turn() {
while (true) {
int choice = (rand() % 9) + 1;
int row = choice / 3;
int col = choice % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'O';
break;
}
}
}
void champion() {
const char* possiblities[8] = {"123", "456", "789", "147",
"258", "369", "159", "753"};
for (int i = 0; i < 8; i++) {
char previous_pos = '0';
bool winner = true;
const char* possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - '1';
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if (previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner) {
puts("You win");
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
champion();
tictacToeMap();
playgame();
computers_turn();
}
}
};
int main() {
TicTacToe ticTacToe;
return 0;
}
As the title states i'm having trouble finding the error with the way in which my queue is being populated. It should be holding every visited state node until they have been processed. but the queue is not being populated as it should be. Can anyone help me find the bug? Below is my implementation file for the PuzzleStateNode class and source.cpp
EDIT: After more debugging it would seem that the problem lies with the following chunk of code from the solvePuzzle function. The items are never pushed to my queue, and I don't understand why. Could it be an issue with my unordered_set?
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
END EDIT:
PuzzleStateNode.h
#pragma once
#include<queue>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
class PuzzleStateNode
{
public:
PuzzleStateNode();
PuzzleStateNode(string tempArray[3][3]);
PuzzleStateNode(const PuzzleStateNode &other);
int getEmptyXArrayPos();
int getEmptyYArrayPos();
int getMoveCounter();
string getPuzzleID();
bool parityCheck();
bool checkForSolve();
void setPuzzleID();
void setEmptyXArrayPos(int x);
void setEmptyYArrayPos(int y);
void incrimentMoveCounter();
void pushToMoveQueue(string move);
void moveEmptySquareDown(int xEmptyPos, int yEmptyPos);
void moveEmptySquareUp(int xEmptyPos, int yEmptyPos);
void moveEmptySquareRight(int xEmptyPos, int yEmptyPos);
void moveEmptySquareLeft(int xEmptyPos, int yEmptyPos);
void printState(ofstream &oFile);
void printMoves(ofstream &oFile);
~PuzzleStateNode();
private:
string puzzleStateArray[3][3];
int moveCounter;
queue<string> moveQueue;
int emptyXArrayPos;
int emptyYArrayPos;
string puzzleID;
};
PuzzleStateNode.cpp
#include "PuzzleStateNode.h"
using namespace std;
PuzzleStateNode::PuzzleStateNode()
{
}
PuzzleStateNode::PuzzleStateNode(string tempArray[3][3])
{
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = tempArray[i][j];
puzzleID += tempArray[i][j];
if (puzzleStateArray[i][j] == "E") {
emptyXArrayPos = j;
emptyYArrayPos = i;
}
}
}
moveCounter = 0;
moveQueue.push("The following lists the movement of the Empty or 'E' square until the puzzle is solved: ");
}
PuzzleStateNode::PuzzleStateNode(const PuzzleStateNode &other) {
{ puzzleID = "";
moveCounter = other.moveCounter;
moveQueue = other.moveQueue;
emptyXArrayPos = other.emptyXArrayPos;
emptyYArrayPos = other.emptyYArrayPos;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = other.puzzleStateArray[i][j];
puzzleID += other.puzzleStateArray[i][j];
}
}
}
}
int PuzzleStateNode::getEmptyXArrayPos() {
return emptyXArrayPos;
}
int PuzzleStateNode::getEmptyYArrayPos() {
return emptyYArrayPos;
}
int PuzzleStateNode::getMoveCounter() {
return moveCounter;
}
string PuzzleStateNode::getPuzzleID() {
return puzzleID;
}
bool PuzzleStateNode::checkForSolve() {
if (puzzleStateArray[0][0] == "1" && puzzleStateArray[0][1] == "2" && puzzleStateArray[0][2] == "3" && puzzleStateArray[1][0] == "4" && puzzleStateArray[1][1] == "5" && puzzleStateArray[1][2] == "6" && puzzleStateArray[2][0] == "7" && puzzleStateArray[2][1] == "8" && puzzleStateArray[2][2] == "E") {
return true;
}
return false;
}
void PuzzleStateNode::setPuzzleID() {
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleID += puzzleStateArray[i][j];
}
}
}
void PuzzleStateNode::setEmptyXArrayPos(int x) {
emptyXArrayPos = x;
}
void PuzzleStateNode::setEmptyYArrayPos(int y) {
emptyXArrayPos = y;
}
void PuzzleStateNode::incrimentMoveCounter() {
moveCounter++;
}
void PuzzleStateNode::pushToMoveQueue(string move) {
moveQueue.push(move);
}
void PuzzleStateNode::printMoves(ofstream &oFile) {
string tempString;
for (int i = 0; i < moveQueue.size(); i++) {
cout << moveQueue.front() << endl;
moveQueue.push(moveQueue.front());
moveQueue.pop();
}
cout << endl << endl;
}
void PuzzleStateNode::printState(ofstream &oFile) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << puzzleStateArray[i][j];
}
cout << endl;
}
cout << endl;
}
void PuzzleStateNode::moveEmptySquareDown(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos + 1][xEmptyPos];
puzzleStateArray[yEmptyPos + 1][xEmptyPos] = "E";
moveQueue.push("Down");
moveCounter++;
cout << "Moving Down" << endl;
emptyYArrayPos = yEmptyPos + 1;
}
void PuzzleStateNode::moveEmptySquareUp(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos - 1][xEmptyPos];
puzzleStateArray[yEmptyPos - 1][xEmptyPos] = "E";
moveQueue.push("Up");
moveCounter++;
cout << "Moving Up" << endl;
emptyYArrayPos = yEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareLeft(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos - 1];
puzzleStateArray[yEmptyPos][xEmptyPos - 1] = "E";
moveQueue.push("Left");
moveCounter++;
cout << "Moving Left" << endl;
emptyXArrayPos = xEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareRight(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos + 1];
puzzleStateArray[yEmptyPos][xEmptyPos + 1] = "E";
moveQueue.push("Right");
moveCounter++;
cout << "Moving Right" << endl;
emptyXArrayPos = xEmptyPos + 1;
}
bool PuzzleStateNode::parityCheck() // counts number of swaps for a bubble sort excluding swaps involving the empty space
{
enter code here
// Puzzles with odd swaps have odd parity and are unsolvable.
string parityCheckString = "";
char tempChar;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
parityCheckString += puzzleStateArray[i][j];
}
}
int counter = 0;
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
if (parityCheckString[i] > parityCheckString[i + 1]) {
if (parityCheckString[i] == 'E') {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
}
else {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
counter += 1;
}
}
}
}
if (counter % 2 == 0) {
cout << "Even Parity, solving the 8 puzzle!" << endl;
return true;
}
else {
cout << "Parity is odd and puzzle is unsolvable. Skipping to next Puzzle." << endl;
return false;
}
}
PuzzleStateNode::~PuzzleStateNode()
{
}
source.cpp
#include"PuzzleStateNode.h"
#include<string>
#include<fstream>
#include<iostream>
#include<unordered_set>
using namespace std;
int main() {
void solvePuzzle(string stateArray[3][3]);
ifstream inFile("input.txt");
ofstream outFile("output.txt");
string puzNum;
int numberOfPuzzles;
string junk;
getline(inFile, puzNum); // read number of puzzles
numberOfPuzzles = stoi(puzNum); // convert value to int.
for (int i = 0; i < numberOfPuzzles; i++) {
string stateArray[3][3]; // populates a temporary puzzle state.
string temp;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
while (temp != "1" && temp != "2" && temp != "3" && temp != "4" && temp != "5" && temp != "6" && temp != "7" && temp != "8" && temp != "E") {
temp = inFile.get();
}
stateArray[i][j] = temp;
temp = inFile.get();
}
}
solvePuzzle(stateArray);
}
system("pause");
return 0;
}
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
if (myTempState.getEmptyXArrayPos() == 1 || myTempState.getEmptyXArrayPos() == 2) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareLeft(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
tempState.incrimentMoveCounter();
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this state" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 0 || myTempState.getEmptyYArrayPos() == 1) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareDown(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have this state already" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 1 || myTempState.getEmptyYArrayPos() == 2) {
PuzzleStateNode tempState(myTempState);
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareUp(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "have visited this state already" << endl;
system("pause");
}
}
}
}
}
else
oFile.close();
return;
}
I found the problem! I was never resetting puzzle id's after copying so all puzzle states had the same ID for my set.
Good evening everyone, could anyone point me in the direction I need to go to get this code for a simple game of tic tac toe operational? I feel it is very close but I cannot get it to behave properly. Also, what could I use instead of break commands under the drawBoard command? Thanks in advance..
#include <iostream>
// This program allows user(s) to play a game of tic-tac-toe.
using namespace std;
// constants
const char SIGIL[3] = { '.', 'X', 'O' };
// prototypes
int winner(int board[3][3]);
void drawBoard(int board[3][3]);
bool isMoveLegal(int board[3][3]);
bool isGameOver(int board[3][3]);
// return 1 if player 1 'X' has won
// return 2 if player 2 'O' has won
// return 0 if neither player has won
int winner(int board[3][3]){
int win = 0;
// Checks for:
// X X X
for (int i = 0; i < 3; i++)
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
win = board[i][0];
// Checks for:
// X
// X
// X
for (int i = 0; i < 3; i++)
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
win = board[0][i];
// Checks for:
// X X
// X or X
// X X
if ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) ||
(board[0][2] == board[1][1] && board[1][1] == board[2][0]))
win = board[1][1];
return win;
}
// using this board as a guide
// draw the board using "." for empty squares
// or 'X' or 'O' for player 1 or player 2
void drawBoard(int board[3][3]){
cout << " 0 1 2" << endl;
for (int i = 0; i < 3; i++){
cout << i ;
for (int j = 0; j < 3; j++){
cout.width(3);
switch (board[i][j])
{
case 0:{
cout << ".";
}break; case 1:{
cout << "X";
}break;
case 2:{
cout << "0";
}break;
default:
break;
}
} cout << endl;
}
}
// return false if row or column are out of bounds
// or if that spot on the board is already taken
// otherwise return true
bool isMoveLegal(int board[3][3], int row, int column){
if (row >= 0 && row <= 3 && column <= 3 && column >= 0) {
if (board[row][column] == 0)
return true;
else return false;
}
return false;
}
// if any player has three in a row or if the board is full
// return true otherwise return false
bool isGameOver(int board[3][3]){
if (winner(board) == 1 || winner(board) == 2) return true;
for (int r = 0; r <= 2; r++)
for (int c = 0; c <= 2; c++)
if (board[r][c] == 0)
return false;
return true;
}
int main(){
int board[3][3] = { { 0 } }; // 0 for empty square, 1 or 2 for taken squares
int player = 1;
int row, column, result;
bool legalMove;
// starting board
drawBoard(board);
while (!isGameOver(board)){
cout << "Player " << player << "(" << SIGIL[player] << "), your move?";
cin >> row >> column;
legalMove = isMoveLegal(board, row, column);
while (!legalMove){
cout << "Player " << player << "(" << SIGIL[player] << "), your move?";
cin >> row >> column;
legalMove = isMoveLegal(board, row, column);
}
board[row][column] = player;
drawBoard(board);
player = 3 - player;
}
// game over
result = winner(board);
if (result == 0){
cout << "Tie Game" << endl;
}
else {
cout << "Player " << result << "(" << SIGIL[result] << ") wins!" << endl;
}
return 0;
}
This piece of code will go out of bounds:
bool isMoveLegal(int board[3][3], int row, int column){
if (row >= 0 && row <= 3 && column <= 3 && column >= 0) {
if (board[row][column] == 0)
return true;
else return false;
}
Remember that arrays are 0-indexed, so it should be:
bool isMoveLegal(int board[3][3], int row, int column){
if (row >= 0 && row < 3 && column < 3 && column >= 0) {
if (board[row][column] == 0)
return true;
else return false;
}
Your break statements in drawBoard are for the switch statement, not a loop. They are okay, however, you should use board[i][j] as an index into SIGIL:
// constants
const char SIGIL[3] = { '.', 'X', 'O' };
// ...
void drawBoard(int board[3][3])
{
cout << " 0 1 2\n";
for (int i = 0; i < 3; ++i)
{
cout << i ;
for (int j = 0; j < 3; ++j)
{
cout << SIGIL[board[i][j]] << " ";
}
cout << endl;;
}
}