I am making a simple game using C++ It's just a tile game with an ASCII map. The game itself works fine, but the console screen(map) is flickering when I move my player and I don't know how to fix this. Any help appreaciated, thanks!
Code:
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
vector<string> map;
int playerX = 10;
int playerY = 10;
int oldPlayerX;
int oldPlayerY;
bool done = false;
void loadMap();
void printMap();
void setPosition(int y, int x);
void eventHandling();
int main()
{
loadMap();
map[playerY][playerX] = '@';
printMap();
while(!done){
eventHandling();
printMap();
}
exit(1);
return 0;
}
void eventHandling(){
char command;
command = _getch();
system("cls");
oldPlayerX = playerX;
oldPlayerY = playerY;
if(command == 'w'){
playerY--;
}else if(command == 'a'){
playerX--;
}else if(command == 'd'){
playerX++;
}else if(command == 's'){
playerY++;
}
if(map[playerY][playerX] == '#'){
playerX = oldPlayerX;
playerY = oldPlayerY;
}
setPosition(playerY,playerX);
}
void setPosition(int y, int x){
map[oldPlayerY][oldPlayerX] = '.';
map[y][x] = '@';
}
void printMap(){
for(int i = 0 ; i < map.size() ; i++){
cout << map[i] << endl;
}
}
void loadMap(){
ifstream file;
file.open("level.txt");
string line;
while(getline(file, line)){
map.push_back(line);
}
}