c++ tron 2d array repeating - c++

I am trying to get a trail to appear behind the player bike but for some reason instead of a "x" appearing behind the player every time it moves, the player would actually duplicate itself. It sounds a little confusing but you should compile this code yourself and see what i mean. What I am trying to do is just have a trail of "x" behind the player instead of the player leaving a trail of "P". thanks
#include <iostream>
#include "windows.h"
#include <conio.h>
#include <ctime>
using namespace std;
//prototype functions used
void DisplayMap();
void PlayerBike();
void setCursorTo();
void SetBike();
//global variables that will be used by different functions
int PlayerX = 10;
int PlayerY = 70;
bool GameOver = false;
const int H = 25; // const variable so it doesnt change size
const int W = 82;// const variable so it doesnt change size
char Map[H][W]; // char map with HxW
char trail = 'x'; // this is where the trail is initialized as a *
int main()
{
SetBike();
DisplayMap();
while (GameOver == false){
setCursorTo();
PlayerBike();
} // end while loop
return 0;
}//end main
void DisplayMap(){ // display map function
for(int i = 0; i < H; i++ ){
for(int j = 0; j < W; j++){
if(i == 0 || i == 24 || j == 0 || j == 81 ){ Map[i][j] = 'x';} // characters in row 24x81 are changed to x
cout << Map[i][j]; // output map
} // end for loop
cout << "\n"; // create new line to output the map correctly
} //end for loop
} // end DisplayMap function
void SetBike(){
Map[PlayerX] [PlayerY] = 'P';
}
void PlayerBike(){
Map[PlayerY][PlayerX]= trail; // I would like this trail to repeat behind the player but it does not appear at all.
if (kbhit()) {// get user key input
char GetCh = getch(); // GetCh equal to the button the user presses
if (GetCh == 'w'){PlayerX = PlayerX - 1; Trailx = Trailx -1;}
else if (GetCh == 's'){PlayerX = PlayerX +1; Trailx = Trailx +1;}
else if (GetCh == 'd'){PlayerY = PlayerY +1;}
else if (GetCh == 'a'){PlayerY = PlayerY - 1;}
}// end kbhit
}// end PlayerBike function
void setCursorTo() // stops constant flashing on the map
{
HANDLE handle;
COORD position;
handle = GetStdHandle(STD_OUTPUT_HANDLE);
position.X = 0;
position.Y = 0;
SetConsoleCursorPosition(handle, position);
}

Your DisplayMap function is flawed.
First, it seems you are not only displaying the map, you are also actively modifying it. Put the drawing-a-border into a separate initMap function, which also zeros out all other positions with a space (it seems you didn't do that yet, so perhaps that is where it goes wrong). You only need to call initMap once.
Next, do not draw the player P in the DisplayMap function. Draw this once, before entering the game loop. Then: if the user pressed a valid move key,
put an x on the player's position
update player position
put a P on the new position
redraw the screen by calling DisplayMap
and you'll see the trail stays put.
Possible refinements: before accepting a 'move' command by updating the position, check if the map contains a space or something else. If it contains a space, you can execute the move; if not, play an explosion animation (*oO*+.). Also, consider looking up the switch statement in your favourite C reference, to avoid endless long sequences of if..else.

Related

PathFinding Algorithm not working

I have a school project where we have to create a game on C++. We are divided into groups and I had to create the pathfinding for it. The program compiles (although it is very slow) and my algorithm does not work. It does not always find the shortest path.
The game is the following: You have a labyrinth, a player and three enemies. The task is to make the enemies find their path to the player and they can move only one "character" every time the player moves.
#include "MapGeneration.cpp"
#include <iostream>
#include <string>
#include <stdlib.h>
#include "EnemyClass.cpp" //use the enemy stuff to get the entity stuff
//in EntityClass see if the xPos and yPos are changing
using namespace std;
/* Variables */
int row; // rows
int col; // columns
const int enemnumb = 3;
const int playnumb = 1;
int playcount = 1; // Counting how much players are left
int enemcount = 3; // Counting how much enemies are left
int enemcordr[enemnumb]; // Enemy row number
int enemcordc[enemnumb]; // Enemy column number
int playcordr[playnumb]; // Player row number
int playcordc[playnumb]; // Player column number
/* Find enemies */
int findAllEnem(){
bool found = false;
while(!found){ // If all enemies are found while loop stops
for(row=0;row<MapRowSize;row++){ // Searches in rows
for(col=0;col<MapColumnSize;col++){ // Searches in columns
if(arrCurrentMap[row][col]=='e'){ // If it finds the letter 'e'
enemcordr[enemcount]=row; // Save the row number
enemcordc[enemcount]=col; // Save the column number
enemcount--; // Substracts 1 from the enemy count in order to show how much are left
}
if(enemcount==0){ // If there are no left enemies
found=true; // All enemies will be found and will stop the while loop
}
}
}
}
}
/* Find players */
int findPlayer(){
bool found = false;
while(!found){ // If player is found
for(row=0;row<MapRowSize;row++){ // Searches in rows
for(col=0;col<MapColumnSize;col++){ // Searches in columns
if(arrCurrentMap[row][col]=='p'){ // If it finds the letter 'e'
playcordr[playcount]=row; // Save the row number
playcordc[playcount]=col; // Save the column number
playcount--; // Substracts 1 from the enemy count in order to show how much are left
}
if(playcount==0){ // If there are no left enemies
found=true; // All enemies will be found and will stop the while loop
}
}
}
}
}
int enemMovement() {
srand(time(NULL));
bool makeMove = false; // to check if the enemy has already made a move
bool legit = false;
const int possible = 1500;
int possmov = 1;
int min[possible]; // minimum distance
int countMove[possible][enemnumb]; // counts how many moves have been made with road
int moveR[possible][enemnumb]; // gets virtual row without moving the enemy
int moveC[possible][enemnumb]; // gets virtual column without moving the enemy
int found[possible][enemnumb]; // if enemy found the player
for (playcount = playnumb; playcount > 0; playcount--) { // for every player
for (enemcount = enemnumb; enemcount > 0; enemcount--) { // the three enemies
for (possmov = 0; possmov < possible; possmov++) { // possible directions
moveR[possmov][enemcount] = enemcordr[enemcount];
moveC[possmov][enemcount] = enemcordc[enemcount];
while (legit != true) {
int previous;
int nRand = rand()%(4-0)+1; //4 possible directions
if (nRand == 1) { //move right
if (arrCurrentMap[moveR[possmov][enemcount]][moveC[possmov][enemcount] + 1] != '#') {
if (arrCurrentMap[moveR[possmov][enemcount]][moveC[possmov][enemcount] + 1] == 'p') {
found[possmov][enemcount]=countMove[possmov][enemcount];
legit=true;
}
moveC[possmov][enemcount]++;
countMove[possmov][enemcount]++;
}
}
if (nRand == 2) // move left
{
if (arrCurrentMap[moveR[possmov][enemcount]][moveC[possmov][enemcount] - 1] != '#') {
if (arrCurrentMap[moveR[possmov][enemcount]][moveC[possmov][enemcount] - 1] == 'p') {
found[possmov][enemcount]=countMove[possmov][enemcount];
legit=true;
}
moveC[possmov][enemcount]--;
countMove[possmov][enemcount]++;
}
}
if (nRand == 3) // move up
{
if (arrCurrentMap[moveR[possmov][enemcount] - 1][moveC[possmov][enemcount]] != '#') {
if (arrCurrentMap[moveR[possmov][enemcount] - 1][moveC[possmov][enemcount]]== 'p') {
found[possmov][enemcount]=countMove[possmov][enemcount];
legit=true;
}
moveR[possmov][enemcount]--;
countMove[possmov][enemcount]++;
}
}
if (nRand == 4) // move down
{
if (arrCurrentMap[moveR[possmov][enemcount] + 1][moveC[possmov][enemcount]] != '#') {
if (arrCurrentMap[moveR[possmov][enemcount] + 1][moveC[possmov][enemcount]]== 'p') {
found[possmov][enemcount]=countMove[possmov][enemcount];
legit=true;
}
moveR[possmov][enemcount]++;
countMove[possmov][enemcount]++;
}
}
}
legit=false; // returns the value of legit to false for next move road
}
min[enemcount]=possible;
for(int i=0;i<=possible;i++){ // finds the shortest path
if(found[i][enemcount]<min[enemcount] && found[i][enemcount] != 0){
min[enemcount]=found[i][enemcount];
}
}
}
}
}
/* Main function */
int main (){
GenerateLoadingMap(1); // Generate map
findPlayer(); // Finds players
findAllEnem(); // Find enemies
enemMovement(); // enemy movement
return 0;
}
This is the code I wrote. Sometimes it finds the shortest path but not always. Also I would like for an advice on how to store the coordinates after every move.

Can't figure out how to loop playerturns and moves Tic Tac Toe (C++) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
EDIT: Solved now thank you triple_r and AJNeufield for your help on this problem I was having.
I've looked around multiple websites and YouTube about this and I can't seem to find anything on what I am specifically looking for this as my format for the program is a good bit different than others. Therefore, it's hard to decipher where I need to put the things I do need that I know of.
Please note that I'm relatively new to C++ so I'd appreciate all the feedback or criticism you might provide me.
Also, note my code does compile and run it just does not allow me to put in more than one input and more than likely does not allow for a switch of player turns.
Quick Edit: Switched the code with the new setup suggested by triple_r but I seemed to have messed it up somewhere along the line and it does compile(with the exception of x and y not being utilized and one other error) but it always starts off with player 2 going first and as soon as it receives input it ends automatically with a segmentation fault.
#include <iostream>
#include <cstdlib>
using namespace std;
//////////////////////////////////////////////////////////
void initboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
for (y=0;y<3;y++)
board[x][y]=' ';
return;
}
//////////////////////////////////////////////////////////
void printboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
{
cout<<"\n";
for (y=0;y<3;y++)
{
cout<<" "<<board[x][y]<<" ";
if (y<2) cout<<"|";
}
if (x<2) cout<<"\n===========";
}
return;
}
//////////////////////////////////////////////////////////
void getmove(char board[3][3], int player)
{
return;
}
//////////////////////////////////////////////////////////
int main()
{
bool done=false;
char board[3][3];
int x,y,player=1,turn,playerchoice,playermark;
initboard(board);
turn=0;
do
{
if (player==1)
playermark='X';
else
playermark='O';
if (turn%2)
player=1;
else
player=2;
cout<<"Player "<<player<<" where do you want to move?: ";
cin>>playerchoice;
if (playerchoice==1)
{
board[0][0]=playermark;
}
else if (playerchoice==2)
{
board[0][1]=playermark;
}
else if (playerchoice==3)
{
board[0][2]=playermark;
}
else if (playerchoice==4)
{
board[1][0]=playermark;
}
else if (playerchoice==5)
{
board[1][1]=playermark;
}
else if (playerchoice==6)
{
board[1][2]=playermark;
}
else if (playerchoice==7)
{
board[2][0]=playermark;
}
else if (playerchoice==8)
{
board[2][1]=playermark;
}
else if (playerchoice==9)
{
board[2][2]=playermark;
}
else
{
cout<<"Invalid move ";
}
if (board[x][y]!=' ')
cout<<"Move is already taken.";
board[x][y]=playermark;
if(board[x][y]==' ')
turn++;
}while (!done);
void printboard(char board[3][3]);
return 0;
}
EDIT: based on the updated code
So, the first thing I can see is that you are using x and y in your program but you don't initialize them or assign any values to them. Also, try to use functions/classes/... yo make your code more readable. You already have a function for player move but you are not using it. You can move the large if statement inside that function and that will make your main code shorter and more readable.
Here are my comments on the main part of your program:
int main()
{
// add a new variable to see if the move was valid or not:
bool done=false, validmove = true;
char board[3][3];
int x, y, player = 1, turn = 0, playerchoice, playermark;
initboard(board);
do
{
// swap the two `if`s so you decide who`s turn it is then assign the player mark,
// also, reverse the condition to make sure turn '0' is player 1's turn.
if (!(turn % 2))
player = 1;
else
player = 2;
if (player == 1)
playermark = 'X';
else
playermark = 'O';
cout << "Player " << player << " where do you want to move?: ";
cin >> playerchoice;
// Assign `x` and `y` here instead of updating the board, because you want to make
// sure that the move is valid before putting the mark:
validmove = true;
if (playerchoice == 1)
{
x = 0; y = 0;
}
else if (playerchoice == 2)
{
x = 0; y = 1;
}
else if (playerchoice == 3)
{
x = 0; y = 2;
}
else if (playerchoice == 4)
{
x = 1; y = 0;
}
else if (playerchoice == 5)
{
x = 1; y = 1;
}
else if (playerchoice == 6)
{
x = 1; y = 2;
}
else if (playerchoice == 7)
{
x = 2; y = 0;
}
else if (playerchoice == 8)
{
x = 2; y = 1;
}
else if (playerchoice == 9)
{
x = 2; y = 2;
}
else
{
cout << "Invalid move, try again!";
// Make sure to mark the move as invalid so they get a chance to
// change their move:
validmove = false;
}
// check to see if the turn was valid:
if(validmove)
{
if (board[x][y] != ' ')
{
cout << "Move is already taken, try again";
}
else
{
board[x][y] = playermark;
turn++;
}
}
// have to make sure you have a condition for end of game. A simple
// one is to check if turn is less than `9`, otherwise the board is
// full:
if(turn == 9)
done = true;
// you probably want to add a few more checks to see who won the game.
}while (!done);
// when calling a function, no need to put the return type or parameter type:
printboard(board);
return 0;
}
========================================================================
There are two do-while loops in your program and both seem to be meant as a game loop. What I would do is:
initboard(...);
turn = 0;
do{
//this is the game loop
...;
if( validturn )
turn++;
}while(!done);
release_resources(...);
return 0;
so, you fold everything into one loop. In that loop, you want to:
find who's turn it is:
if (turn % 2)
player = 1;
else
player = 2;
get users input:
std::cin >> playerchoice;
...
convert player choice to grid location:
switch ( move )
{
case 0:
x = 0;
y = 0;
break;
case 1:
...;
...
default:
//invalid move
}
see if the move is valid:
if( board[x][y] != ' ' )
//already taken, invalid move
then apply the move:
board[x][y] = playermark;
I hope this helps.
Your cin >> playerchoice is outside your do { ... } while ( moves != 9); loop. Move it inside.

Trying to make a primitive console snake game. 0 warnings/erros. Why does my program crash? (C++)

Thank you for reading this thread. I am a beginning programmer and am trying to make a simple snake game with C++. It isn't finished yet, but I think I got a nice start to it. However, when I try to run the program it instantly crashes. (The compiler says there are 0 warnings and errors. I am using the Code::Blocks IDE. Does anyone know why my program isn't working? I think it may have something to do with the "vector coordHistory", but I can't tell for sure. At least that is the last thing I added to the program.
This is my code:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <windows.h>
#include <conio.h>
#include <vector>
#define MAXX 156 //Number of columns that fits on my screen
#define MAXY 62 //Number of rows that fits on my screen
using namespace std;
// This function clears the console window
void clearConsole()
{
system("cls"); //empties console window
};
// This function returns the x position of the cursor
int getcursorX()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
return csbi.dwCursorPosition.X;
}
};
// This function returns the y position of the cursor
int getcursorY()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
return csbi.dwCursorPosition.Y;
}
};
// This function sets the x position of the cursor
void setcursorX(int x)
{
COORD coord = {x, getcursorY()};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// This function sets the y position of the cursor
void setcursorY(int y)
{
COORD coord = {getcursorX(), y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// The snake class contains the coordinates of the snake and direction in which it is moving
class Snake
{
private:
bool isAlive;
int snakexCoord;
int snakeyCoord;
char snakeDirection;
int snakeLength;
public:
//getters
int getsnakexCoord() { return snakexCoord; };
int getsnakeyCoord() { return snakeyCoord; };
char getsnakeDirection() { return snakeDirection; };
bool getisAlive() { return isAlive; };
int getsnakeLength() { return snakeLength; };
//setters
void setsnakexCoord(int newsnakexCoord) { snakexCoord = newsnakexCoord;};
void setsnakeyCoord(int newsnakeyCoord) { snakeyCoord = newsnakeyCoord;};
void setsnakeDirection(char newsnakeDirection) { snakeDirection = newsnakeDirection;};
void setisAlive(bool newisAlive) { isAlive = newisAlive; };
void setsnakeLength(int newsnakeLength) { snakeLength = newsnakeLength; };
//constructor
Snake()
{
snakexCoord = MAXX / 2;
snakeyCoord = MAXY / 2;
snakeDirection = 'E';
isAlive = true;
snakeLength = 1;
};
//destructor
~Snake(){};
};
int main()
{
int i; //iterator
system("mode 650"); //makes console window full-screen
Snake snake; //initializes Snake object snake
char c; //char that stores user input to change snake direction
vector<int[2]> coordHistory; //vector of arrays that stores previous locations of snake
while (snake.getisAlive())
{
//Adds snake coordinates to coordHistory
coordHistory[coordHistory.size()][0] = snake.getsnakexCoord();
coordHistory[coordHistory.size()-1][1] = snake.getsnakeyCoord();
//Iterates backwards through coordHistory and draws an "O" until the snake is as long as it should be
for(i = coordHistory.size() - 1; i > coordHistory.size() - 1 - snake.getsnakeLength(); i--)
{
setcursorX(coordHistory[i][0]);
setcursorY(coordHistory[i][1]);
cout << "O";
}
//Allows user to change snake direction
c = _getch();
switch (c){
case 'w':
snake.setsnakeDirection('N');
break;
case 'd':
snake.setsnakeDirection('E');
break;
case 's':
snake.setsnakeDirection('S');
break;
case 'a':
snake.setsnakeDirection('W');
break;
}
//Checks in which direction snake is going and changes coordinates accordingly
switch (snake.getsnakeDirection())
{
case 'N':
snake.setsnakeyCoord(snake.getsnakeyCoord()-1);
break;
case 'E':
snake.setsnakexCoord(snake.getsnakexCoord()+1);
break;
case 'S':
snake.setsnakeyCoord(snake.getsnakeyCoord()+1);
break;
case 'W':
snake.setsnakexCoord(snake.getsnakexCoord()-1);
break;
}
//Checks if snake goes out of boundaries
if ((snake.getsnakexCoord() > MAXX) || (snake.getsnakexCoord() < 0) || (snake.getsnakeyCoord() > MAXY) || (snake.getsnakeyCoord() < 0))
{
snake.setisAlive(false);
}
//Sleep(200); Ignore WIP
clearConsole();
}
return 0;
}
Your vector usage is wrong.
coordHistory[coordHistory.size()][0] = snake.getsnakexCoord();
coordHistory[coordHistory.size()-1][1] = snake.getsnakeyCoord();
You appear to assume that vector[n-1] will automatically create as many elements as needed to result in a vector of size n. It doesn't.
You are twice accessing the first element of vector coordHistory, a vector which is actually empty.
To add elements, in general use the member function push_back or emplace_back. You're really going to struggle with a vector of arrays, though, since arrays are neither assignable nor copyable. That's why I can't use push_back here; I have to explicitly resize the vector then access the newly-created elements as you were doing before:
coordHistory.resize(1);
coordHistory[0][0] = snake.getsnakexCoord();
coordHistory[0][1] = snake.getsnakeyCoord();
This is pretty awkward. why don't you instead store a nice delicious class type with x and y members?
std::vector<deliciousClassType> coordHistory;
coordHistory.emplace_back(
snake.getsnakexCoord(),
snake.getsnakeyCoord()
);

platform game using sfml 1.6 in c++ collision using AABB's

I am using tile mapping and have my map class in place to draw the map by using an array of sprites. i have it to set the position of the sprite and then create a bounding box array around it and then draw the sprite.
i then have a collision class which gets the player bounding box and compares it with each bounding box for the sprite. i have an array called platformboundingBox. this stores each bounding box of each sprite in the array. however when i compare the values it seems that the platform bounding box has no values in any of the locations yet the i have checked that the values of each sprite go into the bounding box array.
here is my map class. see the drawmap and collision functions to take a look. if anyone can help i would really appreciate it.
#include "Map.h"
#include "Block.h"
#include <sstream>
using namespace std;
Map::Map()
{
//map ctor;
}
Map::~Map()
{
// map dtor
}
void Map::Initialise(const char *filename)
{
if(!BlockImage.LoadFromFile("Images/block.png"))
cout<<endl<<"failed to load block image"<<endl;
if(!GemImage.LoadFromFile("Images/Gem.png"))
cout<<endl<<"failed to load Gem Image"<<endl;
if(!leftBlockImage.LoadFromFile("Images/blockLeft.png"))
cout<<endl<<"failed to load left block Image"<<endl;
if(!rightBlockImage.LoadFromFile("Images/blockRight.png"))
cout<<endl<<"failed to load right block Image"<<endl;
std::ifstream openfile(filename);
std::vector <int> tempvector;
std::string line;
while(std::getline(openfile, line))
{
for(int i =0; i < line.length(); i++)
{
if(line[i] != ' ') // if the value is not a space
{
char value = line[i];
tempvector.push_back(value - '0');
}
}
mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
tempvector.clear(); // clear the temp vector readt for the next value
}
}
void Map::DrawMap(sf::RenderWindow &Window)
{
Player playermap;
for(i = 0; i < mapVector.size(); i++)
{
for(j = 0; j < mapVector[i].size(); j++)
{
if(mapVector[i][j] == 1)
{
sprite[j].SetImage(BlockImage);
sprite[j].SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
platformBoundingBox[j].Bottom = sprite[j].GetPosition().y;
platformBoundingBox[j].Left = sprite[j].GetPosition().x - 5;
platformBoundingBox[j].Right = sprite[j].GetPosition().x;
Window.Draw(sprite[j]);
}
else if(mapVector[i][j] == 2)
{
sprite[j].SetImage(GemImage);
sprite[j].SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
platformBoundingBox[j].Top = sprite[j].GetPosition().y - 5;
platformBoundingBox[j].Bottom = sprite[j].GetPosition().y;
platformBoundingBox[j].Left = sprite[j].GetPosition().x - 5;
platformBoundingBox[j].Right = sprite[j].GetPosition().x;
Window.Draw(sprite[j]);
}
else if(mapVector[i][j] == 3)
{
sprite[j].SetImage(leftBlockImage);
sprite[j].SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
platformBoundingBox[j].Top = sprite[i].GetPosition().y - 5;
platformBoundingBox[j].Bottom = sprite[i].GetPosition().y;
platformBoundingBox[j].Left = sprite[i].GetPosition().x - 5;
platformBoundingBox[j].Right = sprite[i].GetPosition().x;
Window.Draw(sprite[j]);
}
else if(mapVector[i][j] == 4)
{
sprite[j].SetImage(rightBlockImage);
sprite[j].SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
platformBoundingBox[j].Top = sprite[i].GetPosition().y - 5;
platformBoundingBox[j].Bottom = sprite[i].GetPosition().y;
platformBoundingBox[j].Left = sprite[i].GetPosition().x - 5;
platformBoundingBox[j].Right = sprite[i].GetPosition().x;
Window.Draw(sprite[j]);
}
}
}
}
void Map::collisions(float x, float y)
{
Player playermap;
this->x = x;
this->y = y;
playerboundingbox.Top = y - 5;
playerboundingbox.Bottom = y ;
playerboundingbox.Left = x - 5;
playerboundingbox.Right = x;
for(i = 0; i < 100; i++)
{
if(playerboundingbox.Intersects(platformBoundingBox[i]))
cout << " praise the lord";
}
}
Please switch to SFML 2 because 1.6 have a lot of bugs.
Let's say you create a class named handler where you will put:
handler::handler()
// window initialization
Map Map; // here initialize the Map class
/* why don't use Map::Map( ctor) for initialization? */
// player initialization
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
//draw player
Map.DrawMap(); // also need to improve the drawing for less lag
window.display();
update(Map &Map, Player &Player);
// every time to use & because without the compiler will create another object
}
}
update(Map &Map, Player &Player)
{
// verify if exists some interacts
if (intersects(Map &Map, Player &Player))
{
//verify from where and put to the correct position
/* e.g: if we have a collide with a down tile map will say something like this:
Player.setPosition(Player.getPosition().x, (Player.getGlobalBounds().top+Player.getGlobalBounds().height)-(Map.getGlobalBounds().top-(Player.getGlobalBounds().top+Player.getGlobalBounds().height)); */
}
}
intersects(Map &Map, Player &Player)
{
sf::FloatRect fPlayer = Player.getGlobalBounds();
for (int i=0; i<Map.NrOfYourTiles; ++i)
{
sf::FloatRect fMap = YourTile.getGlobalBounds();
if (fPlayer.intersects(fMap))
return 1;
}
return 0;
}
Hope this will help you( the code is in SFML 2.0). You can find a lot more help on forums of the creator sfml-dev.org.

C++ console game input && refresh function

I am writing a small console adventure game and I faced a few problems.
1. The input is kinda laggy, I'm using while loop ( while(getch() == 'w') ). After a key is pressed the first time, nothing happens (you have to press it 2 times) and if you switch directions (press key A/D/S) it also doesn't react the 1st time. If you hold a key, it works fine. How can this be fixed?
2. Here's the function I use to refresh game (render the game scene when a key is pressed):
void refresh(char map[Y][X])
{
system("cls");
for (int i = 0; i<UP; i++)
{
cout<<endl;
}
for (int i = 0; i<Y; i++)
{
for (int k = 0; k<LEFT; k++)
{
cout<<" ";
}
for (int j = 0; j<X; j++)
{
cout<<map[i][j];
}
cout<<endl;
}
}
When I use this function once, it's ok, but when they key is pressed or held multiple times - the game field starts to flash. I figured that I need to redraw only a part of the field (where changes are made/movements are done), not the whole field. Can you offer any ideas how to do that?
The sample code for input:
while(getch() == 'w')
{
if (map[y-1][x]!= WALL)
{
map[y-1][x] = CHARACTER;
map [y][x] = ' ';
y--;
refresh(map);
Sleep(SPEED); // this is unnecessary, SPEED is 0, I just kept it for tests
}
}
Basically, the main function looks like this:
int main()
{
(...) Variables (...)
generateMap(FROM FILE);
refresh(); // First initialization of the field
while (getch() != 'q') // While not quitting
{
while(getch() == 'w')
{
if (THE FIELD ABOVE IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 's')
{
if (THE FIELD BELOW IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'a')
{
if (THE FIELD ON THE LEFT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'd')
{
if (THE FIELD ON THE RIGHT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
return 0;
}
Don't use system("cls"), it is really slow, instead set the cursor on the beginning of the screen with the following code:
COORD cur = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur);
You should call getch() only one time in the loop, like this:
char key;
do
{
key = getch();
if(key == 'w')
{
//do something
}
//the other if statements
}while(key != 'q');
The code should have only one getch() in the whole code (if possible) and inside a switch you do the action for each input. So, it is switch inside the loop, and not loops inside the switch. Something like this:
while ((ch = getch()) != 'q')
{
switch (ch)
{
case 'a':
GoLeft();
break;
...
}
}
There is a library called ncurses that you can use to move the cursor around the screen, and write anything anywhere.
It looks like your problem is calling getch() multiple times. Have only one loop, and call getch() once per loop, and store the result. Test that result for each value (q, w, s, ...) for each iteration of the loop.
I would recommend you to use function input() as it stands:
void input()
{ if (GetKeyState('W') & 0x8000) // That means when button "W" is pressed
... your code ...
// (changes global variables, or you can pass variables by reference)
}
without any getch() command that stops your game every single time.
You can use it with the draw() and calculate()/refresh() functions in the main(), like:
int main()
{
... other part of code ...
while (!gameover)
{
input();
calculate();
draw();
}
}
so that you will always have some sort of input value before the calculations, and then you would draw (+ it's much easier to debug ;) )