0% found this document useful (0 votes)
17 views8 pages

C++ Console Car Game Code

This C++ program defines a car game with the following key elements: 1. It includes header files for input/output functions and sets screen dimensions. 2. It defines variables to track the car position, score, and enemy positions. 3. It includes functions to draw and erase the car, enemies, and borders and to detect collisions. 4. The main function displays a menu to start the game, view instructions, or quit. It calls the play function which runs the game loop moving and drawing the car and enemies until a collision occurs.

Uploaded by

Sameer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views8 pages

C++ Console Car Game Code

This C++ program defines a car game with the following key elements: 1. It includes header files for input/output functions and sets screen dimensions. 2. It defines variables to track the car position, score, and enemy positions. 3. It includes functions to draw and erase the car, enemies, and borders and to detect collisions. 4. The main function displays a menu to start the game, view instructions, or quit. It calls the play function which runs the game loop moving and drawing the car and enemies until a collision occurs.

Uploaded by

Sameer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#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;

[Link] = visible;

[Link] = 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 | “;

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;

Common questions

Powered by AI

The game manages enemies using arrays to store their X and Y coordinates, flags to control their activity status, and specific functions for drawing, erasing, and resetting their positions. Each enemy's Y-coordinate is incremented as part of the game loop to simulate movement. Once an enemy moves beyond the screen height minus 4, it is reset to its initial position (y = 1) and its X-coordinate is randomly re-generated to continue game continuity . This design allows for multiple enemies to appear, disappear, and reappear in different places on the screen, enhancing the challenge for the player.

The code is organized using separate functions for distinct tasks: drawing and erasing elements, handling input, managing game states, etc. This modularity enhances code readability by encapsulating logic within well-defined boundaries, making it easier for other developers or the same developer in the future to understand and modify specific parts without affecting the whole program. Maintenance is simplified as updates to gameplay components or logic can be isolated to relevant functions without risk of unintended side effects .

The collision detection logic checks the player's car position against the enemies' positions. Specifically, if the Y-coordinate of an enemy plus 4 is greater than or equal to 23 (which corresponds to the car's position on the console screen), and if the X-coordinate difference between the enemy and car (accounting for the horizontal offsets) is within the range of 0 to 9, then a collision is considered to occur, returning 1 from the "collision" function .

The "system(\"cls\")" command is used to clear the console screen, effectively resetting the visual output to a blank state. This is particularly useful when transitioning between different states of the game, such as moving from the main menu to the game screen or showing the "game over" message. Clearing the screen prevents overlap of text and graphical elements, ensuring that each game stage or message is presented cleanly and clearly .

The game increases the score each time an enemy is reset after moving off the screen. When an enemy's Y-coordinate exceeds the screen height minus 4, the "resetEnemy" function is called, which increments the score variable. The "updateScore" function then displays the updated score on the sidebar using "gotoxy" to position the text, thus providing real-time feedback to the player .

The "drawEnemy" function checks the "enemyFlag" array to determine whether an enemy should be drawn. If "enemyFlag[ind]" is true for a given index, the function will use the "gotoxy" function to position the console cursor and output the visual representation of the enemy on the console screen. This flag acts as a condition to control whether an enemy at that particular index is active and visible during the game loop .

Random number generation is used in the "genEnemy" function where it assigns random X-coordinates to enemies when they are spawned or reset. This random placement is crucial for gameplay as it ensures unpredictability in enemy appearance, preventing players from memorizing patterns and requiring them to continually adapt to various potential threats on the screen .

The 'gotoxy' function is used to position the cursor at specific coordinates on the console screen before writing text or characters. This allows for precise control over where game elements, such as the player's car or enemies, are drawn on the screen. As a result, it facilitates real-time movement and updating of game visuals, contributing to a more interactive and visually coherent gameplay experience .

The game captures user input using functions like "kbhit" and "getch", which detect if a key has been pressed and then return the key value. User input affects gameplay by allowing movement commands ('a' for left, 'd' for right) or breaking the game loop via the escape key. These inputs directly manipulate the car's position and enable real-time interaction with the game, influencing the player's ability to avoid obstacles and impacting the overall game experience .

Adjusting cursor visibility and size using the "setcursor" function enhances the player's visual experience by minimizing distractions. Setting the cursor to be invisible prevents the cursor's flickering or movement from interfering with the game's graphics displayed on the console, thereby maintaining a clean and immersive interface where only the relevant game elements are visible .

You might also like