You are on page 1of 11

C++ Snake Game (Simple!

)
By Circuitalist in CircuitsSoftware

298.904

16
Open Menu
16
Save PDF
Favorite
circuits
workshop
Introduction:
craft C++ Snake Game (Simple!)
cooking
living
outside
Log InSignup

Search

By CircuitalistVisit my youtube Channel: Follow More


More by the author:

the snake game is a very popular one, here is a very simple one written in C++ using Visual
Studio

the code is only 150 line and can be modified in several ways

Enjoy!

////////////////////////////////////////////////////

You want to support my videos?

You can browse and buy materials from my Amazon Store with the same price. This way I
get a small commission:
C++ How to Program (10th Edition)

Beginning C++ Through Game Programming

Starting out with Visual C# (4th Edition)

////////////////////////////////////////////////////

Step 1: Watch on Youtube...

Following

Step 2: Coding...

#include < iostream >

#include < conio.h >

using namespace std;

bool gameover;
const int width = 20;

const int height = 17;

int x, y, fruitX, fruitY, score;

int tailX[100], tailY[100]; //snake coordinates

int nTail;

enum eDirecton {STOP = 0, LEFT,RIGHT, UP, DOWN}; // Controls

eDirecton dir;

void Setup() {
gameover = false;

dir = STOP;

x = width / 2;

y = height / 2;

fruitX = rand() % width; //display fruit in a random place

fruitY = rand() % height; score = 0;

void Draw() {
system("cls");

for(int i = 0; i < width+2; i++)

cout << "#";

cout << endl ;

Projects
for (int i = 0; i < height ; i++) {
back
for (int j = 0;
Allj Projects
< width; j++) {
Circuits
if (j == 0) back
All
cout << "#"; //walls Apple
if (i == y && j ==Arduino
x)
Art
cout << "*"; // snakeAssistive
tale Tech
Audio
else if (i == fruitY Cameras
&& j == fruitX )
Clocks
cout << "%"; // change it to change the fruit
Computers
Electronics
else { Gadgets
Lasers
bool print = false; LEDs
Linux
for (int k = 0; k< nTail ; k++) {
Microcontrollers
if (tailX [k] == j &&
Microsoft
tailY [k] == i) {
Mobile
cout << "*"; printRaspberry
= true; Pi
Remote Control
} Reuse
Robots
}
Sensors
if (!print) cout <<Software
" ";
Soldering
} Speakers
Tools
if (j == width -1)USB
Wearables
cout << "#"; Websites
Wireless
}
Workshop
cout << endl; back
All
} 3D Design
3D Printing
for (int i = 0; i< width+2;
Cars i++)
CNC
cout << "#"; Electric Vehicles
cout << endl; Energy
Furniture
cout << "Score:" Home Improvement
<< score << endl ;
Home Theater
} Hydroponics
Knives
void Input () Laser Cutting
{ Lighting
Metalworking
if (_kbhit ()) { Molds & Casting
Motorcycles
switch (_getch ()) {
Organizing
Pallets
case 'a':
Repair
dir = LEFT; Science
Shelves
break; Solar
Tools
case 'd': Woodworking
Workbenches
dir = RIGHT;

break;

case 'w':
Craft
dir = UP; back
All
break; Art
Books & Journals
case 's':
Cardboard
Cards
dir = DOWN ; Clay
Costumes & Cosplay
break; Digital Graphics
Duct Tape
case 'x': Embroidery
Fashion
gameover = true;
Felt
break; Fiber Arts
Gift Wrapping
} Jewelry
Knitting & Crochet
} Leather
Mason Jars
} No-Sew
Paper
void algorithm()Parties & Weddings
{ Photography
Printmaking
int prevX = tailXReuse
[0];

int prevY = tailYSewing


[0];
Soapmaking
Wallets
int prev2X, prev2Y;

tailX[0] = x;

tailY[0] = y;
Cooking
back; i++) {
for(int i = 1;i < nTail
All
prev2X = tailX[i]; Bacon
BBQ & Grilling
prev2Y = tailY[i];Beverages
Bread
tailX[i] = prevX; Breakfast
Cake
tailY[i] = prevY; Candy
Canning & Preserving
prevX = prev2X;
Cocktails & Mocktails
prevY = prev2Y Coffee
;
Cookies
} Cupcakes
Dessert
switch (dir) { Homebrew
Main Course
case LEFT: Pasta
Pie
x--; Pizza
Salad
break; Sandwiches
case RIGHT: Snacks & Appetizers
Soups & Stews
x++; Vegetarian & Vegan

break;
case UP:

y--;
Living
break; back
All
case DOWN: Beauty
Christmas
y++;
Cleaning
break; Decorating
Education
default: Gardening
Halloween
break; Health
Hiding Places
} Holidays
Homesteading
if (x >= width) xKids
=0;else if (x <0) x = width -1;
Kitchen
if (y >= height) y = 0; else if (y < 0) y = height - 1;
LEGO & K'NEX
Life Hacks
for (int i =0; i< nTail ;i++)
Music
Office
if (tailX[i] == x && Supply
tailY[i] == y)Hacks
gameover = true; Organizing
Pest Control
if (x == fruitX && Pets
y == fruitY) {
Pranks, Tricks, & Humor
score +=10; Relationships
Toys & Games
fruitX = rand() % width;
Travel
Video Games
fruitY = rand() % height;

nTail ++;

}
Outside
} back
int main() All
Backyard
{
Beach
Setup(); Bikes
Birding
Boats
while (!gameover) {
Camping
Draw (); Climbing
Fire
Input (); Fishing
Hunting
algorithm (); Kites
Knots
}
Launchers
return 0; Paracord
Rockets
} Siege Engines
Skateboarding
Snow 2 People Made This Project!
Sports
Survival
Water

Teachers
back
All
bt707069 made it! Sammy_7 made it!
ELA
Math
Micro:bit
Science
Did you make this project? Share it with us!
Social Studies
Engineering
MakeyMakey
Coding I Made It
Electronics
Robotics
Arduino
CNC
RecommendationsLaser Cutting
3D Printing
3D Design
KINETIC COASTERS With a TWIST! Laser or 3D Printable by DIY Machines
Art
Music
Raspberry Pi NAS by Frank Bernhardt
Theatre
Wood Shop
DIY E-Kayak Part 2: Oar Controller by BradenSunwold
Metal Shop
Resources
Lab Bench Power Supply by Giovanni Aggiustatutto
Grades K-2
Grades 3-5
All Things Pi Contest
Grades 6-8
Grades 9-12
University+

For the Home Contest

Made with AI - Autodesk Design & Make - Student Contest


Comment I Made It

We have a be nice policy. Please be positive and constructive.

16 Comments

soulabdullah2 3 months ago

[Error] 'rand' was not declared in this scope

Reply

tedrosenega33 a year ago


Contests
Teachers
it says fruitX,rand(),system was not declared
how can i fix this?

Reply

fadikk 3 years ago

it says conio.h file is not found


Reply

1 reply

2020elearningwitheveryone 4 years ago

How do we run the program

Reply

1 reply

Cindy Odera 2 years ago

The code is not running , would have been easier if you posted the IDE you used ,
otherwise if anyone managed to get it to run please do tell

Reply

aziz_ure 3 years ago

Value of ntail here

Reply

muhammadaliasifdarvesh 3 years ago

if (_kbhit ()) {

switch (_getch ()) {


problem coming in this
saying Use of undeclared identifier '_kbhit'
saying Use of undeclared identifier '_getch'

Reply

umangaw2 3 years ago

Which ide you used I have vscode but not like you

Reply

chiragjangra05 4 years ago

Everything works fine except you have to change


#include < iostream >
#include < conio.h >

you have to remove the spaces between the <>. So, it should be:
#include <iostream>
#include <conio.h>

Reply

Dhiman Kalita 4 years ago

What is _kbhit,_getch...you probabely forgot to declare it ...my computer show error.

Reply

2 replies
jacobramos122 4 years ago

Everything works fine and is easily modifiable.

Reply

asadb5064 4 years ago

its not run

Reply

Post a comment

AboutContact

Sitemap | TOS | Privacy Statement | Privacy settings | Legal


© 2024

I Made It Favorite View Comments Share More Options


Facebook Twitter Pinterest Google Classroom
Flag

Wrong Category
Inappropriate
Incomplete
Spam

Are you sure you want to flag this instructable as ?

Cancel Confirm

Edit

You might also like