SIMPLE SNAkE GAME USING C++
Hello everyone welcome to mad4monkey. The place where future
billionaires comes together. In this we talk about how to create simple snake game using c++.
#include<iostream>
#include<conio.h>
using namespace std;
bool gameOver;
const int width = 40;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100] ,nTail;
enum direction{STOP=0,RIGHT,LEFT,UP,DOWN};
direction dir;
void setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
}
void draw()
{
system("cls");
for (int i = 0; i < width+2; i++)
cout << "-";
cout << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << "|";
if (i == y && j == x)
cout << "+";
else if (i == fruitY && j == fruitX)
cout << "Q";
else
{
bool print = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "0";
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width-1 )
cout << "|";
}
cout << endl;
}
for (int i = 0; i < width+2; i++)
cout << "-";
cout << endl;
cout << "score:"<<score;
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
dir = UP;
break;
case 'a':
dir = LEFT;
break;
case 's':
dir = DOWN;
break;
case 'd':
dir = RIGHT;
break;
}
}
}
void logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
tailX[0] = x;
tailY[0] = y;
int prev2X, prev2Y;
for (int i = 1; i < nTail; i++)
{
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;
}
if (x >= width) x = 0; else if (x < 0) x = width - 1;
if (y >= height) y = 0; else if (y < 0) y = height - 1;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY)
{
score = score + 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
setup();
while (!gameOver)
{
draw();
input();
logic();
}
system("cls");
cout <<endl<<endl<<endl<<endl<<"\t\t\t\t\t\CHANDU you lose :("<<endl;
cout << "\t\t\t\t\tyou scored:" << score;
return 0;
}
----*----
you can simply copy this code and then place in your code blocks software, visual studio 2019 or you can use your likely coding software.
NOTE;- If you are using 'turbo c++' .This code has to change its keywords or its simply shows a bunch of errors
So i suggest you to download code blocks or visual studio2019
for better experience.
--*--
CONTROLS;- 'W' is for UP.
'A' is for LEFT.
'S' is for DOWN.
'D' is for RIGHT.
(you can also change controls if you know coding)
---*---
If you have any doubt place leave me a comment

| Home | About us | Contact us |
| |
|
