subbisush (1) (1)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Snake 2D-Game 2022-23

CHAPTER 1

INTRODUCTION

The aim of this project is to develop a The Epilogue of Education. A child can choose to
doctor,anengineer,apilot,ascientist,anartist,anentrepreneur,apolitician,apoliceman,agovernment
official ,a marketer ,a cricketer ,a football player ,a hockey player ,a professional bowler ,a
lawyer ,a designer ,a developer ,a photographer ,a dancer ,a singer .He /She could be a super hero
if they wished to be. The opportunities are endless.. The interface should be user friendly and
should use keyboard interface for the interaction with the user. The main goal is a story that
defines the problems of education in our current society, and how we are far off from an actual
smart world.

1.1 COMPUTER GRAPHICS

The term computer graphics includes almost everything on computers that is not text or sound. Today
almost every computer can do some graphics, and people have even come to expect to control
their computer through icons and pictures rather than just by typing .Computer graphics are
created using computers and the representation of image data by a computer specifically with
help from specialized graphic hardware and software. The interaction and understanding of
computers and interpretation of data has been made easier because of computer graphics. A
computer graphic development has had a significant impact on many types of media and has
revolutionized animation, movies and the video game industry. Typically, the term computer
graphics refers to several different things:
 The representation and manipulation of image data by a computer
 The various technologies used to create and manipulate images
 The sub-field of computer science which studies methods for digitally synthesizing and
manipulating visual content.
Computer generated imagery can be categorized into several different types: two dimensional
(2D), three dimensional (3D), and animated graphics. As technology has improved, 3D computer
graphics have become more common, but 2D computer graphics are still widely used. Computer
graphics has emerged as a sub-field of computer science which studies methods for digitally

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 1


Snake 2D-Game 2022-23

synthesizing and manipulating visual content. Over the past decade, other specialized fields have
been developed like information visualization, and scientific visualization more concerned with
"the visualization of three dimensional phenomena (architectural, meteorological, medical,
biological, etc.), where the emphasis is on realistic renderings of volumes, surfaces, illumination
sources, and so forth, perhaps with a dynamic (time) component".

1.2 OpenGL

Originally developed by Silicon Graphics in the early '90s, OpenGL® has become the most
widely-used open graphics standard in the world. OpenGL is a software interface to graphics
hardware. This interface consists of about 150 distinct commands that you use to specify the
objects and operations needed to produce interactive three-dimensional applications. OpenGL
(Open Graphics Library) is basically a cross-language, multi-platform API for rendering 2D and
3D computer graphics. The API is typically used to interact with a GPU, to achieve hardware-
accelerated rendering .OpenGL serves two main purposes:
 To hide the complexities of interfacing with different 3D accelerators, by presenting
the programmer with a single, uniform API.
 To hide the differing capabilities of hardware platforms, by requiring that all
implementations support the full OpenGL feature set (using software emulation if
necessary).Some features of OpenGL include the following:
 Geometric and raster primitives
 RGBA or color index mode
 Display list or immediate mode
 Viewing and modelling transformations
 Lighting and Shading
 Hidden surface removal (Depth Buffer)
 Texture Mapping OpenGL is a low-level, procedural API, requiring the programmer to
dictate the exact steps required to render a scene.

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 2


Snake 2D-Game 2022-23

1.3 GLUT

GLUT is the OpenGL Utility Toolkit, a window system independent toolkit for writing
OpenGL programs. It implements a simple windowing application programming interface(API)
for OpenGL. The GLUT library has C, C++ (same as C), FORTRAN, and Ada programming
bindings. The GLUT source code distribution is portable to nearly all OpenGL implementations
and platforms. The current version is 3.7. Additional releases of the library are not
anticipated .The GLUT library supports the following functionality:
 Multiple windows for OpenGL rendering.
 Callback driven event processing.
 An `idle' routine and timers.
 Utility routines to generate various solid and wire frame objects.
 Support for bitmap and stroke fonts.
 Miscellaneous window management functions

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 3


Snake 2D-Game 2022-23

Chapter 2

LITERATURE SURVEY

Computer graphics started with the display of data on hardcopy plotters and cathode ray
tube (CRT) screens soon after the introduction of computers.
OpenGL APIs: If we want to have a control on the flow of program and if we want to interact
with the window system then we use OpenGL API'S Vertices are represented in the same
manner internally, whether they are specified as two-dimensional or three- dimensional entities,
everything that we do are here will be equally valid in three dimensions. Although OpenGL is
easy to learn, compared with other APIs, it is nevertheless powerful. It supports the simple three-
dimensional programs and also supports the advanced rendering techniques.
GL/glut.h: We use a readily available library called the OpenGL Utility Toolkit (GLUT). which
provides the minimum functionality that should be expected in any modem windowing system.
The application program uses only GLUT functions and can be recompiled with the GLUT
library for other window system. OpenGL makes a heavy use of macros to increase code
readability and avoid the use of magic numbers. In most implementation, one of the include
lines.

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 4


Snake 2D-Game 2022-23

Chapter 3

SYSTEM REQUIREMENTS

To be used efficiently, all computer software needs certain hardware components or other
software components to be present on a computer. These prerequisites are known as software
requirements. Though our graphics software does not demand strict specifications, certain basic
hardware and software requirements must be met.

3.1 HARDWARE REQUIREMENTS

 CPU: Intel/AMD CPU


 RAM (Main memory): 512 MB
 Hard disk: 10MB of free space
 Hard disk speed (in RPM): 5400 RPM
 Mouse: 2 button mouse
 Keyboard: Standard keyboard with arrow keys
 Monitor: 1366*768 display resolution

3.2 SOFTWARE REQUIREMENTS

 Operating System: Windows based operating system


 Code::Blocks with OpenGL library
 Mouse driver
 Graphic driver

FIGURE 3.1 CODE BLOCKS FIGURE 3.2 OPENGL API

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 5


Snake 2D-Game 2022-23

Chapter 4

SYSTEM IMPLEMENTATION
4.1 OpenGL Functions:
The different OpenGL functions that are used in the project is described below: glClearColor
(0.0.0.0,0.0,1.0): - glClearColor () specifies the red, green, blue, and alpha values used by
glClear() to clear the color buffers. Values specified by glClearColor () are clamped to the range
0, 1

 glMatrixMode(GL_MODELVIEW):- Specify which matrix is the current matrix.


Specifics which matrix stack is the target for subsequent matrix operations. Three values
are accepted: GL_MODELVIEW, GL_PROJECTION, and GL TEXTURE. The initial
value is GL MODEL `VIEW.
 gluOrtho2D(0,1024,0,768):- Define a 2D orthographic projection matrix. Left, right-
Specify the coordinates for the left and right vertical clipping planes. Bottom, top-Specify
the coordinates for the bottom and top horizontal clipping planes.
 glRasterPos2i(x, y):- The glRasterPos2 function uses the argument values for x and y
while implicitly setting z and w to zero and one. The object coordinates presented by
glRasterPos are treated just like those of a glVertex command. They are transformed by
the current model view and projection matrices and passed to the clipping stage
 GlutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,string[i]):-
glutBitmapCharacter renders a bitmap character using OpenGL, Without using any
display lists, glutBitmapCharacter renders the character in the named bitmap font.
 glFlush():- Force execution of GL commands in finite time. glFlush empties all of these
buffers, causing all issued commands to be executed as quickly as they are accepted by
the actual rendering engine. Though this execution may not be completed in any
particular time period, it does complete in finite time.
 glVertex2f(0.0,30.0/3):- Specify vertex. glVertex commands within glBegin/glEnd pairs
to specify point, line, and polygon vertices. The current color, normal, texture
coordinates, and fog coordinate are associated with the when glVertex is called. Vertex
used

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 6


Snake 2D-Game 2022-23

 glEnd():- Delimit the vertices of a primitive or group of like primitives. glBegin and
glEnd delimit the vertices that define a primitive or a group of like primitives.
 glutSwapBuffers():- glutSwapBuffers swaps the buffers of the current window if double
buffered. Performs a buffer swap on the layer in use for the current window. Specifically,
glutSwapBuffers promotes the contents of the back buffer of the layer in use of the
current window to become the contents of the front buffer. An implicit glFlush is done by
glutSwapBuffers before it returns. If the layer in use is not double buffered, glutSwap
Buffers has no effect.
 glPushMatrix():- Push and pop the current matrix stack. There is a stack of matrices for
each of the matrix modes. The current matrix in any mode is the matrix on the top of the
stack for that mode. glPushMatrix pushes the current matrix stack down by one,
duplicating the current matrix. That is, after a glPushMatrix call, the matrix on top of the
stack is identical to the one below it.
 glPopMatrix():- Push and pop the current matrix stack. glPopMatrix pops the current
matrix stack, replacing the current matrix with the one below it on the stack.
 glTranslatef(50,100,0) Multiply the current matrix by translation a matrix. glTranslate
produces a translation by x y z. The current matrix is multiplied by this translation
matrix, with the product replacing the current matrix.
 glutInit(&arge.argv) glutInit is used to initialize the GLUT library, glutlnit will initialize
the GLUT library and negotiate a session with the window system. During this process,
glutinit may cause the termination of the GLUT program with an error message to the
user if GLUT cannot be properly initialized. glutinit also processes command line
options, but the specific options parse are window system dependent.
 glutInitDisplayMode(GLUT SINGLE GLUT_RGB) - Sets the initial display mode. The
initial display mode is used when creating top-level windows, sub windows, and overlays
to determine the OpenGL display mode for the to-be-created window or overlay.
 glutInitWindowSize(1024,768) Set the initial window size. Windows created by
glutCreateWindow will be requested to be created with the current initial window
position and size. The initial value of the initial window size GLUT state is 300 by 300.
The initial window size components must be greater than zero. The intent of the initial
window position and size values is to provide a suggestion to the window system for a

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 7


Snake 2D-Game 2022-23

window's initial size and position. The window system is not obligated to use this
information. A GLUT program should use the window's reshape call-back to determine
the true size of the window.
 glutCreateWindow(“MOVING OBJECTS"):- Creates a top-level window. The name will
be provided to the window system as the window's name. The intent is that the window
system will label the window with the name, Implicitly, the current window is set to the
newly created window.
 glutPositionWindow(0.0):- Requests a change to the position of the current window. For
top-level windows, the x and y parameters are pixel offsets from the screen origin. For
sub windows, the x and y parameters are pixel offsets from the window's parent window
origin.
 glutDisplayFunc(display):-Registers the callback function (or event handler) for handling
window-paint event. The OpenGL graphic system calls back this handler when it receives
a window re-paint request. In the example, we register the function display() as the
handler.
 glutKeyboardFunc(keyboard):-glutKeyboardFunc sets the keyboard callback for the
current window. When a user types into the window, each key press generating an ASCII
character will generate a keyboard callback. The key callback parameter is the generated
ASCII character. The state of modifier keys such as Shift cannot be determined directly;
their only effect will be on the returned ASCII data.
 glutMainLoop():-glutMainLoop enters the GLUT event processing loop. This routine
should be called at most once in a GLUT program. Once called, this routine will never
return. It will call as necessary any call backs that have been registered.

4.2 User Defined Functions:


The whole project is divided into many small parts known as functions and these functions
would take care of implementing particular parts of this project which makes the programming
easy and effective. Each function takes the responsibility of designing the assigned parts hence
we combined all the functions at a particular stage to get the final required design. The functions
that are used to implement the "A THIRSTY CROW-STORY DEMONSTRATION " are:

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 8


Snake 2D-Game 2022-23

 void display():-This function is used to display the start of the bus scene. It calls other
function like display20), display3() and display4(). It is also used to define and set the
colour. In the end there is a glflush() to display everything in the screen.
 void front screen(void) This function is used to display the first page i. e topic of the
project and instructions.

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 9


Snake 2D-Game 2022-23

Chapter 5

SYSTEM ANALYSIS

5.1 OpenGL Graphics Architecture:

Fig.1.5.1: Opengl Graphics Architecture

The OpenGL pipeline performs conditional or selection operations at a number of stages


in the pipeline. One or more of these stages can be used together to implement simple
conditional operations in a multipass algorithm. Examples include the depth and alpha tests. The
OpenGL rendering pipeline is initiated when you perform a rendering operation. Rendering
operations require the presence of a properly-defined vertex array object and a linked Program

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 10


Snake 2D-Game 2022-23

Object or Program Pipeline Object which provides the shaders for the programmable pipeline
stages

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 11


Snake 2D-Game 2022-23

Chapter 6
SOURCE CODE

#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <gl/glut.h>

#define UP 1
#define Down 2
#define LEFT 3
#define RIGHT 4

// Status Variables
GLint lvl = 1;
GLint points = 0;
GLint size = 0;
GLbyte gameOver = true;
GLbyte EnableLight = true;

// Snake Variables
GLint bodyPos[2][100] = {{}};
GLint _x = 5;
GLint _z = 10;
GLint _oldX[2] = {};
GLint _oldZ[2] = {};
GLbyte direction = 0;

// Food Variables
GLint _bx = 0;

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 12


Snake 2D-Game 2022-23

GLint _bz = 0;

// Screen variables
GLint _w = 800;
GLint _h = 550;
GLint _Giw = 0;
GLint _Gih = 0;
GLint _Gfw = 150;
GLint _Gfh = 150;

//Variables for the Camera Angle


static GLfloat view_rotx=45.0F ;
static GLfloat view_roty=0.0F ;
static GLfloat view_rotz=0.0F ;

static GLfloat headRotation=90.0F ;


static GLfloat zoom=-300.0f;
//Configure the lightning
void initLight()
{
//Add ambient light
GLfloat ambientColor[] = {0.3f, 0.4f, 0.8f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
//Add positioned light
GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f};
GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
//Add directed light
GLfloat lightColor1[] = {0.5f, 0.2f, 0.2f, 1.0f};
//Coming from the direction (-1, 0.5, 0.5)

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 13


Snake 2D-Game 2022-23

GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f};


glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
}
//initialize the first configurations
void Initialize(void)
{
glEnable(GL_DEPTH_TEST);
glClearColor(0.4f, 0.8f, 1.0f, 1.0f); //Change the background to sky blue
if(EnableLight){
glEnable(GL_COLOR_MATERIAL); //Enable color
glEnable(GL_LIGHTING); //Enable lighting
glEnable(GL_LIGHT0); //Enable light #0
glEnable(GL_LIGHT1); //Enable light #1
glEnable(GL_NORMALIZE); //Automatically normalize normals
}
}
//Configure window resize
void resize (int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)w / (double)h,1, 800.0);
}
void Write(char *string){//Write string on the screen
while(*string)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *string++);
}
//This Function will rotate the object according to the Angles
void ManipulateViewAngle() {

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 14


Snake 2D-Game 2022-23

glRotatef(view_rotx,1.0,0.0,0.0);//Rotate Arround X axis


glRotatef(view_roty,0.0,1.0,0.0);//Rotate Arround Y axis
glRotatef(view_rotz,0.0,0.0,1.0);//Rotate Arround Z axis
}
//This Function will reset the snake size and location...
void Reset(){
_x = 5;
_z = 10;
direction = 0;
lvl = 1;
points = 0;
size = 0;
gameOver = false;
view_rotx=45.0F ;
view_roty=0.0F ;
view_rotz=0.0F ;
headRotation=90.0F ;
}
//Display a welcome screen
void WelcomeScreen(){
char tmp_str[40];

glRasterPos2f(-40, 20);
Write("=========WELCOME TO Azzonika Tutorials=========");
glRasterPos2f(-6, 10);
Write("=========Simulation of Snake Game=========");
glRasterPos2f(-60, 0);
Write("=========To Start Playing please press 'S' or 's' =========");
}
void DrawSnake(){
int i;

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 15


Snake 2D-Game 2022-23

//Drawing the head & the plane


glPushMatrix();
ManipulateViewAngle();
//This will draw the plane that the snake will run on.
glPushMatrix();
//glColor3f(1, 0.7, 0.2);
glColor3f(0.0, 0.6, 0.2);
glTranslatef(75.0, -16.0, 75.0);
glScalef(155,5.0,155);
glutSolidCube(1);
glPopMatrix();
//Here we will draw the Head of the snake
glColor3f(1,0,0);//Color it red
glTranslatef(_x,-10.0,_z);//Give it the location according to _x & _z
glScalef(0.5,0.5,0.5);
glutSolidSphere(10,20,20);//Draw the head as a sphere a litle bit bigger than the body spheres
glRotatef(headRotation, 0.0, 1.0, 0.0);
glColor3f(1,0,0);
glTranslatef(0,0.0,6.0);
glScalef(0.8,1.0,1.0);
glutSolidCone(10,10,20,20);
glColor3f(1,1,1);
glTranslatef(-4.0,10.0,0.0);
glScalef(0.3,0.3,0.3);
glutSolidSphere(10,20,20);
glTranslatef(26.0,0.0,0.0);
glutSolidSphere(10,20,20);
glPopMatrix();

//Drawing the body


for(i=0; i<size; i++){//Loop throw the size and draw spheres representing the body

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 16


Snake 2D-Game 2022-23

glPushMatrix();
ManipulateViewAngle();
glTranslatef(bodyPos[0][i],-10.0,bodyPos[1][i]);//this will locate the spheres
glColor3f(1,0,0);//Color Red
glScalef(0.5,0.5,0.5);
glutSolidSphere(7,20,20);
glPopMatrix();
}
}
void DrawFood()
{
//Draw the Sphere representing the Food for the snake
glPushMatrix();
ManipulateViewAngle();
glTranslatef(_bx,-10.0,_bz);
glColor3f(1, 1, 0);
glScalef(0.5,0.5,0.5);
glutSolidSphere(7,20,20);
glPopMatrix();
}
void GameStatus(){
char tmp_str[40];
glColor3f(0.8, 0.2, 0);
glRasterPos2f(5, 20);
sprintf(tmp_str, "Snake Game");
Write(tmp_str);
// Print the status of the game on the screen
glColor3f(0, 0, 0);
glRasterPos2f(5, 10);
sprintf(tmp_str, "Level: %d Points: %d", lvl, points);
Write(tmp_str);

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 17


Snake 2D-Game 2022-23

}
//Generates Random Numbers for the location of the food that the snake will eat
int RandomNumber(int high, int low)
{
return (rand() % (high-low))+low;
}
//Generate the New Food that the snake will eat
void newFood(){
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
_bx = RandomNumber(_Gfw-_Giw, _Giw+10);
_bz = RandomNumber(_Gfh-_Gih, _Gih+10);
}
//This Function Will Check for Collision
bool collision(){
int i;
for(i=0; i<size; i++){
if((bodyPos[0][i] == _x && bodyPos[1][i] == _z) ||
//((bodyPos[0][i] >= _x) && (bodyPos[0][i] <= _x + 5) && (bodyPos[1][i] >= _z) &&
(bodyPos[1][i] <= _z + 5)) ||
//((bodyPos[0][i] <= _x) && (bodyPos[0][i] >= _x - 5) && (bodyPos[1][i] <= _z) &&
(bodyPos[1][i] >= _z - 5)) ||
//((bodyPos[0][i] <= _x) && (bodyPos[0][i] >= _x - 5) && (bodyPos[1][i] >= _z) &&
(bodyPos[1][i] <= _z + 5)) ||
((bodyPos[0][i] >= _x) && (bodyPos[0][i] <= _x + 5) && (bodyPos[1][i] <= _z) &&
(bodyPos[1][i] >= _z - 5)))
return true;
}
return false;
}

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 18


Snake 2D-Game 2022-23

//This Function will move the snake according to the directions


//Taken from the Keyboard keys
void Run(int value){
int i;
_oldX[1] = _x;
_oldZ[1] = _z;
switch(direction){
case RIGHT:
headRotation =90;
_x += 6;
if(_x > _Gfw-2) _x = _Giw-1;//This will check if the snake is going into the border so it
will appear on the other side
break;
case LEFT:
headRotation =-90;
_x -= 6;
if(_x < 0) _x = _Gfw-2;//This will check if the snake is going into the border so it will
appear on the other side
break;
case UP:
headRotation =0;
_z += 6;
if(_z > _Gfh-2) _z = _Gih-1;//This will check if the snake is going into the border so it will
appear on the other side
break;
case Down:
headRotation =180;
_z -= 6;
if(_z < 2) _z = _Gfh-2;//This will check if the snake is going into the border so it will
appear on the other side
break;

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 19


Snake 2D-Game 2022-23

}
//Checks for Collisoin if yes Game Over
if(collision()) gameOver = true;
//Checks if the snake ate the food (check the X and Y)
// If yes it will increase the points & the size of the snake & create a new food
if((_x == _bx && _z == _bz) ||
((_x >= _bx) && (_x <= _bx + 4) && (_z >= _bz) && (_z <= _bz + 4)) ||
((_x <= _bx) && (_x >= _bx - 4) && (_z <= _bz) && (_z >= _bz - 4)) ||
((_x <= _bx) && (_x >= _bx - 4) && (_z >= _bz) && (_z <= _bz + 4)) ||
((_x >= _bx) && (_x <= _bx + 4) && (_z <= _bz) && (_z >= _bz - 4))){
points++;
if(points < 100) size++;
if(points%5 == 0 && lvl < 15) lvl++;
newFood();
}

for(i = 0; i<size; i++){// Save the positions of the body parts


_oldX[0] = _oldX[1];
_oldZ[0] = _oldZ[1];
_oldX[1] = bodyPos[0][i];
_oldZ[1] = bodyPos[1][i];
bodyPos[0][i] = _oldX[0];
bodyPos[1][i] = _oldZ[0];
}

//Set the Timer


glutTimerFunc(130, Run, 0);
}

void Display(void){//Draw Function


// Clear screen

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 20


Snake 2D-Game 2022-23

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if(EnableLight) initLight();

glTranslatef (-60.0, 40.0, zoom);


//Check if the value of the Flag "Game Over is not True it will continue the game"
if(!gameOver){
GameStatus();
DrawFood();
DrawSnake();
}
else
WelcomeScreen();
// Updates the screen
glutPostRedisplay();
glutSwapBuffers();
}
void Special(int key, int x, int y){
switch(key){
case GLUT_KEY_RIGHT :
if(direction != LEFT)
direction = RIGHT;
break;
case GLUT_KEY_LEFT :
if(direction != RIGHT)
direction = LEFT;
break;
case GLUT_KEY_UP :
if(direction != UP)
direction = Down;

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 21


Snake 2D-Game 2022-23

break;
case GLUT_KEY_DOWN :
if(direction != Down)
direction = UP;
break;
}
}
void keyboard (unsigned char key, int x, int y)
{
switch (key) {
case 'S' : Reset() ;
glutPostRedisplay();
break;
case 's' : Reset() ;
glutPostRedisplay();
break;
//ESC to Exit
case 27:
exit(0);
break;
default:
break;
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(_w,_h);
glutInitWindowPosition(80,80);
glutCreateWindow("Snake Game");
Initialize();

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 22


Snake 2D-Game 2022-23

glutSpecialFunc(Special);
glutKeyboardFunc(keyboard);
glutDisplayFunc(Display);
glutReshapeFunc(resize);
newFood();
Run(0);
glutMainLoop();
}

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 23


Snake 2D-Game 2022-23

Chapter 7
SnapShots

Fig7.1

Fig7.2

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 24


Snake 2D-Game 2022-23

Fig 7.4 Level 3 of the Snake game

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 25


Snake 2D-Game 2022-23

Fig 7.5 level 4 of the Snake game

Fig 7.6

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 26


Snake 2D-Game 2022-23

Chapter 8

Conclusion and references


8.1 Conclusion
The player controls a long, thin creature, resembling a snake, which roams around on a
bordered plane, picking up food (or some other item), trying to avoid hitting its own tail or the
edges of the playing area. Each time the snake eats a piece of food, its tail grows longer, making
the game increasingly difficult.

The Snake Game is a Good Way to Learn How to Recognize Patterns. Patterns have a
way of building academic skills, especially in the mathematical field. The Snake game is all
about patterns and how you can manipulate these patterns as the Snake gets longer.

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 27


Snake 2D-Game 2022-23

8.2 References

Books
1. The Java Programming Language, by Ken Arnold, James Gosling, David HolmesADDISON-
WESLEY, 2000, ISBN 81-7808-148-2
2. Java Threads, Second Edition, by Scott Oaks, Henry WongO'REILLY, 1997, ISBN 81-7366-
057-3
3. Core Java – Volume I/II, Seventh Edition, by Cay S. Horst mann, Gary Cornell PEARSON
EDUCATION, 2005, ISBN 81-297-0932-5
4. Introduction to Algorithms, Second Edition, by Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest, Clifford SteinMIT PRESS, 2001, ISBN 81-203-2141-3
5. Head First Java, Second Edition, by Kathy Sierra, Bert BatesO'REILLY, May 2003, ISBN 81-
7366-602-4
Websites
1. Netbeans Community Docs
http://wiki.netbeans.org/wiki/view/CommunityDocs2.
2. The Inkscape Tutorials Blog
http://inkscapetutorials.wordpress.com/
3. Smashing Magazine – On line magazine for designers
http://www.smashingmagazine.com/
4. The Java Tutorials
http://java.sun.com/docs/books/tutorial/
5. Timing Framework
https://timingframework.dev.java.net/
6. JavaGaming.org's Forum
http://www.javagaming.org/forums/index.php
7. MIT Open Course Ware - 6.831 User Interface Design and Implementation
http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-831Fall-
2004/CourseHome/index.htm

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 28


Snake 2D-Game 2022-23

8. Amit's A* Page – Tutorial on A* Path finding algorithms


http://theory.stanford.edu/~amitp/GameProgramming/
9. Arianne - a multiplayer online games framework
http://arianne.sourceforge.net/
10. JavaDesktop Community Blog
http://community.java.net/javadesktop/
11. Java Forum
http://forum.java.sun.com
12. Blog of Romain Guy – coauthor of Filthy Rich Clients
http://www.curious-creature.org/
13. Filthy Rich Clients – Examples
http://www.filthyrichclients.com/
14. The Java Developers Almanac 1.4
http://www.exampledepot.com/
15. Apache MINA Sample programs and tutorials
http://mina.apache.org/
16. PHP Documentation for XML library
http://www.php.net/

Dept. of CS&E, KR Pete Kirshna Govt. Engg. College K R Pet Page 29

You might also like