SlideShare a Scribd company logo
// A simple snake game project(program) :)
#include<iostream>
usingnamespace std;
#include <stdlib.h> //usedfor rand()
#include<conio.h> // usedforgetch() andkbhit()
#include<windows.h> // usedfor sleep()
#include<iomanip>
bool gameover; // can alsouse flagvariable
const intheight=20 ;
const intwidth=20 ;
intx,y,fruitx,fruity,score ;
inttailx[100],taily[100] ;
inttail,tough=0;
enumdirection{ //can alsouse glabal constint variables
STOP=0, LEFT,RIGHT,UP,DOWN //of name STOP,LEFT,RIGHT,UP,DOWN having
}; //values0,1,2,3,4 respectivally
directiondir;
voidsetup() // inicialisethe inicial values,runonlyonce
{
gameover=false ;
dir=UP ; // defaultmovemebnt of snake
x=width/2; //x and y are coordinatsof defaultsnake head
y=height/2; // position
fruitx=rand()%width; //coordinatesof defaultrandamfruitposition
fruity=rand()%height;
score=0 ;
tail=0 ;
}
void draw()
{
system("cls"); //usedtoclearthe previousscreen,sothat
inti,j,k; //eachtime whendraw() runsthe positionof
for(i=0;i<width+1;i++) //the box remainsthe same .
cout<<"#" ; // printsupperboundary
cout<<endl ;
for(i=0;i<height;i++)
{
for(j=0;j<width;j++)
{
if(j==0||j==width-1) // printsside boundary
cout<<"#" ;
if(i==y&&j==x) //snake head
cout<<"O" ;
else if(i==fruity&&j==fruitx) // fruit
cout<<"*" ;
else
{
bool print=false ; //can alsouse intflagvariable
for(k=0;k<tail;k++)
{
if(tailx[k]==j&&taily[k]==i) //printingof tail of snake
{
cout<<"o" ;
print=true ;
}
}
if(!print)
cout<<" " ;
}
}
cout<<endl ;
}
for(i=0;i<width+1;i++) //lowerboundary
cout<<"#" ;
cout<<endl ;
cout<<" YOUR SCORE = "<<score<<endl ;
}
voidinput()
{
char ch ;
if(!kbhit()) // keyboardhitf(),returns1whenwe hitthe
{ //keyboardelse returns0
switch(ch)
{
case 'w' : dir=UP ;
break;
case 'a' : dir=LEFT ;
break;
case 's' : dir=DOWN ;
break;
case 'd' : dir=RIGHT ;
break;
case 'x' : gameover=true ;
break;
}
}
else // else part for defaultmovementof
{ // the snake inthe same directiontill
switch(getch()) // userdon'tinputsany movement
{
case 'w' : dir=UP ;
ch='w' ;
break;
case 'a' : dir=LEFT ;
ch='a' ;
break;
case 's' : dir=DOWN ;
ch='s' ;
break;
case 'd' : dir=RIGHT ;
ch='d' ;
break;
case 'x' : gameover=true ;
break;
}
}
}
voidlogic()
{
intprevx,prevy,prev2x,prev2y,i ; //line 120-136 for the tail
prevx=tailx[0] ;
prevy=taily[0] ;
tailx[0]=x ;
taily[0]=y;
for(i=1;i<tail;i++) //SWAPPINGof valuesof array
{
prev2x=tailx[i] ;
prev2y=taily[i] ;
tailx[i]=prevx ;
taily[i]=prevy;
prevx=prev2x ;
prevy=prev2y;
}
switch(dir)
{
case UP : y-- ;
break;
case DOWN : y++ ;
break;
case LEFT : x-- ;
break;
case RIGHT : x++ ;
break;
default:break;
}
for(i=0;i<tail;i++) // if snake hitsitsowntail it will
{ // die
if(tailx[i]==x&&taily[i]==y)
{
gameover=true ;
system("cls");
cout<<"n GAME OVER: you hit/bite yourtail";
}
}
if(tough==1)
{
if(x<0||x>width||y<0||y>height) // if the snake hitthe wall it
{ // will die
gameover=true ;
system("cls");
cout<<"n GAME OVER: you hitthe wall " ;
}
}
else
{
if(x<0) // if snake hitthe wall itwill continue
x=width-1; //from same positiononthe opposite
else if(x>width-2) // wall
x=0 ;
if(y<0)
y=height-1;
else if(y>height)
y=0 ;
}
if(x==fruitx&&y==fruity) //if snake ate the fruitscore
{ //shouldincrease andnew fruit
score+=10 ; // positionshouldbe atomatically
fruitx=rand()%width; // genereted onthe screen
fruity=rand()%height;
tail++ ; // lengthof tail increases
}
}
intmain()
{
intn,choice ;
cout<<"nnn...................KEYBOARDINSTRUCTIONS................................";
cout<<endl<<endl<<setw(30)<<"KEYBOARDKEYS"<<setw(30)<<"OPERATION";
cout<<"n-----------------------------------------------------------------------";
cout<<endl<<setw(25)<<"w"<<setw(40)<<"uppwardmovement";
cout<<endl<<setw(25)<<"s"<<setw(40)<<"downwardmovement";
cout<<endl<<setw(25)<<"a"<<setw(40)<<"leftmovement";
cout<<endl<<setw(25)<<"d"<<setw(40)<<"rightmovement";
cout<<endl<<setw(25)<<"x"<<setw(40)<<"quite/exitgame";
cout<<"n-----------------------------------------------------------------------";
cout<<"nnn # all keysshouldbe inlowercase onlyn ( as game workson ASCIIvalues)";
cout<<"nnnenterlevelof game youwanto play" ;
cout<<"n 1. EASY n 2. MEDIAM n 3. HARD " ;
cout<<"n 4. ULTRA TOUGH (if youevenhitthe wall youwill die )";
cout<<"nnplease enterchoice ";
cin>>choice ;
if(choice==1)
n=100 ;
else if(choice==2)
n=50 ;
else if(choice==3)
n=10 ;
else
{
tough=1 ;
n=70 ;
}
system("cls");
setup() ;
while(!gameover) //can alsouse while(flag) we onlyneedtorunthe
{ // loopinfinitrnoof times
draw() ;
input() ;
logic() ;
Sleep(n); // f() todelaythe outputscreeneachtime it
} // getexecutedfornmilli-secondes
cout<<"nn...................................................................";
cout<<"n YOUR FINALSCORE= "<<score ;
cout<<"n...................................................................";
getch() ;
getch() ;
return0 ;
}
A simple snake game project
A simple snake game project

More Related Content

What's hot

Flappy bird game in c#
Flappy bird game in c#Flappy bird game in c#
Flappy bird game in c#
Comstas
 
Tic Tac Toe ppt
Tic Tac Toe pptTic Tac Toe ppt
Tic Tac Toe ppt
SanchitRastogi15
 
Android application - Tic Tac Toe
Android application - Tic Tac ToeAndroid application - Tic Tac Toe
Android application - Tic Tac Toe
Sarthak Srivastava
 
Introduction to flutter
Introduction to flutter Introduction to flutter
Introduction to flutter
Wan Muzaffar Wan Hashim
 
Computer Graphics Practical
Computer Graphics PracticalComputer Graphics Practical
Computer Graphics Practical
Neha Sharma
 
Snake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malavSnake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malav
Rohit malav
 
5 pen-pc-technology complete ppt
5 pen-pc-technology complete ppt5 pen-pc-technology complete ppt
5 pen-pc-technology complete ppt
atinav242
 
Python GUI Programming
Python GUI ProgrammingPython GUI Programming
Python GUI Programming
RTS Tech
 
Intro to Flutter SDK
Intro to Flutter SDKIntro to Flutter SDK
Intro to Flutter SDK
digitaljoni
 
Tic tac toe c++ project presentation
Tic tac toe c++ project presentationTic tac toe c++ project presentation
Tic tac toe c++ project presentation
Saad Symbian
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORT
vineet raj
 
game project presentation
game project presentationgame project presentation
game project presentation
Kavi Kumar
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
FalgunSorathiya
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
Prabindh Sundareson
 
Snake Game in Python Progress report
Snake Game in Python Progress reportSnake Game in Python Progress report
Snake Game in Python Progress report
Muhammad Aziz
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
Vladimir Parfenov
 
Game Architecture and Programming
Game Architecture and ProgrammingGame Architecture and Programming
Game Architecture and Programming
Sumit Jain
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptx
DSCVSSUT
 
UNIT CONVERTER APP
UNIT CONVERTER APPUNIT CONVERTER APP
UNIT CONVERTER APP
Krishnakumar Ramachandran
 
Game Development Company, Flash Game Development,
Game Development Company, Flash Game Development,Game Development Company, Flash Game Development,
Game Development Company, Flash Game Development,
Gateway Technolabs
 

What's hot (20)

Flappy bird game in c#
Flappy bird game in c#Flappy bird game in c#
Flappy bird game in c#
 
Tic Tac Toe ppt
Tic Tac Toe pptTic Tac Toe ppt
Tic Tac Toe ppt
 
Android application - Tic Tac Toe
Android application - Tic Tac ToeAndroid application - Tic Tac Toe
Android application - Tic Tac Toe
 
Introduction to flutter
Introduction to flutter Introduction to flutter
Introduction to flutter
 
Computer Graphics Practical
Computer Graphics PracticalComputer Graphics Practical
Computer Graphics Practical
 
Snake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malavSnake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malav
 
5 pen-pc-technology complete ppt
5 pen-pc-technology complete ppt5 pen-pc-technology complete ppt
5 pen-pc-technology complete ppt
 
Python GUI Programming
Python GUI ProgrammingPython GUI Programming
Python GUI Programming
 
Intro to Flutter SDK
Intro to Flutter SDKIntro to Flutter SDK
Intro to Flutter SDK
 
Tic tac toe c++ project presentation
Tic tac toe c++ project presentationTic tac toe c++ project presentation
Tic tac toe c++ project presentation
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORT
 
game project presentation
game project presentationgame project presentation
game project presentation
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
 
Snake Game in Python Progress report
Snake Game in Python Progress reportSnake Game in Python Progress report
Snake Game in Python Progress report
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
Game Architecture and Programming
Game Architecture and ProgrammingGame Architecture and Programming
Game Architecture and Programming
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptx
 
UNIT CONVERTER APP
UNIT CONVERTER APPUNIT CONVERTER APP
UNIT CONVERTER APP
 
Game Development Company, Flash Game Development,
Game Development Company, Flash Game Development,Game Development Company, Flash Game Development,
Game Development Company, Flash Game Development,
 

Similar to A simple snake game project

Ping pong game
Ping pong  gamePing pong  game
Ping pong game
Amit Kumar
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
fazilfootsteps
 
Ssaw08 0624
Ssaw08 0624Ssaw08 0624
Ssaw08 0624
Atsushi Tadokoro
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노
Chiwon Song
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Ryan McGeary
 
The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)
Aaron Gustafson
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
monikagupta18jan
 
Include
IncludeInclude
Please recreate a simple game of flappy birds using two classes and .pdf
Please recreate a simple game of flappy birds using two classes and .pdfPlease recreate a simple game of flappy birds using two classes and .pdf
Please recreate a simple game of flappy birds using two classes and .pdf
meerobertsonheyde608
 
send edited codeMain 2public class Main2 {   public static voi.pdf
send edited codeMain 2public class Main2 {   public static voi.pdfsend edited codeMain 2public class Main2 {   public static voi.pdf
send edited codeMain 2public class Main2 {   public static voi.pdf
suhshbhosale
 
Потоки в перле изнутри
Потоки в перле изнутриПотоки в перле изнутри
Потоки в перле изнутри
Ilya Zelenchuk
 
Jamming attack in wireless network
Jamming attack in wireless networkJamming attack in wireless network
Jamming attack in wireless network
Thesis Scientist Private Limited
 
Aodv routing protocol code in ns2
Aodv routing protocol code in ns2Aodv routing protocol code in ns2
Aodv routing protocol code in ns2
Prof Ansari
 
Snake report ROHIT MALAV
Snake report ROHIT MALAVSnake report ROHIT MALAV
Snake report ROHIT MALAV
Rohit malav
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays
 
[EN] Ada Lovelace Day 2014 - Tampon run
[EN] Ada Lovelace Day 2014  - Tampon run[EN] Ada Lovelace Day 2014  - Tampon run
[EN] Ada Lovelace Day 2014 - Tampon run
Maja Kraljič
 
JavaScript @ CTK
JavaScript @ CTKJavaScript @ CTK
JavaScript @ CTK
Jakob Mattsson
 
[SI] Ada Lovelace Day 2014 - Tampon Run
[SI] Ada Lovelace Day 2014  - Tampon Run[SI] Ada Lovelace Day 2014  - Tampon Run
[SI] Ada Lovelace Day 2014 - Tampon Run
Maja Kraljič
 
#includeiostream #includetime.h #includecstdio #include.pdf
#includeiostream #includetime.h #includecstdio #include.pdf#includeiostream #includetime.h #includecstdio #include.pdf
#includeiostream #includetime.h #includecstdio #include.pdf
ARORACOCKERY2111
 
Arduino
ArduinoArduino

Similar to A simple snake game project (20)

Ping pong game
Ping pong  gamePing pong  game
Ping pong game
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
 
Ssaw08 0624
Ssaw08 0624Ssaw08 0624
Ssaw08 0624
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Include
IncludeInclude
Include
 
Please recreate a simple game of flappy birds using two classes and .pdf
Please recreate a simple game of flappy birds using two classes and .pdfPlease recreate a simple game of flappy birds using two classes and .pdf
Please recreate a simple game of flappy birds using two classes and .pdf
 
send edited codeMain 2public class Main2 {   public static voi.pdf
send edited codeMain 2public class Main2 {   public static voi.pdfsend edited codeMain 2public class Main2 {   public static voi.pdf
send edited codeMain 2public class Main2 {   public static voi.pdf
 
Потоки в перле изнутри
Потоки в перле изнутриПотоки в перле изнутри
Потоки в перле изнутри
 
Jamming attack in wireless network
Jamming attack in wireless networkJamming attack in wireless network
Jamming attack in wireless network
 
Aodv routing protocol code in ns2
Aodv routing protocol code in ns2Aodv routing protocol code in ns2
Aodv routing protocol code in ns2
 
Snake report ROHIT MALAV
Snake report ROHIT MALAVSnake report ROHIT MALAV
Snake report ROHIT MALAV
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 
[EN] Ada Lovelace Day 2014 - Tampon run
[EN] Ada Lovelace Day 2014  - Tampon run[EN] Ada Lovelace Day 2014  - Tampon run
[EN] Ada Lovelace Day 2014 - Tampon run
 
JavaScript @ CTK
JavaScript @ CTKJavaScript @ CTK
JavaScript @ CTK
 
[SI] Ada Lovelace Day 2014 - Tampon Run
[SI] Ada Lovelace Day 2014  - Tampon Run[SI] Ada Lovelace Day 2014  - Tampon Run
[SI] Ada Lovelace Day 2014 - Tampon Run
 
#includeiostream #includetime.h #includecstdio #include.pdf
#includeiostream #includetime.h #includecstdio #include.pdf#includeiostream #includetime.h #includecstdio #include.pdf
#includeiostream #includetime.h #includecstdio #include.pdf
 
Arduino
ArduinoArduino
Arduino
 

Recently uploaded

Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Transcat
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
Kamal Acharya
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Balvir Singh
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
ijseajournal
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
uqyfuc
 
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
GiselleginaGloria
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
Indrajeet sahu
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
Pallavi Sharma
 
FULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back EndFULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back End
PreethaV16
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
OKORIE1
 
SMT process how to making and defects finding
SMT process how to making and defects findingSMT process how to making and defects finding
SMT process how to making and defects finding
rameshqapcba
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
wafawafa52
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
drshikhapandey2022
 
Flow Through Pipe: the analysis of fluid flow within pipes
Flow Through Pipe:  the analysis of fluid flow within pipesFlow Through Pipe:  the analysis of fluid flow within pipes
Flow Through Pipe: the analysis of fluid flow within pipes
Indrajeet sahu
 
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
IJCNCJournal
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
Advancements in Automobile Engineering for Sustainable Development.pdf
Advancements in Automobile Engineering for Sustainable Development.pdfAdvancements in Automobile Engineering for Sustainable Development.pdf
Advancements in Automobile Engineering for Sustainable Development.pdf
JaveedKhan59
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
DharmaBanothu
 

Recently uploaded (20)

Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
 
FULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back EndFULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back End
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
 
SMT process how to making and defects finding
SMT process how to making and defects findingSMT process how to making and defects finding
SMT process how to making and defects finding
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
 
Flow Through Pipe: the analysis of fluid flow within pipes
Flow Through Pipe:  the analysis of fluid flow within pipesFlow Through Pipe:  the analysis of fluid flow within pipes
Flow Through Pipe: the analysis of fluid flow within pipes
 
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
Advancements in Automobile Engineering for Sustainable Development.pdf
Advancements in Automobile Engineering for Sustainable Development.pdfAdvancements in Automobile Engineering for Sustainable Development.pdf
Advancements in Automobile Engineering for Sustainable Development.pdf
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...
 

A simple snake game project

  • 1. // A simple snake game project(program) :) #include<iostream> usingnamespace std; #include <stdlib.h> //usedfor rand() #include<conio.h> // usedforgetch() andkbhit() #include<windows.h> // usedfor sleep() #include<iomanip> bool gameover; // can alsouse flagvariable const intheight=20 ; const intwidth=20 ; intx,y,fruitx,fruity,score ; inttailx[100],taily[100] ; inttail,tough=0; enumdirection{ //can alsouse glabal constint variables STOP=0, LEFT,RIGHT,UP,DOWN //of name STOP,LEFT,RIGHT,UP,DOWN having }; //values0,1,2,3,4 respectivally directiondir; voidsetup() // inicialisethe inicial values,runonlyonce { gameover=false ; dir=UP ; // defaultmovemebnt of snake x=width/2; //x and y are coordinatsof defaultsnake head
  • 2. y=height/2; // position fruitx=rand()%width; //coordinatesof defaultrandamfruitposition fruity=rand()%height; score=0 ; tail=0 ; } void draw() { system("cls"); //usedtoclearthe previousscreen,sothat inti,j,k; //eachtime whendraw() runsthe positionof for(i=0;i<width+1;i++) //the box remainsthe same . cout<<"#" ; // printsupperboundary cout<<endl ; for(i=0;i<height;i++) { for(j=0;j<width;j++) { if(j==0||j==width-1) // printsside boundary cout<<"#" ; if(i==y&&j==x) //snake head cout<<"O" ; else if(i==fruity&&j==fruitx) // fruit cout<<"*" ; else {
  • 3. bool print=false ; //can alsouse intflagvariable for(k=0;k<tail;k++) { if(tailx[k]==j&&taily[k]==i) //printingof tail of snake { cout<<"o" ; print=true ; } } if(!print) cout<<" " ; } } cout<<endl ; } for(i=0;i<width+1;i++) //lowerboundary cout<<"#" ; cout<<endl ; cout<<" YOUR SCORE = "<<score<<endl ; } voidinput() { char ch ; if(!kbhit()) // keyboardhitf(),returns1whenwe hitthe { //keyboardelse returns0 switch(ch)
  • 4. { case 'w' : dir=UP ; break; case 'a' : dir=LEFT ; break; case 's' : dir=DOWN ; break; case 'd' : dir=RIGHT ; break; case 'x' : gameover=true ; break; } } else // else part for defaultmovementof { // the snake inthe same directiontill switch(getch()) // userdon'tinputsany movement { case 'w' : dir=UP ; ch='w' ; break; case 'a' : dir=LEFT ; ch='a' ; break; case 's' : dir=DOWN ; ch='s' ; break; case 'd' : dir=RIGHT ; ch='d' ;
  • 5. break; case 'x' : gameover=true ; break; } } } voidlogic() { intprevx,prevy,prev2x,prev2y,i ; //line 120-136 for the tail prevx=tailx[0] ; prevy=taily[0] ; tailx[0]=x ; taily[0]=y; for(i=1;i<tail;i++) //SWAPPINGof valuesof array { prev2x=tailx[i] ; prev2y=taily[i] ; tailx[i]=prevx ; taily[i]=prevy; prevx=prev2x ; prevy=prev2y; } switch(dir)
  • 6. { case UP : y-- ; break; case DOWN : y++ ; break; case LEFT : x-- ; break; case RIGHT : x++ ; break; default:break; } for(i=0;i<tail;i++) // if snake hitsitsowntail it will { // die if(tailx[i]==x&&taily[i]==y) { gameover=true ; system("cls"); cout<<"n GAME OVER: you hit/bite yourtail"; } } if(tough==1) { if(x<0||x>width||y<0||y>height) // if the snake hitthe wall it { // will die gameover=true ; system("cls");
  • 7. cout<<"n GAME OVER: you hitthe wall " ; } } else { if(x<0) // if snake hitthe wall itwill continue x=width-1; //from same positiononthe opposite else if(x>width-2) // wall x=0 ; if(y<0) y=height-1; else if(y>height) y=0 ; } if(x==fruitx&&y==fruity) //if snake ate the fruitscore { //shouldincrease andnew fruit score+=10 ; // positionshouldbe atomatically fruitx=rand()%width; // genereted onthe screen fruity=rand()%height; tail++ ; // lengthof tail increases } } intmain() { intn,choice ;
  • 8. cout<<"nnn...................KEYBOARDINSTRUCTIONS................................"; cout<<endl<<endl<<setw(30)<<"KEYBOARDKEYS"<<setw(30)<<"OPERATION"; cout<<"n-----------------------------------------------------------------------"; cout<<endl<<setw(25)<<"w"<<setw(40)<<"uppwardmovement"; cout<<endl<<setw(25)<<"s"<<setw(40)<<"downwardmovement"; cout<<endl<<setw(25)<<"a"<<setw(40)<<"leftmovement"; cout<<endl<<setw(25)<<"d"<<setw(40)<<"rightmovement"; cout<<endl<<setw(25)<<"x"<<setw(40)<<"quite/exitgame"; cout<<"n-----------------------------------------------------------------------"; cout<<"nnn # all keysshouldbe inlowercase onlyn ( as game workson ASCIIvalues)"; cout<<"nnnenterlevelof game youwanto play" ; cout<<"n 1. EASY n 2. MEDIAM n 3. HARD " ; cout<<"n 4. ULTRA TOUGH (if youevenhitthe wall youwill die )"; cout<<"nnplease enterchoice "; cin>>choice ; if(choice==1) n=100 ; else if(choice==2) n=50 ; else if(choice==3) n=10 ; else { tough=1 ; n=70 ;
  • 9. } system("cls"); setup() ; while(!gameover) //can alsouse while(flag) we onlyneedtorunthe { // loopinfinitrnoof times draw() ; input() ; logic() ; Sleep(n); // f() todelaythe outputscreeneachtime it } // getexecutedfornmilli-secondes cout<<"nn..................................................................."; cout<<"n YOUR FINALSCORE= "<<score ; cout<<"n..................................................................."; getch() ; getch() ; return0 ; }