Need assistance with a for loop in Tic Tac Toe game - c++

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"
};

Related

I got the error code -1073741571 in my snake game

I'm making a snake game and it's basically done; however sometimes when I run it it works at first then clears (that might be in my code, it has a lot of clears) and returns error code -1073741571.
This is the code:
#include <iostream>
#include <string>
#include <stdio.h>
#include <conio.h>
#include "windows.h"
#include <vector>
#include <random>
#include <ctime>
#include <cmath>
#include <windows.h>
using namespace std;
struct point
{
int x;
int y;
};
bool goTo(point p,vector<point>& snek)
{
bool flag=false;
for (size_t i = 0; i < snek.size(); i++)
{
if (p.x == snek[i].x && p.y == snek[i].y)
{
return true;
}
}
for (int i=snek.size()-1; i >0; i--)
{
snek[i] = snek[i - 1];
}
snek[0] = p;
return false;
}
void makeFood(point& apple, vector<point> snek)
{
bool appleValid = true;
apple.x = (rand() % 19) + 1;
apple.y = (rand() % 19) + 1;
for (int i = 0; i < snek.size() - 1; i++)
{
if (apple.x == snek[i].x && apple.y == snek[i].y)
{
appleValid = false;
break;
}
}
if (!appleValid)
{
srand(time(NULL));
makeFood(apple,snek);
}
}
int main()
{
vector<point> snek;
snek.push_back({ 10,10 });
snek.push_back({ 10,9 });
snek.push_back({ 10,8 });
snek.push_back({ 10,7 });
int highscore= 0, score;
bool tutorial = false;
bool p = false;
char move = 'w';
char sure = 'f';
string board[21][21];
int direction=2;
point apple;
apple.x = rand() % 20;
apple.y = rand() % 20;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
board[i][j] = " ";
}
}
bool loss = false;
while (true)
{
score = snek.size() - 4;
bool appleEaten = false;
srand(time(NULL));
if (snek[0].x == 0 )
loss = true;
if (snek[0].x == 20 )
loss = true;
if (snek[0].y == 0 )
loss = true;
if (snek[0].y == 20 )
loss = true;
if (loss)
{
system("CLS");
if (score > highscore)
{
highscore = score;
}
cout << "You lost with a score of " << snek.size() - 4 << endl;
cout << "Your highscore for this session is " << highscore<<endl;
cout << "Press any key to play again" << endl;
cout << "Press RMB to quit" << endl;
while (true)
{
if (GetAsyncKeyState(VK_RBUTTON))
{
system("CLS");
cout << "Are you sure you want to quit? Your highscore for this session will be reset" << endl;
cout << "Press Q to quit and P to play again" << endl;
sure = _getch();
if (sure == 'q' || sure == 'Q')
{
_Exit(0);
}
if (sure == 'p' || sure == 'P')
{
p = true;
}
}
if (_kbhit() || p)
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
board[i][j] = " ";
}
}
snek.clear();
snek.push_back({ 10,10 });
snek.push_back({ 10,9 });
snek.push_back({ 10,8 });
snek.push_back({ 10,7 });
loss = false;
p = false;
break;
}
}
}
Sleep(100);
if (_kbhit())
{
move = _getch();
}
system("CLS");
switch (move)
{
case 'w':
loss = goTo({ (snek[0].x - 1),snek[0].y }, snek);
Sleep(10);
break;
case 'a':
loss = goTo({ snek[0].x ,(snek[0].y - 1) }, snek);
Sleep(10);
break;
case 's':
loss = goTo({ (snek[0].x + 1),snek[0].y }, snek);
Sleep(10);
break;
case'd':
loss = goTo({ snek[0].x ,(snek[0].y + 1) }, snek);
Sleep(10);
break;
}
board[apple.x][apple.y] = " 0";
for (int k = 0; k < snek.size() - 1; k++)
{
board[snek[k].x][snek[k].y] = " *";
board[snek[snek.size() - 1].x] [snek[snek.size() - 1].y] = " ";
}
if (apple.x == snek[0].x && apple.y == snek[0].y)
{
snek.push_back({snek[snek.size()-1].x+1,snek[snek.size() - 1].y});
appleEaten = true;
}
if (appleEaten)
{
makeFood(apple,snek);
}
for (int i = 0; i < 20; i++)
{
board[0][i] = "--";
board[20][i] = "--";
}
for (int i = 0; i < 20; i++)
{
board[i][0] = '|';
board[i][20] = '|';
}
if (!tutorial)
{
cout << "You are a snake." << endl;
cout << "Your body looks like this" << endl;
cout << "*****" << endl;
cout << "Move with WASD" << endl;
cout << "If you eat the apples, which look like this " << endl << "0" << endl;
cout << "You get bigger. If you try to eat yourself or run into walls, you lose" << endl;
cout << "Click RMB to begin";
while (true)
{
if (GetAsyncKeyState(VK_RBUTTON))
{
system("CLS");
tutorial = true;
break;
}
}
}
for (int i = 0; i < 21; i++)
{
for (int j = 0; j < 21; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << "Score: " << score;
}
}
EDIT: Most of the time it works fine, only sometimes I get the error
EDIT: The stack overflow is in int main()
Let’s take a closer look at your makeFood function:
void makeFood(point& apple, vector<point> snek)
{
bool appleValid = true;
apple.x = (rand() % 19) + 1;
apple.y = (rand() % 19) + 1;
for (int i = 0; i < snek.size() - 1; i++)
{
if (apple.x == snek[i].x && apple.y == snek[i].y)
{
appleValid = false;
break;
}
}
if (!appleValid)
{
srand(time(NULL));
makeFood(apple,snek);
}
}
Your if statement makes it so that makeFood() is called again when the apple is at the snakes position, but using srand(time(NULL)) will put the apple back into the same place, which calls the function again and again for an infinite amount of time. Remove srand(time(NULL)) in the if(!appleValid) and your program shouldn’t have the issue because you only need to seed random.
if you can, try to convert your random functions to the <random> header, but it should work fine with rand as well :)

C++ tic tac toe game only wins with one combination

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;
}

8 Puzzle Code. Having Issues with my my queue not populating and i can not find the location of my bug

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.

C++ Tic Tac toe game not showing X character

Novice programmer here. Trying to make a tic tac toe game. Everything so far works, except the character X doesn't appear. In the for loop is where I believe I have a problem but I cant seem to find anything wrong. Please help, any criticism is greatly appreciated. Good and bad. Thanks.
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 ();
}
}
};
int main() {
TicTacToe tic;
return 0;
}
int entered_num = entered - 0;
Should be:
int entered_num = entered - '0';
To convert a '1' into a 1, you need to subtract '0' (the character we use to represent the digit zero), not 0 (the number zero). Subtracting zero doesn't do anything.

What character is this?

I'm writing a simple program to generate a box with a user-defined sidelength and border/fill characters. Everything is working as I want it to, except when it prints the box to the terminal, it produces a strange character I cannot find anywhere. I feel like if I know what it is, I might be able to fix it. My header file is here:
#ifndef Box_h
#define Box_h
class Box
{
private:
int pSidelength;
char pBorder;
char pFill;
public:
Box(int pSidelength, char pBorder = '#', char pFill = '*');
int Sidelength;
char Border;
char Fill;
int Area();
int Perimeter();
int GetSize();
int Grow();
int Shrink();
char SetBorder();
char SetFill();
void Draw();
void Summary();
};
#endif Box_h
My source for the class is:
#include <iostream>
#include "box.h"
#include <iomanip>
using namespace std;
Box::Box(int pSidelength, char pBorder, char pFill)
{
if (pSidelength < 1)
{
Sidelength = 1;
}
else if (pSidelength > 39)
{
Sidelength = 39;
}
else
{
Sidelength = pSidelength;
}
if (pBorder != '#')
{
SetBorder();
}
if (pFill != '*')
{
SetFill();
}
}
int main(void)
{
Box MyBox1(3,'#','*');
Box MyBox2(7, '^', '*');
Box MyBox3(10, '$', '%');
MyBox1.Grow();
MyBox2.Shrink();
MyBox1.Summary();
MyBox2.Summary();
MyBox3.Summary();
return 0;
}
int Box::Shrink()
{
if (Sidelength == 1)
{
Sidelength = Sidelength;
}
else
{
Sidelength = Sidelength - 1;
}
return Sidelength;
}
int Box::Grow()
{
if (Sidelength == 39)
{
Sidelength = Sidelength;
}
else
{
Sidelength = Sidelength + 1;
}
return Sidelength;
}
char Box::SetFill()
{
Fill = pFill;
return Fill;
}
char Box::SetBorder()
{
Border = pBorder;
return Border;
}
int Box::Area()
{
int area = (Sidelength)*(Sidelength);
return area;
}
int Box::Perimeter()
{
int perimeter = 4 * (Sidelength);
return perimeter;
}
int Box::GetSize()
{
int size = Sidelength;
return size;
}
void Box::Draw()
{
int j = 1;
int k = 1;
if (Sidelength == 1 || Sidelength == 2)
{
for (int i = 1; i <= Sidelength; i++)
{
while (j <= Sidelength)
{
cout << setw(2) << Border;
j++;
}
j = 1;
}
cout << endl;
}
else
{
for (int i = 1; i <= Sidelength; i++)
{
if (i == 1 || i == Sidelength)
{
while (k <= Sidelength)
{
cout << setw(2) << Border;
k++;
}
cout << endl;
k = 1;
}
else
{
while (j <= Sidelength)
{
if (j == 1 || j == Sidelength)
{
cout << setw(2) << Border;
}
else
{
cout << setw(2) << Fill;
}
j++;
}
cout << endl;
j = 1;
}
}
cout << endl;
}
}
void Box::Summary()
{
cout << "The Sidelength of the box is: " << Box::GetSize() << endl;
cout << "The Perimeter of the box is: " << Box::Perimeter() << endl;
cout << "The Area of the box is: " << Box::Area() << endl;
Box::Draw();
}
The program has a default character associated with Border/Fill, as specified in the header file. When run, it produces this:
What character is that, and any ideas on why it would be appearing in the first place?
The character is random, and could in theory be different every time you run the program.
It's coming from the pBorder member, which is never set to anything.
You got confused with same name of variables.
Box::Box(int pSidelength, char pBorder, char pFill)
{
if (pSidelength < 1)
{
Sidelength = 1;
}
else if (pSidelength > 39)
{
Sidelength = 39;
}
else
{
Sidelength = pSidelength;
}
if (pBorder != ' ') //Here pBorder has '*' but this is local
// pBorder to this Function
{
SetBorder();
}
if (pFill != ' ')
{
SetFill();
}
}
And When you call SetBorder();
It makes Border as pBorder as that was declared in the class which is still unintialized.
char Box::SetBorder()
{
Border = pBorder; //This pBorder is not initialized
return Border;
}
Solution 1
Dont use Function
if (pBorder != ' ')
{
Border = pBorder;
}
Solution 2
Pass pBorder
if (pBorder != ' ')
{
SetBorder(pBorder);
}
char Box::SetBorder(char pBorder)
{
Border = pBorder; //This pBorder is not initialized
return Border;
}