A Simple Car Racing game in C++ using console

Azfar Alam
7 min readMar 10, 2023

--

If you’re dealing with visuals, writing a game demands some solid programming skills as well as a strong grasp of a few APIs, such as OpenGL and DirectX. For C++ programmers, there are a few gaming engines available to make the process straightforward.

Overview on Necessary header files usage:

To write code for car racing game in c++ using console , firstly we should be familiar with this below list header files to get idea on this builded code performance features.

  1. <iostream> : It is the standard C++ library which provides input/output functionality of the program.
  2. <conio.h> : It is a C header file which provides console input output functions like getch(), getche(), clrscr(), etc.
  3. <dos.h> : It is a C header file which provides functions to interact with the DOS operating system.
  4. <windows.h> : It is a C header file which provides access to the Windows API for creating GUI applications.
  5. <time.h> : It is a C header file which provides functions to interact with the system clock and manipulate date and time.
  6. The <windows.h> header file is used to access the Win32 API methods, making it easier for the user to use the built-in functionality.

Win32 executable is used in the source code when built-in functions are included in the main file. Various libraries like <stdio.h> or <stdlib.h> are specifically included in the header file. These libraries enable modification, extension, and replacement of the items in libraries in addition to the capabilities of macros. The string functions that enable the inclusion of C library functions in the Windows kernel utilize UNICODE. This allows for the use of other languages in the source code, such as C++, C#, Visual Basic, and Java. The Win32 API also provides capabilities such as graphical user interfaces, networking, input/output, memory management, and file systems. It also provides access to various other systems and APIs, such as the Windows registry, ODBC, and COM.

Program code for our car racing game:

#include<iostream>  
#include<conio.h>
#include<dos.h>
#include <windows.h>
#include <time.h>

#define SCREEN_WIDTH 90
#define SCREEN_HEIGHT 26
#define WIN_WIDTH 70

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;

int enemyY[3];
int enemyX[3];
int enemyFlag[3];
char car[4][4] = { ' ','±','±',' ',
'±','±','±','±',
' ','±','±',' ',
'±','±','±','±' };

int carPos = WIN_WIDTH/2;
int score = 0;

void gotoxy(int x, int y){
CursorPosition.X = x;
CursorPosition.Y = y;
SetConsoleCursorPosition(console, CursorPosition);
}
void setcursor(bool visible, DWORD size) {
if(size == 0)
size = 20;

CONSOLE_CURSOR_INFO lpCursor;
lpCursor.bVisible = visible;
lpCursor.dwSize = size;
SetConsoleCursorInfo(console,&lpCursor);
}
void drawBorder(){
for(int i=0; i<SCREEN_HEIGHT; i++){
for(int j=0; j<17; j++){
gotoxy(0+j,i); cout<<"±";
gotoxy(WIN_WIDTH-j,i); cout<<"±";
}
}
for(int i=0; i<SCREEN_HEIGHT; i++){
gotoxy(SCREEN_WIDTH,i); cout<<"±";
}
}
void genEnemy(int ind){
enemyX[ind] = 17 + rand()%(33);
}
void drawEnemy(int ind){
if( enemyFlag[ind] == true ){
gotoxy(enemyX[ind], enemyY[ind]); cout<<"****";
gotoxy(enemyX[ind], enemyY[ind]+1); cout<<" ** ";
gotoxy(enemyX[ind], enemyY[ind]+2); cout<<"****";
gotoxy(enemyX[ind], enemyY[ind]+3); cout<<" ** ";
}
}
void eraseEnemy(int ind){
if( enemyFlag[ind] == true ){
gotoxy(enemyX[ind], enemyY[ind]); cout<<" ";
gotoxy(enemyX[ind], enemyY[ind]+1); cout<<" ";
gotoxy(enemyX[ind], enemyY[ind]+2); cout<<" ";
gotoxy(enemyX[ind], enemyY[ind]+3); cout<<" ";
}
}
void resetEnemy(int ind){
eraseEnemy(ind);
enemyY[ind] = 1;
genEnemy(ind);
}

void drawCar(){
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
gotoxy(j+carPos, i+22); cout<<car[i][j];
}
}
}
void eraseCar(){
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
gotoxy(j+carPos, i+22); cout<<" ";
}
}
}

int collision(){
if( enemyY[0]+4 >= 23 ){
if( enemyX[0] + 4 - carPos >= 0 && enemyX[0] + 4 - carPos < 9 ){
return 1;
}
}
return 0;
}
void gameover(){
system("cls");
cout<<endl;
cout<<"\t\t--------------------------"<<endl;
cout<<"\t\t-------- Game Over -------"<<endl;
cout<<"\t\t--------------------------"<<endl<<endl;
cout<<"\t\tPress any key to go back to menu.";
getch();
}
void updateScore(){
gotoxy(WIN_WIDTH + 7, 5);cout<<"Score: "<<score<<endl;
}

void instructions(){

system("cls");
cout<<"Instructions";
cout<<"\n----------------";
cout<<"\n Avoid Cars by moving left or right. ";
cout<<"\n\n Press 'a' to move left";
cout<<"\n Press 'd' to move right";
cout<<"\n Press 'escape' to exit";
cout<<"\n\nPress any key to go back to menu";
getch();
}

void play(){
carPos = -1 + WIN_WIDTH/2;
score = 0;
enemyFlag[0] = 1;
enemyFlag[1] = 0;
enemyY[0] = enemyY[1] = 1;

system("cls");
drawBorder();
updateScore();
genEnemy(0);
genEnemy(1);

gotoxy(WIN_WIDTH + 7, 2);cout<<"Car Game";
gotoxy(WIN_WIDTH + 6, 4);cout<<"----------";
gotoxy(WIN_WIDTH + 6, 6);cout<<"----------";
gotoxy(WIN_WIDTH + 7, 12);cout<<"Control ";
gotoxy(WIN_WIDTH + 7, 13);cout<<"-------- ";
gotoxy(WIN_WIDTH + 2, 14);cout<<" A Key - Left";
gotoxy(WIN_WIDTH + 2, 15);cout<<" D Key - Right";

gotoxy(18, 5);cout<<"Press any key to start";
getch();
gotoxy(18, 5);cout<<" ";

while(1){
if(kbhit()){
char ch = getch();
if( ch=='a' || ch=='A' ){
if( carPos > 18 )
carPos -= 4;
}
if( ch=='d' || ch=='D' ){
if( carPos < 50 )
carPos += 4;
}
if(ch==27){
break;
}
}

drawCar();
drawEnemy(0);
drawEnemy(1);
if( collision() == 1 ){
gameover();
return;
}
Sleep(50);
eraseCar();
eraseEnemy(0);
eraseEnemy(1);

if( enemyY[0] == 10 )
if( enemyFlag[1] == 0 )
enemyFlag[1] = 1;

if( enemyFlag[0] == 1 )
enemyY[0] += 1;

if( enemyFlag[1] == 1 )
enemyY[1] += 1;

if( enemyY[0] > SCREEN_HEIGHT-4 ){
resetEnemy(0);
score++;
updateScore();
}
if( enemyY[1] > SCREEN_HEIGHT-4 ){
resetEnemy(1);
score++;
updateScore();
}
}
}

int main()
{
setcursor(0,0);
srand( (unsigned)time(NULL));

do{
system("cls");
gotoxy(10,5); cout<<" -------------------------- ";
gotoxy(10,6); cout<<" | Car Game by AZFAR | ";
gotoxy(10,7); cout<<" --------------------------";
gotoxy(10,9); cout<<"1. Start Game";
gotoxy(10,10); cout<<"2. Instructions";
gotoxy(10,11); cout<<"3. Quit";
gotoxy(10,13); cout<<"Select option: ";
char op = getche();

if( op=='1') play();
else if( op=='2') instructions();
else if( op=='3') exit(0);

}while(1);

return 0;
}

Explaination of the game code:

  • The gotoxy() function is used to move the cursor to a specified location on the screen. The COORD data structure stores the x and y coordinates of the position to move the cursor to.
  • The GetStdHandle() function is used to retrieve the Standard Input, Standard Output and Standard Error Handles. The srand() function, which is part of the C++ STL, is used to initialise the random number generator by setting a seed value.
  • The rand() function can then be used to generate a stream of pseudo-random numbers.
  • The gotoxy() function is very useful for printing messages at specific locations on the screen, as it allows for precise control over the exact position of text.
  • The COORD structure is an important part of this, as it stores the x and y coordinates that are used to set the cursor position.
  • The GetStdHandle() function is used to retrieve the Standard Input, Standard Output and Standard Error Handles, which are used to control the flow of information.
  • The srand() and rand() functions are also important for generating random numbers, which can be used for a variety of different tasks.
  • All of these functions are essential for controlling the flow of information and providing precise control over the output of a program.

These are the Outputs of my Program:

  • Here we are creating a code which we easily playing a game name car game in this game we actually do left and right by tapping the key “a” and “d”. The code link is given below:
  • https://github.com/azfar-2/task-new/blob/main/carazfar.cpp
  • The tapping of above link you will give the whole code you’ll get a game named car game.
  • Now we are discussing the output of the code how’s it is work.
Fig 1: Output
  • This is the 1st page of output when you are compile and run the program then you shown the first page like this.
  • In this output you can see 1. Start 2. Instruction 3. Quit, It means that when we are tap the 1 from key then game has been start and if you want to known instruction of game then click on 2. As clicking 2 then it will shown like this as look as a following figure.
Fig 2: Output
  • This is the instructions of how to play the game which is created by code as you can see above it’s clear that the Press a to move the car left and Press d to move the car right and if you want to exit the game then click on the esc buttom to exit the game and if you known every instruction of game then click on any key to back and go on a main menu.
FIg 3: Output
  • This is the exit from the instruction and if you want to start the game then click on the 1 key.
Fig 4: Output
  • Now press any key to start the game.
Fig 5: Output
  • Whoa waao your game has been starting successfull now enjoy the game by tap the key “a” and “d” “a” goes to left and “d” goes to right.
  • If you fail in the game then it shown like this. as shown in the given figure.
Fig 6: Output
  • This is the last phase of output which you want to continue the score then press on any key to continue the game if you are boring from the game then press on 3 key to exit the game and goes on your Code which is write by you.

Thank you.. and enjoy your day by this game :)

Keep learning & keep sharing..

--

--

Azfar Alam

Technical Content Writer | DevOps Enthusiast | Exploring Modern Tools & Technologies under the domain -- AI/ML, Industry Use-cases, AWS Cloud, Python, etc.