I am fairly new to C++ and programmed a maze game as an exercise. However, looking at it I can see it can be improved a lot. These are my requests if you don't mind:
- I do not want to use the library
<conio.h>
. - I want to use another method instead of
system("CLS")
. - This code is old; I think it has many unsafe codes in it and I cannot get used to C++11, C++17 etc. If you can help me update this game to the newer variants of C++, I would be more than happy.
- In
main
function I just want to use function calling, so anUpdate()
method would be nice. - OOP is highly appreciated.
- Please do not hesitate to use advanced C++ like Lambda Expressions, auto type declarations etc. (see number 3). I don't know them yet, but I will try to understand.
- Criticize like there is no tomorrow!
//maze game in console
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
// S: Start
// #: Wall
// .: Space
// F: Finish
// P: Player
const char maze[5][5]={{'#','S','#','#','#'},
{'#','.','.','#','#'},
{'#','#','.','#','#'},
{'#','.','.','.','#'},
{'#','#','#','F','#'}};
void Clear(){
system("CLS");//clear console
}
void InputHandle(int move, int &pX, int &pY){
switch(move=getch()){
case KEY_UP:
if( pY-1 >= 0 ){
if(maze[pY-1][pX] != '#'){//if it is not the limit or it is not the wall(#) move player
pY--;
}
}
break;
case KEY_DOWN:
if( pY+1 <= 4 ){
if(maze[pY+1][pX] != '#'){
pY++;
}
}
break;
case KEY_RIGHT:
if( pX+1 <= 4 ){
if(maze[pY][pX+1] != '#'){
pX++;
}
}
break;
case KEY_LEFT:
if( pX-1 >= 0 ){
if(maze[pY][pX-1] != '#'){
pX--;
}
}
}
}
void Display(int &pX, int &pY){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(j==pX && i==pY){//instead of the maze char, put player's 'P'
std::cout<<"P ";
continue;
}
std::cout<<maze[i][j]<<" ";
}
std::cout<<"\n";
}
}
bool CheckWinCondition(int &pX, int &pY){
if(pX==3 && pY ==4){
return true;
}
return false;
}
int main(){
//movement
int playerPosX=1;
int playerPosY=0;
int movement;
while(!CheckWinCondition(playerPosX,playerPosY)){//if player is not in the finish, loop
Display(playerPosX, playerPosY);//Show current maze
InputHandle(movement, playerPosX, playerPosY);//take input
Clear();//Clear the screen
}
std::cout<<"Congrats, you finished the maze!";
}