using random in class to make a loop - c++

I want to ask user to set a compass direction as a char, using n for north, e for east etc and so on, or to use default value which is set to North. e.g (0,0,'n').
Then I want to make it randomly move 100 times in any direction. I am now confused on the loop inside my class. I don't know where should I add the loop. Also, the output shows me the values I have typed.
I would appreciate your help !
output example:
0===0---n
#include<iostream>
#include<string>
#include<iomanip>
#include<ctime>
using namespace std;
class bug
{
public:
bug();
bug(int x_pos, int y_pos, char direction);
void turn(char direction);
void move(int x, int y,char direction);
int get_X() const;
int get_Y() const;
char get_direction() const;
private:
int x;
int y;
char direction;
};
bug::bug(int x_pos, int y_pos, char d)
{
x = x_pos;
y = y_pos;
direction = d;
}
bug::bug()
{
x = 0;
y = 0;
direction = 'n';
}
void bug::turn(char direction)
{
int num = 1 + rand() % 3;
if (direction == 'n')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'n';
}
else if (direction == 'w')
{
if (num == 1)
direction = 'w';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
else if (direction == 's')
{
if (num == 1)
direction = 's';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'e';
}
else if (direction == 'e')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
}
void bug::move(int x, int y, char direction)
{
if (direction == 'n')
y = y + 1;
else if (direction == 'w')
x = x - 1;
else if (direction == 's')
y = y - 1;
else if (direction == 'e')
x = x + 1;
}
int bug::get_X() const
{
return x;
}
int bug::get_Y() const
{
return y;
}
char bug::get_direction() const
{
return direction;
}
void display(bug start)
{
cout << start.get_X()<<"==="<<start.get_Y() << "---"<<start.get_direction() << endl;
}
int main()
{
srand(time(0));
bug first;
int choice;
cout << custom mode(1) or default mode(2) ? ";
cin >> choice;
if (choice == 1)
{
int x, y;
char dir;
cout << "the x axis: ";
cin >> x;
cout << "the y axis: ";
cin >> y;
cout << "the direction: ";
cin >> dir;
bug first(x, y, dir);
//first.turn(dir);
//first.move(x,y);
display(first);
}
else
{
for(int j =0;j<100;j++)
{
bug first;
//first.turn;
//first.move();
//for(int j =0;j<100;j++)
display(first);
}
}
system("pause");
}

There is a missing " on the line:
cout << custom mode(1) or default mode(2) ? ";
I believe the intention is to have the double quote in front of the word custom like so:
cout << "custom mode(1) or default mode(2) ? ";
Start Modification
There are some things to consider that will be more clearly seen by stepping through with the debugger and observing the internal variables versus the passed by value parameters. The passed by value parameters happen to be named the same as the internal class data member variables. Please think through these things and decide what the desired behavior is for the turn and move functions for both mode choices.
End Modification

Related

Snake game stops after I reach 18 points. Why? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Okay so this is some very basic code for a classic snake game that I wrote. I need it as a part of a bigger project I'm working on but while testing I ran into this very annoying error. If someone could just execute it and tell me what I'm missing, that'd be great. Any extra suggestions are also welcome. I've attached the code below and written some very basic comments, hope that they are enough to understand it.
The Error: My code stops after the player achieves 18 points. To be very specific, No more fruits appear on the console at score = 18.
#include<iostream>
#include<conio.h>
#include<vector>
#include<queue>
#include<utility>
#include<windows.h>
using namespace std;
bool play = true;
int score = 0;
class Arena
{
private:
int length, w, h, size, fx, fy;
char snakerep, fruitrep, dir;
queue<pair<int,int>> snakey, marker;
vector<vector<char>> arena;
public:
Arena()
{
//snake stuff
length = 1;
snakerep = 'O';
for(int i = 0 ; i < length ; i++)
snakey.push({1, i+1});
dir = 'R';
//arena stuff
size = 25;
h = size, w = 2*size;
arena.resize(h, vector<char>(w, ' '));
//fruit stuff
fruitrep = 'F';
fx = 1 + (rand() % h);
fy = 1 + (rand() % w);
arena[fx][fy] = fruitrep;
}
void setFruit()
{
fx = 1 + (rand() % h);
fy = 1 + (rand() % w);
arena[fx][fy] = fruitrep;
}
void setArena()
{
for(int i = 0 ; i < w ; i++)
{
arena[0][i] = '*';
arena[h-1][i] = '*';
}
for(int i = 1 ; i < h-1 ; i++)
{
arena[i][0] = '*';
arena[i][w-1] = '*';
}
for(int i = 1 ; i < h-1; i++)
{
for(int j = 1; j < w-1 ; j++)
{
arena[i][j] = ' ';
}
}
arena[fx][fy] = fruitrep;
}
void setSnake()
{
queue<pair<int,int>> temp_snakey = snakey;
while(!temp_snakey.empty())
{
pair<int, int> xy = temp_snakey.front();
temp_snakey.pop();
int x = xy.first, y = xy.second;
//condition for hitting any of the boundaries
if (x <= 0 || y <= 0 || x >= size-1 || y >= 2*size-1)
play = false;
//condition for hitting itself
if (arena[x][y] == snakerep)
play = false;
//condition for if a fruit is eaten
if (arena[x][y] == fruitrep)
{
setFruit();
//increase length of the snake
length++, score++;
marker.push({x,y});
}
arena[x][y] = snakerep;
}
}
void moveSnake(char dir)
{
//calculate the new location of the head or whatever according to the direction given within the brackets
pair<int,int> prevHead = snakey.back(), newHead;
if (dir == 'R')
newHead = {prevHead.first, prevHead.second+1};
else if (dir == 'L')
newHead = {prevHead.first, prevHead.second-1};
else if (dir == 'U')
newHead = {prevHead.first-1, prevHead.second};
else if (dir == 'D')
newHead = {prevHead.first+1, prevHead.second};
//pop the tail from the queue and add the new head
pair<int, int> tail = snakey.front();
if (!marker.empty() && tail == marker.front())
marker.pop();
else
snakey.pop();
snakey.push(newHead);
}
void printAll()
{
//prints the matrix
for(int i = 0 ; i < h ; i++)
{
for(int j = 0 ; j < w ; j++)
{
cout<<arena[i][j];
}
cout<<endl;
}
}
void getDirection()
{
if(_kbhit())
{
char ch = _getch();
if (dir == 'R' || dir == 'L')
{
if (ch == 'w')
dir = 'U';
else if (ch == 's')
dir = 'D';
else if (ch == 'x')
play = false;
}
else if (dir == 'U' || dir == 'D')
{
if (ch == 'd')
dir = 'R';
else if (ch == 'a')
dir = 'L';
else if (ch == 'x')
play = false;
}
}
}
void playGame()
{
getDirection();
setArena();
moveSnake(dir);
setSnake();
printAll();
}
};
int main()
{
Arena A;
while(play)
{
A.playGame();
cout<<" SCORE = "<<score<<endl;
//better than using system("cls"), because it moves cursor to beginning of console, flickering stops
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0, 0});
}
return 0;
}
The 18th fruit is getting generated out of bounds. Your random location function is incorrect. You have
void setFruit()
{
fx = 1 + (rand() % h);
fy = 1 + (rand() % w);
arena[fx][fy] = fruitrep;
}
Okay, consider fx, rand() % h will give you a number in [0 .. h-1] inclusive but you are adding one to it because the zeroth position is a wall. So now you have [1..h] but h is out of bounds. Also there is a wall on the right too. So putting that all together, I think what you want is
void setFruit()
{
fx = 1 + (rand() % (h-2));
fy = 1 + (rand() % (w-2));
arena[fx][fy] = fruitrep;
}
Also you should change the Arena constructor to use this function. It is good to not repeat bits of code like that.

Why the last element in istringstream doesn't disappear in my code?

I am writing a calculator program in c++ , and I met two problems .
After I calculate 1 calculation questions , I only need to press enter ,then the program will output the last number in the previous calculation .
There are some incorrect answer , like " 7 / 9 / 10 * 1 * 4 / 6 - 3 * 9 - 8 - 7 " , the output should be -41.95 , but my answer is -11.95 .And I can't find what's wrong with my code.
The cin problem has been fixed when I use if(cin.get()!='\n')break;
And At the bottom there is a correct code of others .
my code use istringstream
#include<iostream>
#include<string>
#include<sstream>
#include<stack>
#include<iomanip>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
else return 2;
}
double calculate(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x * y;
return x / y;
}
int main() {
int n;
char op;
stack<double> nums;
stack<char> ops;
string a;
int count = 0;
while (getline(cin, a)) {
count++;
int allNum = 0;
int allzero = 0;
allNum++;
istringstream b(a);
b >> n;
if (n == 0) allzero++;
nums.push(n);
while (b >> op >> n) {
if (op == '\n') break;
allNum++;
if (n == 0) allzero++;
if (!ops.empty() && priority(op) <= priority(ops.top())) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
ops.push(op);
nums.push(n);
}
while (!ops.empty()) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
if (allzero != allNum) cout<< fixed << setprecision(2) << nums.top() << endl;
b.clear();
nums.pop();
}
}
this is the code I find on the internet
I learned the method from here , the biggest differentenss is that he use C ,and I use C++ .But his result is right .
#include <iostream>
#include <cstdio>
#include <cstring>
#include<stack>
using namespace std;
int P(char c)
{
if (c == '+' || c == '-') return 1;
return 2;
}
double Ans(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x*y;
return x / y;
}
int main() {
int n;
while (scanf("%d",&n)!=EOF)
{
char c = getchar();
if (c=='\n'&&n == 0)break;
stack<char> op;
stack<double>num;
num.push(n);
while (true)
{
scanf("%c %d", &c, &n);
char k = getchar();
while (!op.empty()&&P(c)<=P(op.top()))
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
op.push(c);
num.push(n);
if (k == '\n')break;
}
while (!op.empty())
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
printf("%.2f\n", num.top());
}
return 0;
}

C++ user input twice before specified response

I am making a whack-a-mole game for my class but I am stuck on the basic controls. I setup a basic board, using an array with a border using ascii symbols, with O representing the holes and X the hammer. When I go to move the hammer, lets say to the right, I have to press it twice for the hammer to move and I don't know why. It has to go through the whole loop 2 times before moving the hammer the right way.
#include <iostream>
#include <windows.h>
using namespace std;
bool gamerunning = true;
const int num = 20; //width
const int num2 = 40; //height
int x, y, score, perx, pery;
int hole1x, hole1y;
int hole2x, hole2y;
int hole3x, hole3y;
int hole4x, hole4y;
void setup(){
x= 5;
y=5;
hole1x = 15;
hole1y = 5;
hole2x = 15;
hole2y = 10;
hole3x = 25;
hole3y = 5;
hole4x = 25;
hole4y = 10;
score = 0;
perx = 15;
pery = 6;
}
//creating board
void draw(){
system("cls");
int i,j;
char Layout[num][num2];
for (i=0;i<num;i++){
for (j=0;j<num2;j++){
//boarder for play area
if (i==0 && j==0) //Top Left
Layout [i][j] = 201;
else if( i==0 && j==num2-1) //top right
Layout [i][j] = 187;
else if(i==num-1 && j==0) //bottom left
Layout [i][j] = 200;
else if(i ==num-1 && j==num2-1) //bottom right
Layout [i][j] = 188;
else if (i==0 || i==num - 1)
Layout[i][j]=205;
else if(j==0 || j==num2-1)
Layout [i][j] = 186;
else
Layout[i][j]=' ';
//holes
if(i == hole1y && j == hole1x)
Layout[i][j]= 'O';
if(i == hole2y && j == hole2x)
Layout[i][j]= 'O';
if(i == hole3y && j == hole3x)
Layout[i][j]= 'O';
if(i == hole4y && j == hole4x)
Layout[i][j]= 'O';
//character
if(i == pery && j == perx)
Layout[i][j]= 'X';
cout << Layout[i][j];
}
cout << endl;
}
}
void input(){
if(GetAsyncKeyState(VK_RIGHT)){
if(perx<=15)
perx +=10;
}
if(GetAsyncKeyState(VK_LEFT)){
if(perx>=25)
perx -=10;
}
if(GetAsyncKeyState(VK_DOWN)){
if(pery<=10)
pery +=5;
}
if(GetAsyncKeyState(VK_UP)){
if(pery>=10)
pery -=5;
}
if(GetAsyncKeyState(VK_ESCAPE)){
gamerunning = false;
}
}
void logic(){
}
int main(){
setup();
while(gamerunning == true){
draw();
input();
logic();
system("pause>nul");
}
system("cls");
cout << "GAME OVER" << endl;
return 0;
}
Here :
while(gamerunning == true)
{
draw();
input();
system("pause>nul");
logic();
}
You first draw your game board then you get the input, drawing will not happen until the next time loop execution, so your drawing will not update.
You need to put first draw call outside the loop (for initial drawing) then inside the loop call draw after input. like this :
draw();
while(gamerunning == true)
{
input();
draw();
system("pause>nul");
logic();
}

Turtle Graphics Program

#include <iostream>
#include <fstream>
using namespace std;
void printArray(void);
char grid[6][34] = {'0'}; // empty floor
void movement(int command);
int direction = 2; // 1 for north, 2 for east, 3 for south, 4 for west. Turtle starts facing east.
void turtleMovement(int, int);
int spacesMoved; // used after F command.
int yCoord = 0; // Y position assumed 0;
int xCoord = 0; // X position assumed 0;
bool pen = 0; // assume pen is up
void initialize(void);
char command; // U for pen up, D for pen Down, R for right turn, L for left turn, F for forward movement with spaces moved, P for array print, and Q for end.
int main(){
initialize();
ifstream infile;
infile.open("commands.txt");
infile >> command;
while(command != 'Q'){
if(command == 'U'){
pen = 0;
}
else if(command == 'D'){
pen = 1;
}
if(command == 'R' || command == 'L'){
movement(command);
}
if(command == 'F'){
infile >> spacesMoved;
turtleMovement(yCoord, xCoord);
}
else if(command == 'P')
printArray();
infile >> command;
}
}
//=====================================================================================================================================================
//
// Function Name: intialize
//
// Pre: none
//
// Post: sets every element of the array grid to all zeroes.
//
//======================================================================================================================================================
void initialize()
{
for(int i = 0; i < 6; i++){ //
for(int j = 0; j < 34; j++){ // Initialization of Array to all zeros.
grid[i][j] = '0'; //
}
}
}
//=====================================================================================================================================================
//
// Function Name: printArray
//
// Pre: none
//
// Post: prints out the array grid to the console
//
//======================================================================================================================================================
void printArray()
{
for(int i = 0; i < 6; i++)
for(int j = 0; j < 34; j++){
grid[i][j];
cout << grid[i][j] << (j == 33 ? "\n" : ""); // if the row gets to 33 characters a new line will be made.
}
}
void movement(int command)
{
if (direction == 2){ // direction is east
if (command == 'R')
direction = 3;// if you're facing east and you turn right you're now facing south
else if (command == 'L') // if you're facing east and you turn left you're now facing north.
direction = 1;
}
else if (direction == 3) // direction is south
{
if (command == 'R') // turn right to go west
direction = 4;
else if (command == 'L') // turn left to go east
direction = 2;
}
else if (direction == 4) // direction is west
{
if (command == 'R') // right for north
direction = 1;
else if (command == 'L') // left for south
direction = 3;
}
else if (direction == 1) // direction is north
{
if (command == 'R') // right for east
direction = 2;
else if (command == 'L') // left for west
direction = 4;
}
}
void turtleMovement(int y, int x){
if(direction == 2){
int i = y;
for(int j = x; j < x + spacesMoved; j++){
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
xCoord += spacesMoved - 1; //updates the x coordinate
}
else if(direction == 3){
for(int i = y; i < y + spacesMoved; i++){
int j = x;
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
yCoord += spacesMoved - 1; //updates the y coordinate
}
else if(direction == 4){
int i = y;
for(int j = x; j > x - spacesMoved; j++){
if(pen == 1)
grid[i][j] = '1';
else if (pen == 0)
grid[i][j] = '0';
}
xCoord -= spacesMoved - 1; //updates the x coordinate
}
else if(direction == 1){
for(int i = y; i > y- spacesMoved; i++){
int j = x;
if(pen == 1)
grid[i][j] = '1';
else
grid[i][j] = '0';
}
yCoord -=spacesMoved - 1; //updates the y coordinate
}
}
I'm having extreme frustration with my program, when I try and do a 180 turn, i.e. a R R or a L L the whole program just freezes. Is it something with my logic? or a syntax? because it doesn't give me any of those errors.
Sorry, but your program is annoying me and it is a little hard to read.
Try this:
struct Position
{
int x;
int y;
};
struct Direction_Vector : Position
{
unsigned int direction;
};
const unsigned int MAX_DIRS = 4u;
void movement(char command,
const Direction_Vector present_dir,
Direction_Vector& new_dir)
{
unsigned int dir = present_dir.direction;
switch (command)
{
case 'R': // rotate clockwise;
dir = (dir + 1) % MAX_DIRS;
break;
case 'L': // rotate counter clockwise
dir = (dir + (MAX_DIRS - 1)) % MAX_DIRS;
break;
case 'M': // Move one position in the given direction
switch (dir)
{
case 0: // Assume north, Y decreases
new_dir.y = present_dir.y - 1;
break;
case 1: // Assume east, X increases
new_dir.x = present_dir.x + 1;
break;
case 2: // Assume south, Y increases
new_dir.y = present_dir.y - 1;
break;
case 3: // Assume west, X decreases
new_dir.x = present_dir.x - 1;
break;
}
break;
default:
break;
}
new_dir.direction = dir;
}
You may be able to optimize the movement section by using algebra and realizing a relationship between the direction and the ordinate that gets adjusted.
Also, I have not put in any boundary checking.
Sorry if I ruined your day by simplifying a lot of your posted code.
Use a debugger and step through the above code and figure out if it handles the 180 degree turns correctly.
Edit 1: Truth Tables
Here are the truth tables for the movement and ordinate changes
Direction | Delta X | Delta Y| // "delta" means change
----------+---------+--------+
0 | 0 | -1 |
----------+---------+--------+
1 | +1 | 0 |
----------+---------+--------+
2 | 0 | +1 |
----------+---------+--------+
3 | -1 | 0 |
----------+---------+--------+
Can you come up with an algebraic equation for the ordinates based on the direction?

Tic-Tac-Toe Array Error

This program is a simple Tic Tac Toe game between a player and the computer. The computer just generates a random space to move to if said space is not already occupied. Also, I have the x-coordinates on the vertical axis while the y-coordinates are on the horizontal axis. I did this because I use a two dimensional array, and that is just how they are structured.
When running the program, some of the spaces are faulty and I cannot find out why. When the user inputs the point (0,2) the program also fills in the point (1,0) and vise versa. This also occurs with the points (1,2) and (2,0).
#include<iostream>
#include<string>
#include<stdlib.h>
#include<ctime>
using namespace std;
int board[2][2];
int chooseFirstPlayer();
void userMove(int boardArray[2][2]);
void compMove(int boardArray[2][2]);
int checkIfWinner(int boardArray[2][2]);
void displayBoard(int boardArray[2][2]);
int main(){
srand(time(NULL));
int x,y,winner;
for(x = 0; x <= 2; x++){ //sets the enitre board array to 0
for(y = 0; y <= 2; y++){
board[x][y] = 0;
}
}
if (chooseFirstPlayer() == 1){ //the user gets to movve first
do{//it will loop this until there is a winner
displayBoard(board);
userMove(board);
displayBoard(board);
winner = checkIfWinner(board);
if (winner == 0){//after the player moves, it will see if he won. If not, then the computer willbe able to move.
compMove(board);
displayBoard(board);
winner = checkIfWinner(board);
}
}while (winner == 0);//it will loop until a winner is found
}
else{//same structure as above just slightly altered to allow the computer to move first
do{
compMove(board);
displayBoard(board);
winner = checkIfWinner(board);
if (winner == 0){
userMove(board);
displayBoard(board);
winner = checkIfWinner(board);
}
}while(winner == 0);
}
if (winner = 1){
cout << "Congratulations, you won!";
}
else if (winner = 2){
cout << "Sorry, you lost!";
}
}
int chooseFirstPlayer(){//randomly genereate a number 1 or 2 to choose who moves first
return rand() % 2 + 1;
}
void userMove(int boardArray[2][2]){
int userX, userY;
do{
cout << "Enter an x coordinate: "<<endl;
cin >> userX;
cout << "Enter a y coordinate: "<<endl;
cin >> userY;
if (boardArray[userX][userY] != 0){
cout << "That loaction is already occupied"<<endl;
}
}while(boardArray[userX][userX] != 0);
boardArray[userX][userY] = 1;
}
void compMove(int boardArray[2][2]){
int compX,compY;
do{
compX = rand() % 3;
compY = rand() % 3;
}while(boardArray[compX][compY] != 0);
boardArray[compX][compY] = 2;
}
int checkIfWinner(int boardArray[2][2]){
if(boardArray[0][0] == boardArray[0][1] && boardArray[0][1] == boardArray[0][2]){ //across
return boardArray[0][0];}
else if (boardArray[1][0] == boardArray[1][1] && boardArray[1][1] == boardArray[1][2]){
return boardArray[1][0];}
else if (boardArray[2][0] == boardArray[2][1] && boardArray[2][1] == boardArray[2][2]){
return boardArray[2][0];}
else if (boardArray[0][0] == boardArray[1][0] && boardArray[1][0] == boardArray[2][0]){//down
return boardArray[0][0];}
else if (boardArray[0][1] == boardArray[1][1] && boardArray[1][1] == boardArray[2][1]){
return boardArray[0][1];}
else if (boardArray[0][2] == boardArray[1][2] && boardArray[1][2] == boardArray[2][2]){
return boardArray[0][2];}
else if (boardArray[0][0] == boardArray[1][1] && boardArray[1][1] == boardArray[2][2]){//diagonal
return boardArray[0][0];}
else if (boardArray[2][0] == boardArray[1][1] && boardArray[1][1] == boardArray[0][2]){
return boardArray[2][0];}
else{
return 0;
}
}
void displayBoard(int boardArray[2][2]){
system("CLS");
cout <<" "<<" Y1 "<<" Y2 "<<" Y3 "<<endl;
cout <<" X1 "<< "__"<<boardArray[0][0]<<"__|__"<<boardArray[0][1]<<"__|__"<<boardArray[0][2]<<"__"<<endl;
cout <<" X2 "<< "__"<<boardArray[1][0]<<"__|__"<<boardArray[1][1]<<"__|__"<<boardArray[1][2]<<"__"<<endl;
cout <<" X3 "<< " "<<boardArray[2][0]<<" | "<<boardArray[2][1]<<" | "<<boardArray[2][2]<<" "<<endl;
}
My IDE is Dev-C++ (5.4.2)
Your array is 2x2 and you do:
for(x = 0; x <= 2; x++){ //sets the enitre board array to 0
for(y = 0; y <= 2; y++){
board[x][y] = 0;
}
}
and you access memory you shouldn't. That means you are going out of bounds!
Here x and y will take a value equal to 2 eventually.
Indexing of an array starts from 0 until it's size - 1.
So, you could use an array of 3x3, or change your code (and the function checkIfWinner that goes until 2).
Side note:
You have missed the equality operator here:
if (winner = 1){
cout << "Congratulations, you won!";
}
else if (winner = 2){
cout << "Sorry, you lost!";
}
What will happen if you leave it as is? The assignment will take place and will result in logical true, thus the first condition will be always true (and the second, but the code won't go that far).
So, change = with ==.