have a problem with this coding, how to check and display the winner? I have tried to add it but turns into error due to the function checkWinner().
#include <iostream>
using namespace std;
void showBoard(void);
void playerInput(int p);
void checkWinner();
void nextPlayer(int);
int board[3][3]={{0,0,0},{0,0,0},{0,0,0}};
int main()
{
int r;
int c;
int player;
int winner;
int turns;
cout << "******* Tic Tac Toe Game *******" << endl;
showBoard();
nextPlayer(1);
checkWinner();
return 0;
}
Output board function:
void showBoard(void)
{
int r;
int c;
for(r=0; r<=2; r++)
{
for(c=0; c<=2; c++)
{
if( board [r][c]==0)
cout << "0 ";
else if (board [r][c]==1)
cout << "1 ";
else
cout << "2 ";
}
cout << endl;
}
}
This is the player input function:
void playerInput(int p)
{
int row;
int col;
if(p==1)
cout <<"You are player number 1 \n\n";
else
cout <<"You are player number 2 \n\n";
cout<<"Please enter your coordinate:";
cin>>row;
cout<<"\n";
cin>>col;
if(p==1)
board[--row][--col]=1;
if(p==2)
board[--row][--col]=2;
}
Heres the problem I'm facing now, how to make it display the winner?
void checkWinner()
{
int winner;
for (int i=0; i<=2; i++)
{
if(board[i][0]==board[i][1] && board[i][1]==board[i][2] && board[i][0]!=0)
{
winner=board[i][0];
}
}
for(int i=0; i<=2; i++)
{
if (board[0][i]==board[1][i] && board[1][i]==board[2][i] && board[0][i]!=0)
{
winner=board[0][i];
}
}
if(board[0][0]=board[1][1] && board[1][1]==board[2][2] && board[0][0]!=0)
{
winner=board[0][0];
}
if(board[0][2]=board[1][1] && board[1][1]==board[2][0] && board [0][2]!=0)
{
winner=board[0][2];
}
if(board[0][0]==board[0][1] && board[0][1]==board[0][2]&& board[0][2]==board[0][1]&& board[1][0]==board [1][1]&& board[1][1]==board [1][2]&& board[1][2]==board[2][0]&&board[2][0]==board [2][1]&& board[2][1]==board [2][2] && board [0][0]!=0)
{
winner=0;
}
}
void nextPlayer(int player)
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
The problem is the game is not ended but it still asking for the player to resume and it keep updating the value.
click below to see the problem I'm facing. Thanks!
Click to view my output, it doesn't end the game
Your code has a serious recursion problem. The function checkWinner() in main never gets called because the function nextPlayer(1); is infinitely recursive, since, it lacks a base case.
A recursive base case, is what causes a recursive function to stop its recursion.
Note that in your code:
void nextPlayer(int player)
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
once nextPlayer(1); is called from main, it never returns, because, it always enters into another call of its own nextPlayer(player); at the end of the function. For this you need a base case to stop this recursion at some point from happening.
Now, logically your base case should actually be, checking for a winner before proceeding to play, which is what is handled by the checkWinner() function.
But, the problem is that the checkWinner() function returns void which means nothing so, in its current state, we cannot use it as a base case.
However, if we redesign it to return something such as:
0 for play on
1 or 2 indicating a player has won
and lastly -1 indicating that the board is full and nobody won (a tie).
So, reforming the checkWinner() function as (I also corrected a few conditions so have a close look at the code):
int checkWinner()
{
int winner;
// any of the rows is same
for (int i=0; i<=2; i++)
{
if(board[i][0]==board[i][1] && board[i][1]==board[i][2] && board[i][0]!=0)
{
winner = board[i][0];
return winner;
}
}
// any of the columns is same
for(int i=0; i<=2; i++)
{
if (board[0][i]==board[1][i] && board[1][i]==board[2][i] && board[0][i]!=0)
{
winner = board[0][i];
return winner;
}
}
// 1st diagonal is same
if(board[0][0]==board[1][1] && board[1][1]==board[2][2] && board[0][0]!=0)
{
winner = board[0][0];
return winner;
}
// 2nd diagonal is same
if(board[0][2]==board[1][1] && board[1][1]==board[2][0] && board [0][2]!=0)
{
winner = board[0][2];
return winner;
}
// if we reached here nobody has won yet
// if any empty box on board then play on
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++)
{
if(board[i][j]==0)
{
winner = 0;
return winner;
}
}
}
winner = -1; // all boxes full and nobody won so A tie has occurred
return winner;
}
Now, that it can be used, we will use it in void nextPlayer(int player) function as:
void nextPlayer(int player)
{
int winner = checkWinner();
if( winner == 0) // play on
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
else if(winner == -1)
{
cout<<"\nGame drawn!\n";
}
else
{
cout<<"\nPlayer "<<winner<<" wins!\n"<<endl;
}
}
Note that, the checkWinner() condition is checked before we start to do anything.
And now, the call to checkWinner() in the main function, which was unreachable anyways, is not needed and will now be done before proceeding at every step in void nextPlayer(int player):
#include <iostream>
using namespace std;
void showBoard(void);
void playerInput(int p);
int checkWinner();
void nextPlayer(int);
int board[3][3]={{0,0,0},{0,0,0},{0,0,0}};
int main()
{
int r;
int c;
int player;
int winner;
int turns;
cout << "******* Tic Tac Toe Game *******" << endl;
showBoard();
nextPlayer(1);
return 0;
}
The rest of the functions are correct and will remain the same.
At two points in your code, you have used = in your if statement. This leads to initialization instead of equality checking. You should use == instead of the =.
if (board[0][0] = board[1][1] && /** This should be a == for checking equality */
board[1][1] == board[2][2] &&
board[0][0] != 0)
{
winner=board[0][0];
}
if (board[0][2] = board[1][1] && /** This should be a == for checking equality */
board[1][1] == board[2][0] &&
board[0][2] != 0)
{
winner = board[0][2];
}
Related
Whenever I run my program I check to see if I would place down 3 os it goes to the right. I know that the problem is that I have a bunch of if statements that cycle through, but I have a for loop there to place down the snakes trail. I know that all those ifs aren't good.
I tried changing in the top of the for loop to be a if statement that was always true, it didn't work nothing did. I am confused on how to check for all of the coordinates, but still not have the walls pop up on the sides.
I am a begginer, so don't hate on my code that much.
snake.cpp
#include <iostream>
#include <conio.h>
#include <random>
#include <time.h>
#include "snake.hpp"
void endGame(int score);
const int KEY_ARROW_CHAR1 = 224;
const int KEY_ARROW_UP = 72;
const int KEY_ARROW_DOWN = 80;
const int KEY_ARROW_LEFT = 75;
const int KEY_ARROW_RIGHT = 77;
void snake::input() {
// checks for arrow key input
if (_kbhit()) {
//stores keycode
int key = _getch();
//checks if key is arrow key
if (key == KEY_ARROW_CHAR1) {
//stores arrow key
key = _getch();
//checks if arrow key is up
if (key == KEY_ARROW_UP) {
direction = '^';
}
//checks if arrow key is down
else if (key == KEY_ARROW_DOWN) {
direction = 'v';
}
//checks if arrow key is left
else if (key == KEY_ARROW_LEFT) {
direction = '<';
}
//checks if arrow key is right
else if(key == KEY_ARROW_RIGHT) {
direction = '>';
}
}
}
switch (direction) {
case '^':
snakeCoords[2]--;
break;
case 'v':
snakeCoords[2]++;
break;
case '>':
snakeCoords[0]++;
break;
case '<':
snakeCoords[0]--;
}
checkForObjects();
}
bool snake::checkForObjects() {
if ((snakeCoords[0] == 40 || snakeCoords[0] == 0) || (snakeCoords[2] == 20 || snakeCoords[2] == 0)) {
endGame(score);
}
if (snakeCoords[0] == fruitCoords[0] && snakeCoords[2] == fruitCoords[2]) {
score++;
getFruitLoc();
return true;
}
return false;
}
void snake::getFruitLoc() {
srand(time(0));
fruitCoords[0] = rand() % 39;
fruitCoords[2] = rand() % 19;
}
void endGame(int score) {
std::cout << "you died, your score was " << score;
exit(0);
}
```
#include <iostream>
#include <conio.h>
#include <random>
#include "snake.hpp"
#include <vector>
void createArena(char direction);
//Coordinates for snake
std::vector <std::vector<int>> previousCoords{
{14, 10},
{13, 10},
{12, 10}
};
snake coordManager{};
int score{0};
int main()
{
//make terminal green
system("color 0a");
while (true) {
std::cout << "\t" << score;
//pushes ascii arena down
for (size_t i{}; i <= 5; i++) {
std::cout << std::endl;
}
score = coordManager.score;
//updates snake based on coordinates
createArena(coordManager.direction);
//manages all snake movements
coordManager.input();
//reminder this clears the screan
system("CLS");
}
}
void createArena(char direction) {
//offsets screen
std::cout << "\t\t\t\t";
for (size_t y{}; y <= 20; y++) {
for (size_t x{}; x <= 40; x++) {
//checks if it hits the snakes coordinates
for (size_t i{}; i < previousCoords.size();) {
if (x == previousCoords.at(i).at(0) && y == previousCoords.at(i).at(1)) {
std::cout << "O";
}
i++;
}
if (coordManager.snakeCoords[0] == x && coordManager.snakeCoords[2] == y) {
std::cout << direction;
}
else if (x == 0 || x == 40) {
std::cout << '|';
}
else if (y == 0 || y == 20) {
std::cout << '-';
}
else if(coordManager.fruitCoords[0] == x && coordManager.fruitCoords[2] == y) {
std::cout << "F";
}
else {
std::cout << " ";
}
}
//offsets again
std::cout << std::endl << "\t\t\t\t";
}
}
#include <conio.h>
#include <random>
#include <time.h>
class snake {
public:
void input();
bool checkForObjects();
int score{};
int snakeCoords[2]{
/* X */ 15,
/* Y */ 10
};
int fruitCoords[2]{
/* X */ rand() % 39,
/* Y */ rand() % 19
};
char direction{'O'};
private:
void getFruitLoc();
};
https://i.stack.imgur.com/bdSNf.png
I got it working, I used a boolean that I would change if it was different from whitespace. it was a simple fix sorry.
I am making a card game, Crazy Eights, I have everything done except I am having a problem with this AI. The AI needs to delete the card it just played from its card options. (Each player is dealt 5 cards, and if the card matches the suit, value, or an 8, it can play). SO far, the computer does play the correct card, it just doesn't remove the card so it can just keep playing and playing.
Main Function
#include <iostream>
#include <time.h>
#include "CCrazyEight.h"
#include "stdafx.h"
using namespace std;
void main()
{
// Calls Crazy eight and declares a variable, then runs the game
CCrazyEight E1;
E1.Menu();
}
CCard Header File
#pragma once
#include <iostream>
#include <time.h>
#include "stdafx.h"
using namespace std;
enum CardSuit { Hearts, Diamonds, Spades, Clubs };
class CCard
{
friend ostream & operator << (ostream &left, CCard right);
private:
int value;
CardSuit suit;
public:
// Constructor, sets default values to suit and value
CCard()
{
value = 1;
suit = Hearts;
}
// return thes value of the card
int GetValue()
{
return value;
}
// returns the suit of the card
CardSuit GetSuit()
{
return suit;
}
// Passes values to CDeck constructor, which then randomizes values for the cards
void InitCard(CardSuit s, int v)
{
suit = s;
if (v > 0 && v < 14)
{
value = v;
}
}
};
// outputs value and suit of the card
ostream & operator << (ostream &left, CCard right)
{
if (right.value < 11 && right.value > 1)
{
left << right.value;
}
else if (right.value == 1)
{
left << "Ace";
}
else if (right.value == 11)
{
left << "Jack";
}
else if (right.value == 12)
{
left << "Queen";
}
else if (right.value == 13)
{
left << "King";
}
left << " of ";
if (right.suit == Hearts)
{
left << "Hearts";
}
else if (right.suit == Diamonds)
{
left << "Diamonds";
}
else if (right.suit == Spades)
{
left << "Spades";
}
else if (right.suit == Clubs)
{
left << "Clubs";
}
return left;
}
CDeck Header File
#pragma once
#include <iostream>
#include "CCard.h"
#include <time.h>
using namespace std;
class CDeck
{
private:
CCard Deck[52];
int TopCard;
public:
// constructor
// randomizes the card numbers for suit and value
CDeck()
{
srand(time(NULL));
TopCard = 0;
for (int suit = 0; suit < 4; suit++)
{
for (int value = 1; value <= 13; value++)
{
Deck[((suit * 13) + value) - 1].InitCard((CardSuit)suit, value);
}
}
}
// shuffles the deck, completely randomizes the cards
void Shuffle()
{
TopCard = 0;
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 52; x++)
{
int SwapPosition = rand() % 52;
CCard temp;
temp = Deck[x];
Deck[x] = Deck[SwapPosition];
Deck[SwapPosition] = temp;
}
}
}
// Draw a card function that gives out a card when called for in crazy eight
CCard DrawCard()
{
if (TopCard > 51)
{
cout << "Deck is Empty." << endl;
}
else
{
return Deck[TopCard++];
}
}
};
CrazyEight header file
#pragma once
#include <iostream>
#include <time.h>
#include "CCard.h"
#include "CDeck.h"
#include "CPlayer.h"
using namespace std;
// Having an issue trying to get the computer to play something different
class CCrazyEight
{
private:
CDeck d1;
CCard c1;
int index;
CCard Topcard;
CPlayer Computer;
CPlayer Human;
public:
// constructor
// shuffles the deck to the played, and assigns the topcard to start the game
CCrazyEight()
{
d1.Shuffle();
c1 = d1.DrawCard();
Topcard = c1;
}
// plays the game, dealing cards to computer and human
void PlayGame()
{
cout << "Welcome to Crazy Eight!" << endl;
cout << "You get to go first!" << endl;
cout << endl;
for (int k = 0; k < 5; k++)
{
Computer.GetCard(d1.DrawCard());
Human.GetCard(d1.DrawCard());
}
}
// displays the topmost card
void TopCard()
{
cout << Topcard << endl;
}
// displays the cards for the human, and the options they can chose, and anything else they need about the game
void Menu()
{
PlayGame();
while (Human.NumCards() != 0 || Computer.NumCards() != 0)
{
cout << endl;
cout << "Top Card is: "; TopCard();
cout << endl;
cout << "You Have " << Human.NumCards() << " Cards Left." << endl;
cout << "Your play: " << endl;
cout << "0) Draw Card" << endl;
cout << Human << endl;
cin >> index;
if (index == 0)
{
Human.GetCard(d1.DrawCard());
Topcard = Topcard;
}
else if (index > 0 && index <= Human.NumCards())
{
Topcard = Human.CardPlayed(index, Topcard);
}
cout << endl;
Topcard = Computer.ComputerAI(Topcard);
cout << "Computer Played: " << Topcard << endl;
if (Computer.NumCards() > 0)
{
cout << "Computer has " << Computer.NumCards() << " Cards Left." << endl;
}
else
cout << "You Lose!" << endl;
}
}
};
CPlayer Header File
#pragma once
#include "CCard.h"
#include <time.h>
#include <iostream>
using namespace std;
class CPlayer
{
friend ostream & operator << (ostream &left, CPlayer right);
private:
CCard Hand[25];
CDeck d1;
int NumberOfCard;
bool Computer;
const int MaxHand = 26;
bool TopCard;
public:
// Constructor for the computer, sets computer to true
CPlayer(bool computer = true)
{
Computer = computer;
NumberOfCard = 0;
}
// Computers AI, checks and sees if they can play, if not then they draw until they can play, or they play a card that is playable******Easy mode**** Lol
CCard ComputerAI(CCard Topcard)
{
for (int i = 0; i < NumberOfCard; i++)
{
if (Hand[i].GetSuit() == Topcard.GetSuit() || Hand[i].GetValue() == 8 || Hand[i].GetValue() == Topcard.GetValue())
{
for (int i = 0; i < NumberOfCard; i++)
{
if (Topcard.GetSuit() == Hand[i].GetSuit() && Hand[i].GetValue() != 8)
{
NumberOfCard--;
return Hand[i];
}
}
for (int i = 0; i < NumberOfCard; i++)
{
if (Topcard.GetValue() == Hand[i].GetValue() && Hand[i].GetValue() != 8)
{
NumberOfCard--;
return Hand[i];
}
}
for (int i = 0; i < NumberOfCard; i++)
{
if (Hand[i].GetValue() == 8)
{
NumberOfCard--;
return Hand[i];
}
}
}
else
{
GetCard(d1.DrawCard());
}
}
}
// Is not the computer, sets computer to fasle. i.e. its the human
void Human()
{
Computer = false;
}
int NumCards()
{
return NumberOfCard;
}
// will hand out a card
bool GetCard(CCard NewCard)
{
if (NumberOfCard < MaxHand)
{
// Now is taking the card
Hand[NumberOfCard] = NewCard;
NumberOfCard++;
return true;
}
else
return false;
}
// subtracts the card that was played from the deck of the human user
CCard CardPlayed(int index, CCard Topcard)
{
if (CheckCard(index, Topcard) == true)
{
CCard TempTopcard = Hand[index - 1];
for (int i = index - 1; i <= NumberOfCard - 1; i++)
{
Hand[i] = Hand[i + 1];
}
NumberOfCard--;
return TempTopcard;
}
else
cout << "Not a valid Card." << endl;
return Topcard;
}
// checks the card and see's if it is playable or not
bool CheckCard(int index, CCard Topcard)
{
if (Hand[index - 1].GetSuit() == Topcard.GetSuit() || Hand[index - 1].GetValue() == 8 || Hand[index - 1].GetValue() == Topcard.GetValue())
{
return true;
}
else
return false;
}
};
// overloads the output to cout the card
ostream & operator << (ostream &left, CPlayer right)
{
for (int i = 0; i < right.NumberOfCard; i++)
{
left << i + 1 << ") " << right.Hand[i] << endl;
}
return left;
}
Hi so i have just recently started learning c++ and any help would be appreciated in my problem.
I've been asked to create a piece of code for a game (chosen tic tac toe)
but its divided between two people.
my role is to create a class for only the displaying of the board and the choosing of player x or player o.
so far i have tried creating this c++ code but errors keep showing, anyone know how to correct this??
p.s in the game i class it as XsandOs.
#include <string>
#include <iostream>
using namespace std;
class XsandOs // Name of the class
{
public:
XsandOs();
void drawboard();
void printBoard();
void getMove(int move);
void choosePlayer(char player);
bool checkwinner(const char board[3][3], char symbol, int plays);
private:
const char board[3][3];
};
void XsandOs::drawboard // Develops the board
{
cout << "Let's play X's and O's\n" << "_________________________________\n\n"; //This prints a title declaring the name of the game
//This action uses an array to create the board, the user will choose the number to select where they want the character to go.
char board[3][3] =
{
{ '1', '2', '3', }; //This creates the top row
{'4', '5', '6', }; // This creates the middle row
{'7', '8', '9', }; // This creates the bottom row
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << board[i][j] << "";
}
cout << endl;
}
}
void XsandOs::choosePlayer(char player)
{
if (player == 'X')
Player = 'O';
elseif(player == 'O')
Player = 'X';
return(void);
}
int main()
{
draw();
while (1)
{
input();
draw();
choosePlayer();
}
system("pause");
return 0;
}
I've cleaned up some of the design issues and created methods for you. There is still work to be done, you can't expect us to do it for you. Good luck.
#include <string>
#include <iostream>
using namespace std;
class XsandOs // Name of the class
{
public:
XsandOs();
void draw();
void input();
int getMove(); // 1-9 or zero on error
void choosePlayer();
bool checkWinner(); // true means game over
private:
char board[3][3];
char player;
};
XsandOs::XsandOs()
{
// initialize the board
player = 'X'; // x goes first
for (int i = 0;i < 3;++i)
for (int j = 0;j < 3;++j)
board[i][j] = ' '; // blank means the spot is empty
}
void XsandOs::draw() // Develops the board
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
int XsandOs::getMove()
{
// ask for a move
// validate the move or get a new move
// TODO
}
void XsandOs::input()
{
// ask for a move
int move = 0;
while (!move) {
move = getMove();
}
// do the move and update the board
board[move-1] = player;
}
void XsandOs::choosePlayer()
{
if (player == 'X')
Player = 'O';
elseif(player == 'O')
Player = 'X';
}
bool XsandOs::checkWinner()
{
// TODO
// Check the board state and look for a winner.
return false;
}
int main()
{
XsandOs game;
bool gameOver = false;
game.draw();
while (!gameOver)
{
game.input();
game.draw();
game.checkWinner()
gameOver = game.choosePlayer();
}
system("pause");
return 0;
}
I'm working on the following C++ application:
Description:
The user enters a number n and the program takes a random collection of cards that are declared at the top of main in the global arrays. It will output a random number of cards each time.
Issue:
The number, e.g. '3 Hearts', appears more than one time. I made a function to correct that, however it didn't solve the issue.
Reference code provided below:
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
string type[4] = {"Hearts" , "Diamonds" , "Spades" , "Clubs"};
string num[13] = {"1","2","3","4","5","6","7","8","9","10","J","Q","K"};
int random(int x)
{
return rand() %x;
}
bool isDrawn(int);
void DrawCard();
int card_remaining = 52;
bool card_is_drawn[52] = {false};
int main()
{
while(1)
{
cout<<"\n Enter A Card Number : ";
int n;
cin>>n;
if(card_remaining <= 0)
{
card_remaining = 52;
cout<<" No More Cards , Refreshing ...\n";
cout<<" Refresh Done ! Try Again if you Want \n";
for(int i=0;i<52;i++)
card_is_drawn[i] = false;
}
else
{
for(int i=0;i<n;i++)
{
DrawCard();
}
}
}
cout<<endl;
system("PAUSE");
return 0;
}
void DrawCard()
{
bool check_1 = false;
int card;
while(!check_1)
{
card = random(card_remaining);
if(!isDrawn(card))
check_1 = true;
}
if(check_1)
cout << num[card%13]<<" OF " << type[card/13] << endl ;
card_remaining--;
}
bool isDrawn(int x)
{
if (card_is_drawn[x] == false)
{
card_is_drawn[x] = true;
return true;
}
return false;
}
Check the function
bool isDrawn(int x){
if(card_is_drawn[x] == false){
card_is_drawn[x] = true;
return true;
}
return false;
}
You might want to exchange the both return values. That means:
if(card_is_drawn[x] == false) {
...
return false; //since the card was NOT drawn;
And at the end of the function:
return true; //since the if-clause evaluated as false what means that the card was drawn;
By the way:
You get your random card by rand()%cards_remaining. That means if you draw ANY card and therefore reduce cards_remaining by one you won't be able to draw the King of Clubs anymore. And going on like this you will loose cards from the 'end' of your deck.
should be:
void DrawCard(){
if (card_remaining <= 0) // no cards left? can't draw
return;
bool check_1 = false;
int card;
while(!check_1){
card = random(52); // here 52
if (isDrawn(card)) // here, if the card HAS been drawn
check_1 = true;
}
if(check_1)
cout << num[card%13]<<" OF " << type[card/13] << endl ;
card_remaining--;
}
So I am trying to make a pretty basic TicTacToe in C++, and while I have no apparent syntax errors, I am having a lot of Debug errors of : "Unhandled exception at 0x0100142D in Cobra.exe: 0xC0000005: Access violation reading location 0xCCCCC359"
I feel like it is an obvious Error that I am just not processing but it;s definitely starting to grate my nerves. I'll label where the access error is... Right now it;s in my checkwin method but I feel like there is definitely more than one..
In my header I use a private char** board and a private int player.
#include "TicTacToe.h"
#include <iostream>
using namespace std;
int main()
{
int rowChosen,
colChosen;
TicTacToe newGame;
while(newGame.checkWin()==' ' && !newGame.fullBoard())
{
newGame.displayBoard();
do
{
cout << "Player " << newGame.getPlayer() << " choose a row and column.";
cin >> rowChosen >> colChosen;
newGame.setGame(rowChosen,colChosen);
}while(newGame.setGame(rowChosen,colChosen)==false);
newGame.makeMove(rowChosen, colChosen, newGame.getPlayer());
newGame.switchPlayer();
}
newGame.displayBoard();
if(newGame.checkWin()!=' ')
cout << "Player " << newGame.returnWinner() << " wins!";
else if(newGame.fullBoard()==true)
cout << "Cat's Game: This is a Draw!";
return 0;
}
TicTacToe::TicTacToe()
{
player = 1;
char blank = ' ';
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
board[row][col] = ' ';
}
void TicTacToe::setPlayer(int play)
{
player = play;
}
int TicTacToe::getPlayer()
{
return player;
}
void TicTacToe::switchPlayer()
{
if (player==1)
player++;
else
player--;
}
bool TicTacToe::setGame(int row, int col) //input validation
{
if (row >= 3 || row < 0)
return false;
if (col >= 3 || col < 0)
return false;
if (board[row][col] != ' ')
return false;
return true;
}
char TicTacToe::getBoard(int row, int col)
{
return board[row][col];
}
bool TicTacToe::fullBoard()
{
bool full = true;
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
{
full=false;
break;
}
}
return full;
}
void TicTacToe::makeMove(int r, int c, int player)
{
char ch;
if (player==1)
ch = 'X';
else
ch = 'O';
board[r][c] = ch;
}
char TicTacToe::checkWin()
{
char b = ' ';
for(int i=0; i<3; i++) //horizontal
{
if((board[i][1]==board[i][0]) && (board[i][1]==board[i][2])) //THIS IS ERROR
{
b=board[i][1];
}
}
for(int j=0; j<3; j++) //vertical
{
if( (board[1][j]==board[0][j]) && (board[1][j]==board[2][j]) )
b=board[1][j];
}
if((board[0][0]==board[1][1] && board[1][1]==board[2][2]) ||
(board[2][0]==board[1][1] && board[1][1]==board[0][2]))
b= board[1][1];
return b;
}
void TicTacToe::displayBoard()
{
for(int row=0;row<3;row++)
{
cout << "|-----|";
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
cout << "| ";
else
cout << "|" << board [row][col];
}
cout << "|" << endl;
cout << "|-----|";
}
}
int TicTacToe::returnWinner()
{
int winner = 0;
if(checkWin()=='X')
winner = 1;
else if(checkWin()=='O')
winner = 2;
return winner;
}
This is my header TicTacToe.h
class TicTacToe
{
private:
char board[3][3]; //there we go
int player;
public:
TicTacToe();
void setPlayer(int);
int getPlayer();
void switchPlayer();
bool setGame(int,int);
char getBoard(int,int);
bool fullBoard();
void makeMove(int,int,int);
char checkWin();
void displayBoard();
int returnWinner();
};
Assuming you've included all the code, you're missing something essential: the declaration of the class TicTacToe. Of course, there's a TicTacToe.h, so it could be (probably is) hiding in there. That would help.
That all said, I think Mat has it right -- you declare a local named board inside the ctor and initialize it. But that goes out of scope as soon as the ctor is finished, which means all that initialization disappears into the aether.. Assuming you define board in your class, then simply removing that char declaration might be all you need.
Now, here's general advice: if you get an access violation exception, it usually means that you have made a mistake about the scope of something you're referring to. Since the exception happens at a point where you're using board, the slice of the program containing the identified board is the place to look.