×

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left, right, up, and down; after consuming the food, the snake's length increases. Snake food will be generated at a predetermined interval.

With the help of C++ and graphics functions, I'll make a snake game. The concept of C++ classes and computer graphics functions will be applied to this.

Computer Graphics

Information displayed on drawings, graphs, photographs, and visual symbols or on a typewriter called computer graphics.

C++ Graphics Primitives

A graphics primitive is a non-divisible graphical element used in a computer graphics system for input or output. To render and create any images on the screen, we'll need a header file called < graphics.h >. It can also be defined as the way a computer visualizes and manipulates data. All animation and multimedia work best in a photo studio, without having to draw figures of various shapes.

In the snake game, the following activities are used to create graphics:

  • The initgraph () function is used to initialize the graphics function.
  • Syntax: void Intergraph(int *graph driver, int *graph mode, char *path);
  • The graphics driver is represented by gd.
  • The graphics mode is represented by gm.
  • path: This indicates the location of the graphic file.
  • closegraph(): It's used to turn off the graphics feature.
  • Syntax: void closegraph ();
  • Outputting text: The functions outtext () and outtextxy in C graphics can be used to output text().
  • outtext(): It's used to show the current location of the text.
  • Syntax: void outtext (char *str);
  • outtexttxy(): It's used to show text in a certain location.
  • Syntax: void outtextxy (int x, int y, char *str);

Example of a code showing snake game in C++:

#include<iostream.h>  
#include<conio.h>  
#include<graphics.h>  
#include<dos.h>  
#include<stdlib.h>  
#include<stdio.h>  
#include<time.h>  
#include<string.h>  
class Snake  
{  
 int p1,p2,v1,v2,v3, e1, e2,prev,now,n,colr,dsp,cnt,dly,m;  
 int stp, egGen;  
 int xr, yr;  
 void caught();  
 public:  
  long scr;  
 int strtX,strtY,endX,endY;  
 int pos[100][2];  
 void show();  
 void init();  
 void egg();  
 void transpose();  
 void gnrtCond();  
 void gnrtUnCond();  
 void check();  
 void checkegg();  
 void move();  
 void chngDir();  
 void sndet();  
 void sndCgt();  
 int test();  
 void score();  
 Snake();  
 Snake(Snake*);  
 ~Snake();  
 };  
Snake::Snake()  
 {  
 }  
Snake::~Snake()  
{  
}  
void Snake::checkegg()  
{  
 if((e1 == p1) && (e2 == p2))  
 { sndet();  
  egg();  
  dly--;  
  score();  
  n++;  
  }  
}  
void Snake::sndet()  
{ nosound();  
 sound(2500);  
 delay(2);  
 nosound();  
}  
void Snake::sndCgt()  
{ nosound();  
 for(int x=1000;x>0;x--)  
 { sound(x);  
  delay(1);  
  }  
 nosound();  
}  
void Snake::score()  
{ char *p;  
  ltoa(scr,p,10);  
  settextstyle(8,0,1);  
  setcolor(0);  
  outtextxy(585,40,p);  
  if(egGen != 1){  
  scr = scr + dly / 10;  
  }  
  ltoa(scr,p,10);  
  setcolor(10);  
  outtextxy(585,40,p);  
}  
void Snake::gnrtCond()  
{ if(n < 367)  
 { if(now == 8 && (prev != 8 && prev != 2))  
  { pos[0][0] = p1;  
   pos[0][1] = p2 - dsp;  
   prev = now;  
   }  
  if(now == 4 && (prev != 4 && prev != 1))  
  { pos[0][0] = p1 + dsp;  
   pos[0][1] = p2;  
   prev = now;  
   }  
  if(now == 2 && (prev != 8 && prev != 2))  
  { pos[0][0] = p1;  
   pos[0][1] = p2 + dsp;  
   prev = now;  
   }  
  if(now == 1 && (prev != 1 && prev != 4))  
  {pos[0][0] = p1 - dsp;  
   pos[0][1] = p2;  
   prev = now;  
   }  
}  
}  
void Snake::gnrtUnCond()  
{  
  if( prev == 8 )  
  { pos[0][0] = p1;  
   pos[0][1] = p2 - dsp;  
   }  
 if( prev == 4 )  
  {pos[0][0] = p1 + dsp;  
   pos[0][1] = p2;  
   }  
 if( prev == 2 )  
  { pos[0][0] = p1;  
   pos[0][1] = p2 + dsp;  
   }  
 if( prev == 1 )  
  {pos[0][0] = p1 - dsp;  
   pos[0][1] = p2;  
   }  
 p1 = pos[0][0];  
 p2 = pos[0][1];  
}  
void Snake::check()  
{  
 if(p1 > endX)  
  {p1 = strtX;}  
 else if(p1 < strtX)  
  { p1 = endX;}  
 if(p2 > endY)  
  { p2 = strtY;}  
 else if(p2 < strtY)  
  { p2 = endY;}  
 pos[0][0] = p1;  
 pos[0][1] = p2;  
for(int i = 1;i < n;i++)  
  { if(p1 == pos[i][0] && p2 == pos[i][1])  
  { caught();  
   break;  
  }  
 }  
}  
void Snake::show()  
{  
  int x = getcolor();  
  if(egGen != 1)  
  {  
  setcolor(getbkcolor());  
  setfillstyle(1,getbkcolor());  
  fillellipse(v1,v2,yr,yr);  
   }  
  else  
   egGen = 0;  
  if (egGen == 2)  
   egGen--;  
  setcolor(colr);  
  setfillstyle(1,9);  
  if(now == 8 || now == 2)  
   fillellipse(pos[0][0],pos[0][1],xr,yr);  
  else if(now == 4 || now == 1)  
   fillellipse(pos[0][0],pos[0][1],yr,xr);  
  setcolor(x);  
}  
void Snake::transpose()  
{ int i,j,x,y;  
   p1 = pos[0][0];  
   p2 = pos[0][1];  
   if(!egGen){  
   v1 = pos[n-1][0];  
   v2 = pos[n-1][1];  
   }  
   else  
    egGen = 0;  
   for(i = n-1;i >= 1;i--)  
   {pos[i][0] = pos[i-1][0];  
    pos[i][1] = pos[i-1][1];  
   }  
}  
void Snake::move()  
{ int st = 0;  
  do{  
   if(!kbhit())  
   { checkegg();  
    if(!st)  
     show();  
    else  
     st = 0;  
    delay(dly/4);  
    transpose();  
    delay(dly/4);  
    gnrtUnCond();  
    delay(dly/4);  
    check();  
   delay(dly/4);  
    }  
   else if(stp){  
   chngDir();  
   gnrtCond();  
   check();  
   show();  
   st = 1;  
   }  
   } while(stp);  
}  
void Snake::init()  
{time_t tm;  
 srand(time(&tm));  
 dsp = 20;  
 n = 5;  
 prev = 4;  
 for(int i = 4;i >= 0;i--)  
 { pos[i][0] = 201 + (n - i - 1) * dsp;  
  pos[i][1] = 301;  
  }  
  strtX = 21;  
  strtY = 21;  
  endX = 481;  
  endY = 361;  
  colr = 14;  
  now = prev;  
  dsp = 20;  
  stp = 111;  

OUTPUT:

Snake Code in C++

Related Topics

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.