Detecting Walls in Multidimensional Arrays C++ Issues - c++

I need some help figuring this out. For some reason, when I move along
my array say for example "e" for east, I have made a detect wall
collision so the player can't go any further. However, when I try to
go "w" for west (back) it goes back 2 instead of 1. Any ideas on how
to fix this?
For now, use the e button to go right and west button to go left. I've used a multidimensional array and a switch to detect what room you're in, also providing player coordinates.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <windows.h>
using namespace std;
int playerX = 0; // x
int playerY = 0; // y
int nextX; // pY
int nextY; // pX
bool win = false;
string move;
char dungeon[11][11] = {
{ 's','c','c','c','r','w','c','c','c','r','r',},
{ 'w','w','w','c','w','r','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',},
{ 's','c','c','r','r','c','c','c','c','r','r',}
};
void movePlayer();
void location(int X, int Y);
int main()
{
do {
movePlayer();
location(playerX, playerY);
} while (win == false);
}
void movePlayer() {
string move;
cin >> move;
// reference Grid-Cave-Mk1 Author: Heather Southall Date: 2017
if (move == "n") {
nextY = playerY - 1;
if ((nextY >= 0) && (nextY < 11)) {
playerY = nextY;
}
else {
cout << "Can't move there" << endl;
}
}
else if (move == "e") {
nextX = playerX + 1;
if ((nextX >= 0) && (nextX < 11)) {
playerX = nextX;
}
else {
cout << "Can't move there" << endl;
}
}
else if (move == "w") {
nextX = playerX - 1;
if ((nextX >= 0) && (nextX < 11)) {
playerX = nextX;
}
else {
cout << "Can't move there" << endl;
}
}
else if (move == "s") {
nextY = playerY + 1;
if ((nextY >= 0) && (nextY < 11)) {
playerY = nextY;
}
else {
cout << "Can't move there" << endl;
}
}
}
void location(int X, int Y) {
cout << "X: " << X << endl;
cout << "Y: " << Y << endl;
char local = dungeon[Y][X];
switch (local) {
case 's':
cout << "Starter Room" << endl;
break;
case 'c':
cout << "Corridor" << endl;
break;
case 'r':
cout << "Room" << endl;
break;
case 'w':
nextX = playerX - 1;
if ((nextX >= 0) && (nextX < 11)) {
playerX = nextX; playerY = nextY;
break;
}
}
}

Its an issue with misleading logs - you don't print the current position, but the one which "type" is being checked. So you can get to logs [5, 0] and [3, 0] when:
You move east from the [4, 0] room. You check what's at [5, 0] (first print). You hit a wall, so the current position is moved back to [4, 0].
Discouraged, you move west. You check what's at [3, 0] (second print).
You should change the printed message, so that the user is notified about both the current position, and the tested one.
ps. hitting a wall should move you to the previous location instead of translating the position by [-1, 0].

Related

My character going left but not going right (CONSOLE GAME)

I working on my project this project have a frame to [100] x [25] matrix and i try to add animation but my character is going left but it's not going right.
i tried with "counter" variable but its not work.
int counter = 1;
int counter2 = 1;
int left_border = 1;
int matris1 = sizeof(map)/100;
int matris2 = sizeof(map[0])/4;
int startx = 19;
int starty = 8;
while (true)
...
int right = 0, left = 0;
...
for (int a = 0; a < matris2; a++)
cout << "\n#"; //i have this because i make it square map.
for (int k = 0; k < matris1 - 2; k++)
{
if (left == 1)
{
if (((startx+2)-counter) == left_border)
{
counter = 0;
//cout << "SINIR!!"<< endl ;
}
if (k == (startx-counter) and a == starty)
{
counter += 1;
cout << "O";
}
else {
cout << " ";
}
}
else if (right == 1)
{
if (k == (startx+counter2) and a == starty)
{
counter2 += 1;
cout << "O";
}
its need to be going right but its not.
if you need full code.
https://codeshare.io/UbKVU
[![This is the map and "O" is the character]
https://i.stack.imgur.com/uyGQo.png
The code is very difficult to follow - you should have a coordinate system. I've made a simple example below. Update the player coordinate when a key is pressed and redraw the map x by y position, if the player is there then draw the 'O', otherwise if its a wall draw an 'X' (in this case), otherwise draw a space ' '.
using namespace std;
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define MAPW 15 // map width
#define MAPH 15 // map height
int map[MAPW][MAPH];
#define WALL 1
#define EMPTY 0
void initmap()
{
// just set the map to have walls around the border
for (int x = 0; x < MAPW; x++)
{
for (int y = 0; y < MAPH; y++)
{
if (x == 0 || y == 0 || x == (MAPW - 1) || y == (MAPH - 1))
map[x][y] = WALL;
else
map[x][y] = EMPTY;
}
}
}
int px = MAPW / 2; // player x
int py = MAPH / 2; // player y
void main()
{
initmap(); // initialize map
cout << "Press A/W/S/D to begin and move";
while (1)
{
if (kbhit()) // key pressed?
{
switch (getch()) // which key?
{
case 'a':
if (px > 0 && map[px - 1][py] != WALL) // can go left?
px--; // update x coordinate
break;
case 'd':
if (px < (MAPW-1) && map[px + 1][py] != WALL) // can go right?
px++; // update x coordinate
break;
case 'w':
if (py > 0 && map[px][py - 1] != WALL) // can go up?
py--; // update y coordinate
break;
case 's':
if (py < MAPH && map[px][py + 1] != WALL) // can go down?
py++; // update y coordinate
break;
}
// update map - clear screen and redraw
system("CLS");
// draw map each line
for (int y = 0; y < MAPH; y++)
{
for (int x = 0; x < MAPW; x++)
{
// its a wall?
if (map[x][y] == WALL)
cout << "X";
else
{
// is the player there?
if (x == px && y == py)
{
// draw the player
cout << "O";
}
else // empty space
cout << " ";
}
}
// next line
cout << "\n";
}
}
}
}

Why doesn't the Player.x and Player.y variables change?

Edit #2: Ok, I did another *.cpp to check if the codes for Arrow Keys were right. Doing that, I noticed keyPressed variable in detectKeyPressing() had the wrong type of variable, so I changed it from char to int and changed the codes.
Once I did that, it worked. Now I have put the limits, so the Player cannot go outside the square. But I have another problem, the movement is too tough and if you press the keys too fast, the instructions run with a annoying delay. I know I should use either Sleep(ms) or Delay(ms), but I don't know when I should use it.
This is the new code:
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <Windows.h>
using namespace std;
int detectKeyPressing() {
// 0: Escape
// 1: Enter
//2: Up
// 3: Left
// 4: Down
// 5: Right
int keyPressed = 0;
while (keyPressed != 27) {
if (keyPressed == 0 || keyPressed == 224) {
keyPressed = _getch(); //First value of _getch() when any of the arrow keys are pressed is "224", the next one is the code depending of which arrow you pressed
}
else if (keyPressed == 13) {
return 1;
}
else {
switch (keyPressed) {
//Up
case 72:
return 2;
break;
//Left
case 75:
return 3;
break;
//Down
case 80:
return 4;
break;
//Right
case 77:
return 5;
break;
//Default
default:
return -1;
break;
}
}
};
return 0;
};
int mainMenu() {
int enterPressed = 0;
cout << "Press Enter to Begin, or ESC to exit" << endl;
enterPressed = detectKeyPressing();
system("cls");
return enterPressed;
};
void draw(int playerX, int playerY) {
//Player coordinates, made for testing
cout << "Player.x = " << playerX << endl << "Player.y = " << playerY << endl;
//The next 8 spaces go blank
for (int i = 1; i < 8; i++) {
cout << endl;
}
//Square Limit Making
//Top Limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
cout << endl;
//Border limits and inside the Square
for (int ih = 1; ih < 30; ih++) {
//Left border
cout << "|";
//Inside the Square
for (int iw = 1; iw < 78; iw++) {
if (iw == playerX && ih == playerY) {
cout << "a"; //This is supposed to be ♥ but I don't know how to put it in the screen with a cout
}
else {
cout << " ";
}
}
//Right border
cout << "|" << endl;
}
//Bottom limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
}
int main() {
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 1;
cci.bVisible = FALSE;
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
int pressedKey = -1; //Creating pressedKey at Start
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 1;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
pressedKey = detectKeyPressing(); // Save detectKeyPressing()'s return in pressedKey
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (pressedKey == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (pressedKey > 1 && pressedKey < 6) {
switch (pressedKey) {
//Up
case 2:
Sleep(200);
if (Player.y == Player.speed) {
Player.y = Player.speed; //Top Limit
}
else {
Player.y -= Player.speed;
}
break;
//Left
case 3:
Sleep(200);
if (Player.x == Player.speed) {
Player.x = Player.speed; //Left Limit
}
else {
Player.x -= Player.speed;
}
break;
//Down
case 4:
Sleep(200);
if (Player.y == 30 - Player.speed) {
Player.y = 30 - Player.speed; //Bottom Limit
}
else {
Player.y += Player.speed;
}
break;
//Right
case 5:
Sleep(200);
if (Player.x == 78 - Player.speed) {
Player.x = 78 - Player.speed; //Right Limit
}
else {
Player.x += Player.speed;
}
break;
};
system("cls"); //Erase all
draw(Player.x, Player.y); //Redraw everything, with Player.x or Player.y modified
};
};
};
return 0;
};
Edit #1: I fixed the mistakes you told me, here's the main function modified. It isn't working though.
int main(){
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 50;
cci.bVisible = FALSE; //Changed "TRUE" to "FALSE"
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
int pressedKey = -1; //Creating pressedKey at Start
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 2;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
pressedKey = detectKeyPressing(); //Save detectKeyPressing()'s return in pressedKey
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (pressedKey == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (pressedKey > 1 && pressedKey < 6) {
cout << "There's no problem in Else If statement"; //Couts made for testing
switch (pressedKey) {
cout << "There's no problem in Switch statement";
//Up
case 2:
Player.y -= Player.speed;
cout << "You moved Up";
break;
//Left
case 3:
Player.x -= Player.speed; //Fixed Left movement
cout << "You moved Left";
break;
//Down
case 4:
Player.y += Player.speed;
cout << "You moved Down";
break;
//Right
case 5:
Player.x += Player.speed;
cout << "You moved Right";
break;
};
//system("cls"); //Erase all
//draw(Player.x, Player.y); //Redraw everything, with Player.x and Player.y supposedly modified
};
};
};
return 0;
};
Initial Post: I'm trying to do something like an Undertale normal fight and now I'm doing the "dodging attacks" part, but I'm stuck at making the player move (Yep, that "a") because it didn't update when I press an arrow key (for movement). It is supposed to draw, and put the Player in Player.x and Player.y, so I did something in main() to edit these variables depending on the arrow key you pressed, and then erase and re-draw with the Player.x or Player.y modified.
Here's the code:
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <Windows.h>
using namespace std;
int detectKeyPressing(){
// 0: Escape
// 1: Enter
// 2: Up
// 3: Left
// 4: Down
// 5: Right
char keyPressed = 0;
while (keyPressed != 27){
if(keyPressed == 0){
keyPressed = _getch();
}
else if(keyPressed == 13){
return 1;
}
else{
switch (keyPressed) {
//Up
case 65:
return 2;
break;
//Left
case 68:
return 3;
break;
//Down
case 66:
return 4;
break;
//Right
case 67:
return 5;
break;
//Default
default:
return -1;
break;
}
}
};
return 0;
};
int mainMenu(){
int enterPressed = 0;
cout << "Press Enter to Begin, or ESC to exit" << endl;
enterPressed = detectKeyPressing();
system("cls");
return enterPressed;
};
void draw(int playerX, int playerY) {
//Player coordinates, made for testing
cout << "Player.x = " << playerX << endl << "Player.y = " << playerY << endl;
//The next 8 spaces go blank
for (int i = 1; i < 8; i++) {
cout << endl;
}
//Square Limit Making
//Top Limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
cout << endl;
//Border limits and inside the Square
for (int ih = 1; ih < 30; ih++) {
//Left border
cout << "|";
//Inside the Square
for (int iw = 1; iw < 78; iw++) {
if (iw == playerX && ih == playerY){
cout << "a"; //This is supposed to be ♥ but I don't know how to put it in the screen with a cout
}
else {
cout << " ";
}
}
//Right border
cout << "|" << endl;
}
//Bottom limit
for (int iw = 1; iw < 80; iw++) {
cout << "-";
}
}
int main(){
//Hide cursor
HANDLE hCon;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = 50;
cci.bVisible = TRUE;
SetConsoleCursorInfo(hCon, &cci);
//Variable Making
int gameStarted = -1; // 1 if game is running, 0 if not
//int t = 0; //Turn Counter, not useful for now
Sleep(200); //Wait to get a new seed
srand(time(NULL)); //Seed for rand()
//Menu Loop, remember, 1 if game starts running, 0 if you exit
while (gameStarted > 1 || gameStarted < 0) {
gameStarted = mainMenu();
}
//Like Void Start() in Unity
if (gameStarted == 1) {
class Player {
public:
int life = 20;
int accuracy = 80 + (rand() % 100) / 20;
int damage = 5 + (accuracy / 10) + (rand() % 100) / 50;
bool isAlive = true;
int x = 39;
int y = 24;
int speed = 2;
};
class Enemy {
public:
int life = 100;
int satisfaction = 0;
bool isAlive = true;
bool isSatisfied = false;
int damage = 2 + (rand() % 100) / 20;
};
Player Player;
Enemy Enemy;
draw(Player.x, Player.y);
//Like Void Update() in Unity
while (gameStarted != 0) {
//Draw if proyectile is moving - not yet
//Draw if player is moving (pay attention specially to this part)
if (detectKeyPressing() == 0) {
gameStarted = 0; //if ESC is pressed, exit the loop and exits
}
//If any of the Arrow Keys are pressed
else if (detectKeyPressing() > 1 && detectKeyPressing() < 6) {
switch (detectKeyPressing()) {
//Up
case 2:
Player.y -= Player.speed;
break;
//Left
case 3:
Player.x += Player.speed;
break;
//Down
case 4:
Player.y += Player.speed;
break;
//Right
case 5:
Player.x += Player.speed;
break;
};
system("cls"); //Erase all
draw(Player.x, Player.y); //Redraw everything, with Player.x and Player.y supposedly modified
};
};
};
return 0;
};
I did a few tests and it seems that the else if in "//If any of the Arrow Keys is Pressed" part isn't running but I don't know why.
I would really appreciate any help you can provide. Sorry if anything isn't well written, I'm not a native english speaker.
Where you have this comment
//Draw if proyectile is moving - not yet add a variable to save your pressed key, something like
int pressedKey = detectKeyPressing();
Then, use that variable to check which condition is met within your if-else.
What’s happening is that you’re calling your function, thus asking/waiting for an input each time a condition is being checked.

Tic Tac Toe overwritten array user inputs

The issue I am having is this:
I input a choice in square 1 "X" then it is O's turn so just to test things I input square 1 again. The error message pops up about it being an invalid square please enter another square. So I input a valid square and then the board gets drawn by the function and that's when I find out that the "X" in square one has been overwritten. This happens regardless of which character, X or O, is selected at the time. I'm kind of at my wits end and just looking for a little help with that part of the program. I figure once I hammer this part out the random number generator for the computers turn will be simple to implement, as well as checking for a win condition.
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include <ctime>
const int yCoordMax = 6;
const int xCoordMax = 2;
int xCoord;
int yCoord;
int square = 0;
const std::string PLAYER1 = "X";
const std::string COMPUTER = "O";
int turnCount = 0;
const int MAXTURN = 9;
int whoIsPlayer = 0; //denotes human with 0 and computer with 1 alternating between
std::string playerChar = " "; //the current turn's player's symbol
const std::string WIN = "You won!\n";
const std::string LOSE = "You lost.\n";
const std::string DRAW = "It's a draw.\n";
const std::string PLAY = "You will be the X's against the computer O's\n\n";
const std::string INSTRUCTIONS = "Enter the number of the square you wish to mark\nwith 1 being top left and 9 being bottom right.\n\n";
const std::string INVALIDSQUARE = "Please enter a correct square number between 1 and 9.\n";
const std::string SQUAREISFULL = "That square is already marked. Choose another.\n";
bool squareIsFilled[9] {0}; // any NON-Zero is true; ZERO is false
//array is zero thru eight
void drawBoard(void);
void convertSquareToCoordinates(std::string);
void validMove (int, std::string);
void drawMove(int, std::string, int, int);
void computerTurn(std::string);
std::string board[7][3] =
{ //0 //1 //2
{"+----", "+----+", "----+\n"}, // 0
{"| ", "| |", " |\n"}, // 1 input here only [1][0], [1][1], [1][2]
{"+----", "+----+", "----+\n"}, // 2
{"| ", "| |", " |\n"}, // 3 input here only [3][0], [3][1], [3][2]
{"+----", "+----+", "----+\n"}, // 4
{"| ", "| |", " |\n"}, // 5 input here only [5][0], [5][1], [5][2]
{"+----", "+----+", "----+\n"} // 6
};
int main()
{
std::srand(time(0));
std::cout << PLAY;
std::cout << INSTRUCTIONS;
drawBoard();
while (turnCount < MAXTURN)
{
if(whoIsPlayer == 0)
{
playerChar = PLAYER1;
convertSquareToCoordinates(playerChar);
whoIsPlayer = 1;
}
else
{
playerChar = COMPUTER;
convertSquareToCoordinates(playerChar);
whoIsPlayer = 0;
}
++turnCount;
}
return 0;
}
void drawBoard()
{
for (int y = 0; y <= yCoordMax; ++y)
{
for (int x = 0; x <= xCoordMax; ++x)
{
std::cout << board[y][x];
}
}
}
void convertSquareToCoordinates(std::string playerChar)
{
int square;
int yCoord;
int xCoord;
std::cout << std::endl;
std::cin >> square;
while(square < 1 || square > 9)
{
std::cout << INVALIDSQUARE;
std::cin >> square;
}
if (square == 1)
{yCoord = 1;
xCoord = 0;} //bool needs to flag invalid if square is filled
if (square == 2) //if square is empty then flag bool as filled
{yCoord = 1; //so validMove will skip execution
xCoord = 1;}
if (square == 3)
{yCoord = 1;
xCoord = 2;}
if (square == 4)
{yCoord = 3;
xCoord = 0;}
if (square == 5)
{yCoord = 3;
xCoord = 1;}
if (square == 6)
{yCoord = 3;
xCoord = 2;}
if (square == 7)
{yCoord = 5;
xCoord = 0;}
if (square == 8)
{yCoord = 5;
xCoord = 1;}
if (square == 9)
{yCoord = 5;
xCoord = 2;}
validMove(square, playerChar);
drawMove(square, playerChar, yCoord, xCoord);
}
void validMove(int square, std::string playerChar)
{
if(square == 1)
{
if(squareIsFilled[square - 1] == true){
if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 2)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 3)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
// checks middle column for mark
if(square == 4)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 5)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 6)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
// checks right column for mark
if(square == 7)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 8)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
if(square == 9)
{
if(squareIsFilled[square - 1] == true)
{if(whoIsPlayer == 0){
std::cout << SQUAREISFULL;}
convertSquareToCoordinates(playerChar);}
else
{squareIsFilled[square - 1] = true;}
}
}
void drawMove(int square, std::string playerChar, int yCoord, int xCoord)
{
if(square == 1) //Draws left column move
board[yCoord][xCoord] = "| " + playerChar + " ";
else if(square == 2)
board[yCoord][xCoord] = "| " + playerChar + " |";
else if(square == 3)
board[yCoord][xCoord] = " " + playerChar + " |\n";
if(square == 4) //Draws middle column move
board[yCoord][xCoord] = "| " + playerChar + " ";
else if(square == 5)
board[yCoord][xCoord] = "| " + playerChar + " |";
else if(square == 6)
board[yCoord][xCoord] = " " + playerChar + " |\n";
if(square == 7) //Draws right column move
board[yCoord][xCoord] = "| " + playerChar + " ";
else if(square == 8)
board[yCoord][xCoord] = "| " + playerChar + " |";
else if(square == 9)
board[yCoord][xCoord] = " " + playerChar + " |\n";
drawBoard();
}
Look at convertSquareToCoordinates:
...
validMove(square, playerChar);
drawMove(square, playerChar, yCoord, xCoord);
If square refers to a square that is already filled, this function still calls drawMove on the corresponding (yCoord, xCoord).
More fundamentally, convertSquareToCoordinates and validMove call each other in a weird way. And your function names do not clearly describe what the functions are supposed to do.

C++ Tic Tac Toe project

I'm now working on a Tic Tac Toe project. I'm having the problem that whenever I input into the console an ordinate,for example [6][0] (and the program will put the mark 'X' or 'O' into that position) for an array with the size of [15][15],it will automatically save the mark 'X' or 'O' into another position which is not in the array range (in my case is [5][15]).This is my program (P/S: I'm Vietnamese so just ignore the parts that are in Vietnamese):
int size = 15;
int inputAmount;
int inputX = 0;
int inputY = 0;
char board[15][15];
bool checkWin = false;
char mark = 'X';
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
}
// Lay-coordinate of the muon practice player list
void takeInput() {
do {
// Lay gia tri toa do x
do {
cout << "Please choose the horizontal (rightward) number (smaller than " << size + 1 << "): ";
cin >> inputX;
} while ((inputX > size) || (inputX <= 0));
// Lay y coordinate values
do {
cout << "Please choose the vertical (downward) number (smaller than " << size + 1 << "): ";
cin >> inputY;
} while ((inputY > size) || (inputY <= 0));
inputX--;
inputY--;
if (board[inputX][inputY] != '.')
cout << "Already chosen!" << endl ;
} while (board[inputX][inputY] != '.');
board[inputX][inputY] = mark;
if (mark == 'X')
mark = 'O';
else
mark = 'X';
cout << endl << endl << endl;
}
// Hien game board on the screen
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (; y < size ; y++)
{
for (; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
x = 0;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
x,y = 0;
takeInput();
inputAmount++;
}
}
// At first preparation game board
void prepareGameboard () {
int x,y;
for (; y < size ; y++)
{
for (; x < size ; x++)
{
board[x][y] = '.' ;
}
x = 0;
}
}
int main(array<System::String ^> ^args)
{
char reset = 'y';
do {
prepareGameboard();
loadGameboard();
checkWin = 0;
inputAmount = 0;
cout << "Do you want to replay ? (y/n): ";
cin >> reset;
if ((reset == 'y') || (reset == 'Y'))
{
system("CLS");
}
} while ((reset == 'y') || (reset == 'Y'));
return 0;
}
I would change x,y = 0 to x = y = 0 at line 123 in the code you pasted. And also add return 0 to the function checkWinLose().
You are not initializing the values for x and y in ther for's.
Try to use :
void prepareGameboard () {
int x,y;
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
board[x][y] = '.' ;
}
}
}
And:
void loadGameboard () {
int x,y;
////TODO: check win or lose
while (!checkWin) {
for (y = 0; y < size ; y++)
{
for (x = 0; x < size ; x++)
{
cout << board[x][y] << " ";
}
cout << endl;
}
checkWin = checkWinLose();
if (checkWin == true)
return;
takeInput();
inputAmount++;
}
}
Also, like #Heinz said, and a return 0; at the end of the checkWinLose function;
Looking at your code, I believe the you are assuming the int always are initialized with 0 and that checkWinLose will return 0 by the default. Local variables have undefined initialization values and when no explicity return is called, the function just return so 'garbage' value.
Try to always add the returned value to the functons and initialize your variables (specially counters).
Update
This is how the function checkWinLose should be with the return 0;
// Interdisciplinary examination of scale loss
bool checkWinLose() {
int max;
int x,y;
x = inputX;
y = inputY;
// Looking horizontally under investigation
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y] && board[x - 1][y] == board[x - 2][y]))
{
cout << "Game over ngang!" << endl;
return 1;
}
x++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of vertical
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x][y - 1] && board[x][y - 1] == board[x][y - 2]))
{
cout << "Game over doc!" << endl;
return 1;
}
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from left to right
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x - 1][y - 1] && board[x - 1][y - 1] == board[x - 2][y - 2]))
{
cout << "Game over trai sang phai!" << endl;
return 1;
}
x++;
y++;
}
x = inputX;
y = inputY;
max = 0;
// Interdisciplinary examination of under the cliff cave from right to left
for (; max < 3; max++)
{
if ((board[x][y] == 'X' || board[x][y] == 'O') && (board[x][y] == board[x + 1][y - 1] && board[x + 1][y - 1] == board[x + 2][y - 2]))
{
cout << "Game over phai sang trai!" << endl;
return 1;
}
x--;
y++;
}
// Flower test case
if (inputAmount == 225)
{
cout << "Game over hoa!" << endl;
return 1;
}
return 0; //<- Returning false if the all other tests failed
}

using random in class to make a loop

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