So I am making a tic-tac-toe game in c . Here is my code so far:
#include <iostream>
#include <cmath>
using namespace std;
char gameboard[3][3]{{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}}; //Declares the Global Array for the Board
char turn = 'X';
int column = 0;
int row = 0;
void PrintBoard() { //Displays the board
cout << " | | \n";
cout << " "<<gameboard[0][0]<<" | " <<gameboard[0][1]<<" | " <<gameboard[0][2]<< " \n";
cout << "____|____|____\n";
cout << " | | \n";
cout << " "<<gameboard[1][0]<<" | " <<gameboard[1][1]<<" | " <<gameboard[1][2]<< " \n";
cout << "____|____|____\n";
cout << " | | \n";
cout << " "<<gameboard[2][0]<<" | " <<gameboard[2][1]<<" | " <<gameboard[2][2]<< " \n";
cout << " | | \n";
}
void PlaceCounter(int TileNum, char Tile) {
int LocalRow = 0;
int LocalColumn = 0;
LocalRow = (floor(Tile/3))-1;
LocalColumn = (TileNum - LocalRow) - 1;
gameboard[LocalRow][LocalColumn] = Tile;
PrintBoard();
}
void RunTurn(char playerturn) {
char LocalTurnTile = ' ';
switch(turn) {
case 'X':
cout << "It is X's turn. Enter the number corresponding to the tile you want to select: ";
cin >> LocalTurnTile;
PlaceCounter(LocalTurnTile, playerturn);
break;
case 'O':
cout << "It is O's turn. Enter the number corresponding to the tile you want to select: ";
cin >> LocalTurnTile;
PlaceCounter(LocalTurnTile, playerturn);
break;
}
}
void GameLoop() {
RunTurn(turn);
}
int main() //Main Function
{
PrintBoard();
GameLoop();
}
The issue is, whenever the function Print Board is called upon for the second time, in the function PlaceCounter, in order to update the screen, it doesn't change, and displays the same thing. Here is the output
| |
1 | 2 | 3
____|____|____
| |
4 | 5 | 6
____|____|____
| |
7 | 8 | 9
| |
It is X's turn. Enter the number corresponding to the tile you want to select: 5
| |
1 | 2 | 3
____|____|____
| |
4 | 5 | 6
____|____|____
| |
7 | 8 | 9
| |
I don't know what shouldn't be working. The 5 square (center) should update to an X, but it isn't. I am quite new to c and need some help. If anyone knows what's going on, I would love your help. I've looked on the internet, and no one has had the same issue as me before. I looked all through the code, and can't seem to put my finger on what isn't working.
CodePudding user response:
Your math is out and you have a typo (wrong variable)
This is the correct code (I'm assuming TileNum
has a values from 1 to 9)
LocalRow = (TileNum - 1)/3;
LocalColumn = (TileNum - 1)%3;
Note that when you divide one integer by another you always get another integer, so floor
is unnecessary.