Sunday 10 September 2017

SNAKE GAME SIMPLIFIED IN C++ [Easiest Way]


//SNAKE GAME CREATED BY MOHD MUJTABA
// Follow Me on Insta @mujtaba.aamir1
// Facebook @mujtaba.aamir1
#include<iostream>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
using namespace std;
bool gameover;
int x,y;
const int width=20,height=20;
 int score=0;
int fruitX,fruitY;
enum DIRECTION{STOP=0,UP,DOWN,LEFT,RIGHT};
DIRECTION dir;

void draw()
{
system("cls");
    int i=0;
for(i=0;i<width+2;i++)
cout<<"#";
cout<<endl;
for(int j=0;j<height;j++)
{
for(i=0;i<width+2;i++)
{
if(i==0)
cout<<"#";
if(i==x&&j==y)
cout<<"O";
else
if(fruitX==i&&fruitY==j)
cout<<"F";
else 
cout<<" ";

if(i==width-1)
cout<<"#";
if(x==fruitX&&y==fruitY)
        {
        score+=10;
    fruitX= rand()%width;
    fruitY= rand()% height;
        }  

}
cout<<endl;
}

for(int i=0;i<width+1;i++)
cout<<"#";
cout<<endl;
cout<<"SCORE="<<score;
}


void input()
{
if(_kbhit())  // _kbhit is to find Keyboard input
{
switch(_getch())
{
case 'a':
dir=LEFT;
break;
case 'd':
dir=RIGHT;
break;
case 's':
dir=DOWN;
break;
case 'w':
dir=UP;
break;
case 'x':
gameover=true;
default:
break;
}
}
}

void logic()
{
switch(dir)
{
case UP:
--y;
break;

case DOWN:
++y;
break;

case RIGHT:
++x;
break;

case LEFT:
--x;
break;

default:
break;
}
if(x>=width)
x=0;
else if(x<0)
x=width;
if(y>=height)
y=0;
else if(y<0)
y=height;

}
void start()
{
gameover=false;
x=width/2;
 y=height/2;
fruitX=rand()%width;
fruitY=rand()%height;
score=0;
}

main()
{

start();
while(!gameover)
{
Sleep(50); // This function is used to delay the output
draw();
input();
logic();
}
}//end of main()

No comments:

Post a Comment

Amazon1Ads