0% found this document useful (0 votes)
72 views

Snake Game Project Report

The document describes a snake game project that aims to bring fun and simplicity of the classic snake game. It provides details about the game objectives, features, and development. The game allows the player to control a snake and eat apples to grow while avoiding collisions. It includes features like pause, speed control, score tracking, and respawning after death. The project aims to implement the game in Java and add improvements over traditional snake games.

Uploaded by

wilp.bits.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Snake Game Project Report

The document describes a snake game project that aims to bring fun and simplicity of the classic snake game. It provides details about the game objectives, features, and development. The game allows the player to control a snake and eat apples to grow while avoiding collisions. It includes features like pause, speed control, score tracking, and respawning after death. The project aims to implement the game in Java and add improvements over traditional snake games.

Uploaded by

wilp.bits.cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

An

Industrial Project Report


On
Snake Game
Submitted to the Rajasthan Technical University, Kota in
Partial fulfilment of the requirement for the degree of
MASTER OF COMPUTER APPLICATIONS

Supervisor Submitted by:


Mr. Ramakant Gautam Aanchal Gupta
Assistant Professor Enrolment No.: 20C2MOXXF40P600

MODI INSTITUE OF MANAGEMENT AND TECHNOLOGY


Affiliated to
RAJASTHAN TECHNICAL UNIVERSITY,
Kota(Rajasthan)-324010

May, 2022
Candidate’s Declaration

I hereby declare that the work, which is being presented in the MCA-451, Industrial Project ,
entitled “Snake Game” in partial fulfilment for the award of Degree of “Master of
Computer Applications” in Department of Computer Applications submitted to the Modi
Institute of Management and Technology(MIMT), Rajasthan Technical University is a
record of my own work carried under the Guidance of Shri Ramakant Gautam sir,
Department of Computer Applications, Modi Institute of Management and Technology.
I have not submitted the matter presented in this Project Report anywhere for the award of
any other Degree.

Aanchal Gupta
Enrolment No.: 20C2MOXXF40P600
Modi Institute of Management and Technology,

Name of Supervisor
Mr. Ramakant Gautam
Assistant Professor
Modi Institute of Management and Technology
Department of Computer Applications

Certificate

Date:
This is to certify that the Industrial Project (MCA-451) work entitled “Snake Game”
submitted by “Aanchal Gupta” (RTU Roll No.: 20CMOXX600) to the Department of
Computer Science and Application of Modi Institute of Management and Technology has
been examined and evaluated.

The Project work has been prepared as per the regulations of Rajasthan Technical
University, Kota and qualifies to be accepted in partial fulfilment of the requirement for the
degree of MCA (Master of Computer Applications).

Signature of the student Supervisor


Aanchal Gupta Mr. Ramakant Gautam
Assistant Professor

External Examiner
(Name with Designation) Head of Institution/Principal
Acknowledgement

The success and final outcome of this project required a lot of guidance and assistance from
many people, and I am extremely privileged to have got this all along the completion of my
project. All that I have done is only due to such supervision and assistance and I would not
forget to thank them.

I respect and thank my H.O.D, Mr. Kamal Kulshreshtha, for providing me an opportunity
to do the project work in Modi Institute of Management & Technology, and giving me all
support and guidance, which made me complete the project duly. I am extremely thankful to
him for providing such a nice support and guidance.

I heartily thank my internal project guide and owe my deep gratitude to Mr. Ramakant
Gautam, for his encouragement and moreover for his timely support and guidance till the
completion of my project work.

I am thankful to and fortunate enough to get constant encouragement, support and guidance
from all teaching staff of Department of Computer Applications, which helped me in
successfully completing my project work. Also, I would like to extend my sincere esteems to
all staff in laboratory for their timely support.
TABLE OF CONTENTS

1. Introduction
1.1 Objectives
1.2 Problem description
1.3 About Organization
2. System Study
2.1 System with limitations
2.2 Significance of the Project
2.3 Beneficiaries of the System
2.4 Feasibility study
3. System Analysis Requirement Specification
i. Functional Requirement
ii. Non Functional Requirement
iii. User Requirement
iv. System Requirement
4. System Design
a) Data Flow Diagram
b) E-R Diagrams
c) Use Case Diagrams
d) Flow Charts
e) Input output Forms
5. Development
a) Environment
b) Coding Style
c) Coding Techniques
d) Coding
6. Testing
a. Test cases
7. System Security
a. Checks and Control
b. Encryption, secure
8. Conclusion/Future Enhancement
9. Bibliography
1. INTRODUCTION

The Project is a game written in Java based on the game called ‘snake’ which has been
around since the earliest days of home computing and has re-emerged in recent years on
mobile phones.
This Project aims to bring fun and simplicity of snake game.
Snake is an older classic video game. It was first created in late 70s. Later it was brought to
PCs. In this game the player controls a snake. The objective is to eat as many apples as
possible. Each time the snake eats an apple its body grows. The snake must avoid the walls
and its own body. This game is sometimes called Nibbles.
The game is similar to snake on mobile phones (which is similar to a game played on Unix
over 30 years ago), but with some ‘improvements’. The game is played by one player, who
has the objective of obtaining the highest score possible. The player is in control of a snake
which is constantly moving around a square field of cells. The length of the snake is a whole
number of cells. At any time, the snake moves in one of the 4 directions, parallel to a side of
the square, and the player can change the direction using the 4 arrow keys of the keyboard. If
the snake crashes into a side, or into itself, then it is dead, and the game stops. Also in the
field is a single piece of food. When the head of the snake hits this, the food is eaten, and the
snake becomes one cell longer. This event increases the score of the player. At 2 the same
time, a new piece of food is placed in a randomly chosen cell somewhere in the field, which
was previously clear (empty).
The game has a score message bar, informing the player what is the current score, and also a
single message which changes from time to time. For example, when food is eaten the player
is informed how much score was just obtained, and when the snake crashes a suitable
message is shown. The player can make the game go slower or faster, and can alter the speed
during the game, by pressing ‘s’ to slow down and ‘f’ to speed up. The score obtained when
a piece of food is eaten is proportional to the speed setting. The game can also be paused and
resumed by pressing ‘p’ and ‘r’ respectively.
The game will be in a paused state when it starts. The speed controller can be placed in
interactive mode by the player pressing ‘i’ – this enables the player to see the current speed
and also alter it via buttons. At any time, the player can end the game and start a new one,
simply by pressing ‘a’ on the keyboard. The most common use of this will be after the snake
has crashed, so as to continue playing with a new game.
When the snake is dead, the player has the option to ‘cheat’ by making it come back to life so
play can continue. However, this costs the player half of his or her score. The cheat feature is
invoked when the player presses ‘c’ on the keyboard. The player has the option of enabling
trees to appear in the field. This feature is toggled on and off by pressing ‘t’ on the keyboard.
When trees become enabled, a single tree appears in a randomly chosen clear cell. Then,
each time the food is eaten, another tree appears somewhere, and so on. This makes the game
more interesting, because the snake will die if it crashes into a tree.
The game is thus more difficult, and so if trees are enabled when the food is eaten, the score
obtained is multiplied by the number of trees in the field at the time. When the trees feature
is toggled off, all the trees vanish. Each time the snake crashes into something, it will not die
immediately. Instead, a ‘crash countdown’ begins, and reduces by one each move time of the
game. The player sees this count down via the score message bar. If the snake is moved away
before the countdown reaches zero, it has escaped death. The game offers a single ‘about’
and ‘help’ box, popped up and down by pressing ‘h’. There is no requirement for keeping
track of high scores.

1.1 Objective

This game aims to change the way people think of traditional snake game. It will offer the ex
perience of commercial multilayer games to the player retaining the simplicity of traditional
snake game.

The objective and scope of my Project Snake Game is to record the details various activities
of user. It will simplify the task and reduce the paper work. During implementation every
user will be given appropriate training to suit their specific needs. Specific support will also
be provided at key points within the academic calendar. Training will be provided on a
timely basis, and we will be trained as the new is Snake Game rolled out to our area of
responsibility.

At the moment we are in the very early stages, so it is difficult to put a specific time on the
training, but we will keep people informed as plans are developed. The system is very user
friendly and it is anticipated that functions of the system will be easily accessed by
administrators, academics, students and applicants.

Hence the management system for the College management has been designed to remove all
the deficiency from which the present system is suffering and to ensure.
The major objectives of this project are:

● Create a snake game that will have all the functionality of traditional snake games.
● Introduce multilayer functionality in the game that will allow several players to play a
game simultaneously. It should be able to give the experience of a real time multiplayer
game to the players.
● Introduce computer controlled intelligent opponent (unique feature of this game) to make
the game more challenging and interesting. The movement and action of these intelligent
opponents will be controlled by computer whose aim will be to eat the food
before human players capture it.

1.2 Problem description

This is small game. In this if the player has to change the direction of the snake for getting
food for snake. The game is similar to snake on mobile phones (which is similar to a game
played on Unix over 30 years ago), but with some ‘improvements’.

The game is played by one player, who has the objective of obtaining the highest score
possible. The player is in control of a snake which is constantly moving around a square field
of cells. The length of the snake is a whole number of cells.

At any time, the snake moves in one of the 4 directions, parallel to a side of the square, and
the player can change the direction using the 4 arrow keys of the keyboard. If the snake
crashes into a side, or into itself, then it is dead, and the game stops. Also in the field is a
single piece of food.

When the head of the snake hits this, the food is eaten, and the snake becomes one cell
longer. This event increases the score of the player. At the same time, a new piece of food is
placed in a randomly chosen cell somewhere in the field, which was previously clear
(empty).
1.3 About Organisation

Perfect Soft Solutions Private Limited is a Private incorporated on 04 August 2014. It is


classified as non-government company and is registered at Registrar of Companies, Delhi.
The corporate identification number (CIN) of the company is U72900DL2014PTC269844
and the company registration number is 269844. Based on the official records, the current
age of the company is 7 Years 9 Months 15 Days years.

Its authorized share capital is Rs. 100,000 and its paid up capital is Rs. 100,000. It is
involved in other computer related activities [for example maintenance of websites of other
firms/ creation of multimedia presentations for other firms etc.]. The industrial and the SIC
code for PERFECT SOFT SOLUTIONS PRIVATE LIMITED is 72900.

Perfect Soft Solutions Private Limited's Annual General Meeting (AGM) was last held on 30
November 2021 and as per records from Ministry of Corporate Affairs (MCA), its balance
sheet was last filed on 31 March 2021.

Directors of Perfect Soft Solutions Private Limited are Laxman Singh and Sneh Kant
Choudhary.

Perfect Soft Solutions Private Limited's Corporate Identification Number is (CIN)


U72900DL2014PTC269844 and its registration number is 269844. Its Email address is
[email protected] and its registered address is D-13/GL-1 DILSHAD COLONY
DELHI East Delhi DL 110095 IN , - , .

Current status of Perfect Soft Solutions Private Limited is - Active.

LAXMAN KUMAR is the director of this company. The contact details of the company are
as per the official records.
PERFECT SOFT SOLUTIONS PRIVATE LIMITED is a Ministry of Corporate Affairs
(MCA) provider company based on the National Industrial Classification (NIC) code of
72900 and it is involved in the business activities related to this industry code such as other
computer related activities.
2. System Study

2.1 System with limitations

The limitations of present implementation of Snake are:

 The present implementation of Snake can only be played in LAN. Due to large latency
time and bandwidth limitation, it cannot be played over the Internet.
 Path finding algorithms (Blackmamba and Viper) implemented in this game have their
own computation limitations which has been describe in ANNEX A,B.
 Full stress test of the application has not been done yet. Hence, the response of game
server in unpredictable situations cannot be handled properly.
 Snake's Game Server Manager (Snake – GSM) located at http://isnake.sf.net is still in
its early development phase. There are some unresolved security issues.
 The existing system only provides text-based interface, which is not as user-friendly as
Graphical user Interface.

 Since the system is implemented in Manual, so the response is very slow.

 The transactions are executed in off-line mode, hence on-line data capture and
modification is not possible.

 Off-line reports cannot be generated due to batch mode execution.

Hence, there is a need of reformation of the system with more advantages and flexibility. The
Snake Game eliminates most of the limitations of the existing software.
It has the following objectives:

 Enhancement:

The main objective of The Snake Game is to enhance and upgrade the existing system by
increasing its efficiency and effectiveness. The software improves the working methods by
replacing the existing manual system with the computer-based system.

 Automation:

The Snake Game automates each and every activity of the manual system and increases its
throughput. Thus the response time of the system is very less and it works very fast.

 Accuracy:

The Snake Game provides the uses a quick response with very accurate information
regarding the users etc. Any details or system in an accurate manner, as and when required.

 User-Friendly:

The software The Snake Game has a very user-friendly interface. Thus the users will feel
very easy to work on it. The software provides accuracy along with a pleasant interface.
Make the present manual system more interactive, speedy and user friendly.

 Availability:

The transaction reports of the system can be retried as and when required. Thus, there is no
delay in the availability of any information, whatever needed, can be captured very quickly
and easily.

 Maintenance Cost:

Reduce the cost of maintenance.


2.2 Significance of the Project

Snake is the common name for a video game concept where the player manoeuvres a line
which grows in length with the line itself being a primary obstacle. The concept originated in
the 1976 arcade game Blockade and the ease of implementing Snake has led to hundreds of
versions (some of which have the word snake or worm in the title) for many platforms. After
a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest
in the snake concept as it found a larger audience.
It is not the world’s greatest game, but it does give us an idea of what we can achieve with a
relatively simple java swing program and perhaps the basis by which to extend the principles
and create more interesting games of our own.

2.3 Beneficiaries of the System

 Snake is a classic game that requires players to assess their surroundings and find the
quickest or safest route to a point. This is an excellent opportunity to learn about spatial
awareness and plan ahead to your next move.
 The classic game is infamous for using your own success against you when you
become so long that you get in your own way. Whilst many games and activities can
teach your child about vital life skills, there are not many that would educate on long
term strategic planning.
 As many parents will know, it can be extremely frustrating to reach such a high level
and then lose as you crash into your own tail. The game requires patience in order to
grow and a cool head once you inevitably lose. These are all valuable skills to learn
early on in a child’s life that will benefit them in later years.
 Snake is a tool that can be used as an educational helping hand. One of the important
parts of learning is that you will never get something right the first time. Snake teaches
children that practice makes perfect when it comes to learning new skills.
 To reinforce many of the Java and programming concepts you have already met.
 To provide valuable experience of the design and implementation of a large program.
 To provide a framework for a more challenging, and thus rewarding, laboratory
exercise.

Whilst there is no substitute for writing our own programs, watching the development of
another’s is still an extremely effective way of collecting design and programming
experience, particularly as the programs can be a little more challenging than those we would
be able to write ourselves at this stage.
2.4 Feasibility Study

Preliminary investigation examines project feasibility; the likelihood the system will be
useful to the organization. The main objective of the feasibility study is to test the Technical,
Operational and Economical feasibility for adding new modules and debugging old running
system. All systems are feasible if they are given unlimited resources and infinite time. There
are aspects in the feasibility study portion of the preliminary investigation:

 Technical Feasibility
 Operation Feasibility
 Economic Feasibility

TECHNICAL FEASIBILITY

Technical feasibility centre around the existing computer system hardware etc. and to what
extent it can support the proposed addition. For example, if the current computer is operating
at 80% capacity - an arbitrary ceiling – then running another application could over load the
system or require additional hardware. This involves financial consideration to accommodate
technical enhancements. If the budget is a serious constraint, then the project is judged not
feasible.

This study should answer the following questions:

Whether the project can be carried out with the existing equipment’s?
Whether the existing software is enough?
Can the work be done with the existing personnel?
If a new technology is required, how best can it be implemented?

The technical issue usually raised during the feasibility stage of the investigation includes the
following:

 Does the necessary technology exist to do what is suggested?


 Do the proposed equipment’s have the technical capacity to hold the data required to
use the new system?
 Will the proposed system provide adequate response to inquiries, regardless of the
number or location of users?
 Can the system be upgraded if developed?

Are there technical guarantees of accuracy, reliability, ease of access and data security?

OPERATIONAL FEASIBILITY
It is common knowledge that computer installations have something to do with turnover,
transfers, retraining and changes in employee job status. Therefore, it is understandable that
the introduction of a candidate system requisites special efforts to educate, sell, and train the
staff on new ways of conducting business.

 User-friendly:

Customer will use the forms for their various transactions i.e. for adding new routes, viewing
the routes details. Also the Customer wants the reports to view the various transactions based
on the constraints. These forms and reports are generated as user-friendly to the Client.

 Reliability:

The package wills pick-up current transactions on line. Regarding the old transactions, User
will enter them in to the system.

 Security:

The web server and database server should be protected from hacking, virus etc.

 Portability:

The application will be developed using standard open source software (Except Oracle) like
Java, tomcat web server, Internet Explorer Browser etc. This software will work both on
Windows and Linux o/s. Hence portability problems will not arise.

 Availability:

This software will be available always.

 Maintainability:

The system called the wheels uses the 2-tier architecture. The 1st tier is the GUI, which is
said to be front-end and the 2nd tier is the database, which uses My-Sql, which is the back-
end.

The front-end can be run on different systems (clients). The database will be running at the
server. Users access these forms by using the user-ids and the passwords.
ECONOMIC FEASILITY

The computerized system takes care of the present existing system’s data flow and
procedures completely and should generate all the reports of the manual system besides a
host of other management reports.

It should be built as a web based application with separate web server and database server.
This is required as the activities are spread throughout the organization customer wants a
centralized database. Further some of the linked transactions take place in different
locations.

Open source software like TOMCAT, JAVA, MySQL and Linux is used to minimize the
cost for the Customer.

A feasibility study is undertaken to determine the possibility of either improving the existing
system or developing a completely new system. This study helps to obtain an overview of the
problem and to get rough assessment of whether feasible solutions exist. Since the feasibility
study may lead to the commitment of large resources, it is important that it is conducted
completely and that no fundamental errors of judgment are made.

The purpose of feasibility study is to determine whether the requested project is successfully
realizable. There are following aspects of feasibility study, namely

Economic analysis is the most frequently used method for evaluating the effectiveness of a
candidate system. More determine the benefits and the saving that are expressed from a
candidate system and compare them costs. If benefits outweigh costs. Otherwise, further
justification or alterations in the proposed system will have to be made if it is to have a
chance of being approved. This is an ongoing effort that improves in accuracy at each phase
of the system life cycle.

By conducting this study, I can ascertain the following:


Whether the project is economically feasible?

If enough funds are not available, then what are the sources of funds?

Whether there are sufficient benefits when compared to the costs incurred?

CULTURAL (OR POLITICAL) FEASIBILITY

This is related to operational Feasibility. But where operational feasibility deals more with
how well the solution will meet system requirements, cultural/political feasibility deals with
how the end users feel about the proposed system. Operational feasibility evaluates whether a
system can work, and cultural/political feasibility asks whether a system will work in a given
organizational climate.
The following question can be asked by conducting this study:

o Does management support the system?


o How do the end users feel about their role in the new system?
o What end users or managers may resist or not use the system? Can this problem be
overcome? If so, how?
o How will the working environment of the end users change? Can or will end users and
management adapt to the change?

The existing system is manual system where all the work is done manually.
So, this project is a new technology then there is a need to teach about the new Automated
Salary Processing System. The technical feasibility is concerned with specifying equipment
and software that will successfully support the required task.

SCHEDULE FEASIBILITY

Some projects are initiated with specific deadlines. It is necessary to determine whether the
deadlines are mandatory or desirable. For instance, a project to develop a system to meet new
government reporting regulations may have a deadline that coincides with when the new
reports must be initiated. Penalties associated with missing such a deadline may make
meeting it mandatory. If the deadlines are desirable rather than mandatory. If the deadlines
are rather may make meeting it mandatory. If the deadlines are desirable rather than
mandatory, the analyst can propose alternative schedules.

It is preferable (unless the deadline is absolutely mandatory) to deliver a properly functioning


information system two months late than to deliver an error-prone, useless information
system on time! While missing deadlines can be problematic, developing inadequate systems
can be disastrous. It’s a choice between the lesser of two evils.

LEGAL FEASIBILITY

Information systems have a legal impact. First of all, there are copyright restrictions. For any
system that includes purchased components, one has to make sure that the license copies. But
license agreements and copy protection can also restrict how you integrate the data and
processes with other parts of the system.

TIME FEASIBILITY

Time feasibility is a determination of, whether a proposed project can be implemented fully
within a stipulated time frame. If a project takes too much time it is likely to be rejected.
3. System Analysis Requirement Specification

i. Functional Requirement

1. WASD keys for W-Up, A-Left, S-Down, D-Right change the snake's direction.

2. The snake has a velocity in the direction it is moving. That velocity increases with
time.

3. Randomly place power-ups:

a. Slow snake velocity.


b. Food makes the snake longer.
c. Bonus targets gain bonus points.
d. etc.

4. If the sake collides with the snake the round ends and a new round starts.

5. At the end of rounds, the score is registered as the player’s highest if it is better than
any recorded before. The highest registered score is tracked between all players on a
leader board.

6. Log in to identify the player. (Details should include username/password


requirements, is two-factor authentication needed, should obscene words be allowed
as usernames? etc.?)

7. Options menu to set music and sound effects volumes. Colour scheme?

ii. Non Functional Requirement

1. On cutting-edge computers, as of 2010, it should get a 40 FPS refresh rate.

2. The leader board needs to support 9 million concurrent users.

3. The leader board must be updated within 2 min after a new high score is registered
by a play.
iii. User Requirement

GameGUI - This will provide a user interface so that the player can see the snake and the
food, etc., and be able to operate the game via the keyboard. It will also be the driving force
for the game, that is, it shall contain a method to play the game by repeatedly invoking the
move method from the Game class.

iv. System Requirement

HARDWARE REQUIREMENT:

Most of the computer games require high configurations of computer. But in the case of the
proposed gaming system, the system requirements is not that much.

The minimum systems requirements for the proposed project game is mentioned following.

(a) Operating System: Windows 10

(b) Processor: 1.2 GHz

(c) RAM: 512MB

(d) Storage: 100 MB

SOFTWARE REQUIREMENT:

Project Platform: Java


Programming Language: Java
IDE Tools: JDK
4. System Design

a) Data Flow Diagram


START

INITIAL GAME

MOVING

NO
MEET
FOOD?

YES

NODE INCREMENTED
FOOD GENERATED

KEY PROTECTION &


DELAY FOR MOVING

YES NO
GAME
OVER?
b) E-R Diagram
START

ENTER THE MAIN MENU OF SNAKE

FROM ANY
ONE OF
THESE

ENTER NAME PLAY GAME QUIT

DO YOU
WANT TO
CONTINUE?

STOP
c) Flow Chart
START

KEYPRESS
NO

NO
ARROW ESC
KEY? KEY?

YES YES

CALCULATE NEW
POSITION END

ADD
POSITION TO
SNAKE

NO

COLLISION

YES
d) Input Output Forms
5. Development

a) Environment

We used several open source tools to develop this project:

● Netbeans 5.5 IDE


All the developers of iSnake team used Netbeans IDE for the development of this project.

● Inkscape 0.45 and Gimp 2.2


These graphics development tools were extensively used for the development of User
Interface components. The illustrations presented in this report have also been prepared
using these open source tools.

● Gnuplot
The data obtained during profiling of two path finding algorithms viz. Blackmamba and
Viper was plotted using gnuplot.

● OpenOffice Writer 2.2


All the project documents and this report were prepared using OpenOffice Writer 2.2.

● Wireshark Network Traffic Analyzer 0.99.6


During the development of iSnake Game Server Manager (GSM) @ SF.net, Wireshark
tool was used to analyze the network traffic.
b) Coding Style

SNAKE

A Snake Class for the snake. We want to


--> Know and maintain the size of the snake.
--> The ability to control movement of the Snake
--> Check whether it did not hit a Wall.

So it shall contain the following functions:

 A constructor to initialise the snake with its head.


 A function to grow the size of the snake.
 A function for the snake to move.
 A function to check if the snake has crashed.
 A function that returns the snake
 A function to set values in the snake.
 A function that returns the head of the snake.
 A function to set the head of the snake.

CELL

While food seemed intuitive to me while thinking, cell feels intuitive to me for working!

Why so?
Our boards, consistes of various cells, A cell at random will be proclaimed as the cell
containing food. The identify of food is random, but identity of cell is meaningful, so I would
rather make a class Cell than food.

Cells are also important to kep track of position of the snake!


Each cell is thereby contains the information about

--> Its Row

--> Its Column

--> Whether it contains food or not?


--> Whether it is a part of the snake or not?

Hence its member functions include

 A constructor to initialise it.


 A function that specifies its type (contains food etc.)
 A function that returns its type.
 A function to return its row.
 A function to return its column.

BOARD

It is the set of valid points for the game to function on, qualitatively a matrix of cells.
While the cells revert to the questions, being the collection and home of cells, the board
needs to ensure the cells get satisfiable answers.

Whether it contains food or not?


We need to assign food to some random cell as well. This is attributed to the board, as the
cell doesn't choose whether it shall contain food, the board is acquainted with the cells it
contains and hence should empowered to assign a cell to contain food.

Whether it is a part of the snake or not?


This is answered by the Snake class we described above. While food is an attribute of the
board, movement is an attribute of the snake! Hence it is wise to let the Snake class contain
method pertaining to the Snake's movement.

It will contain the following functions

 A constructor to initialise the board with number of rows and columns.


 A function to return its cells.
 A function to set values in its cells.
 A function to generate Food.
GAME

This is the meaty part of the code, our primary logic, the game!

It needs an instance of

 Board
 Game

Notice how Board already contains instances of Cell.

This also needs to contain the following


--> Ability and logic to use the classes we make and conduct a game!
--> Know when the game is over

So the following functions will be required:

 A constructor to initialise the game with a snake and a board.


 A function to return the snake.
 A function to set the value of snake.
 A function to return the board.
 A function to set the value of board
 A function to set the game to be over.
 A function to check if the game is over.
 A function to set the direction of snake's motion.
 A function to return the direction of snake's motion.
 A function to update the game according to snake's movement.
 A function to keep track of the forthcoming cell.
After this we will also define a main function to actually play the game.
c) Coding

CELL
The most basic element, we only need private data members as discussed and public methods
to set and retrieve them.

public class Cell


{
private final int row, col;
private CellType cellType;

public Cell(int row, int col)

{
this.row = row;
this.col = col;
}

public CellType getCellType()

{
return cellType;
}

public void setCellType(CellType cellType)

{
this.cellType = cellType;
}
public int getRow();

{
return row;
}

public int getCol()

{
return col;
}

BOARD
For the board, it must contain a 2-Dimensional array of cells, which we need to initialise in
its constructor. Thereby it is meaningful to maintain
the ROW_COUNT and COL_COUNT for a board, which shall be passed to the constructor.
We also need a method to randomly designate a cell as Food along with some methods to set
and retrieve cells.

Board.java

package com.zetcode;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener


{

private final int B_WIDTH = 300;


private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;

private final int x[] = new int[ALL_DOTS];


private final int y[] = new int[ALL_DOTS];

private int dots;


private int apple_x;
private int apple_y;

private boolean leftDirection = false;


private boolean rightDirection = true;
private boolean upDirection = false;

private boolean downDirection = false;


private boolean inGame = true;

private Timer timer;


private Image ball;
private Image apple;
private Image head;

public Board()
{

initBoard();
}

private void initBoard()


{

addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);

setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));


loadImages();

initGame();
}

private void loadImages()


{

ImageIcon iid = new ImageIcon("src/resources/dot.png");


ball = iid.getImage();

ImageIcon iia = new ImageIcon("src/resources/apple.png");


apple = iia.getImage();

ImageIcon iih = new ImageIcon("src/resources/head.png");


head = iih.getImage();
}

private void initGame()


{

dots = 3;

for (int z = 0; z < dots; z++)


{
x[z] = 50 - z * 10;
y[z] = 50;
}

locateApple();
timer = new Timer(DELAY, this);
timer.start();
}

@Override
public void paintComponent(Graphics g)

{
super.paintComponent(g);

doDrawing(g);
}

private void doDrawing(Graphics g)


{

if (inGame)
{

g.drawImage(apple, apple_x, apple_y, this);

for (int z = 0; z < dots; z++)


{
if (z == 0)
{
g.drawImage(head, x[z], y[z], this);
}
else
{
g.drawImage(ball, x[z], y[z], this);
}
}

Toolkit.getDefaultToolkit().sync();

}
else
{

gameOver(g);
}
}

private void gameOver(Graphics g)


{

String msg = "Game Over";


Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);

g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
private void checkApple()
{

if ((x[0] == apple_x) && (y[0] == apple_y))


{

dots++;
locateApple();
}

private void move()


{

for (int z = dots; z > 0; z--)


{
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}

if (leftDirection)
{
x[0] -= DOT_SIZE;
}

if (rightDirection)
{
x[0] += DOT_SIZE;
}

if (upDirection)
{
y[0] -= DOT_SIZE;
}

if (downDirection)
{

y[0] += DOT_SIZE;
}
}

private void checkCollision()


{

for (int z = dots; z > 0; z--)


{

if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z]))


{
inGame = false;
}
}
if (y[0] >= B_HEIGHT)
{
inGame = false;
}

if (y[0] < 0)
{
inGame = false;
}

if (x[0] >= B_WIDTH)


{

inGame = false;
}

if (x[0] < 0)
{
inGame = false;
}

if (!inGame)
{
timer.stop();
}
}
private void locateApple()
{

int r = (int) (Math.random() * RAND_POS);


apple_x = ((r * DOT_SIZE));

r = (int) (Math.random() * RAND_POS);


apple_y = ((r * DOT_SIZE));
}

@Override
public void actionPerformed(ActionEvent e)
{

if (inGame)

checkApple();
checkCollision();
move();
}

repaint();
}
private class TAdapter extends KeyAdapter
{

@Override
public void keyPressed(KeyEvent e)
{

int key = e.getKeyCode();

if ((key == KeyEvent.VK_LEFT) && (!rightDirection))


{
leftDirection = true;
upDirection = false;
downDirection = false;
}

if ((key == KeyEvent.VK_RIGHT) && (!leftDirection))

{
rightDirection = true;
upDirection = false;
downDirection = false;
}

if ((key == KeyEvent.VK_UP) && (!downDirection))


{
upDirection = true;
rightDirection = false;
leftDirection = false;
}

if ((key == KeyEvent.VK_DOWN) && (!upDirection))


{
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}

First we will define the constants used in our game.


private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;

private final int DELAY = 140;


The B_WIDTH and B_HEIGHT constants determine the size of the board.
The DOT_SIZE is the size of the apple and the dot of the snake. The ALL_DOTS constant
defines the maximum number of possible dots on the board (900 = (300*300)/(10*10)).
The RAND_POS constant is used to calculate a random position for an apple.
The DELAY constant determines the speed of the game.

private final int x[] = new int[ALL_DOTS];


private final int y[] = new int[ALL_DOTS];
These two arrays store the x and y coordinates of all joints of a snake.
private void loadImages()
{

ImageIcon iid = new ImageIcon("src/resources/dot.png");


ball = iid.getImage();

ImageIcon iia = new ImageIcon("src/resources/apple.png");


apple = iia.getImage();

ImageIcon iih = new ImageIcon("src/resources/head.png");


head = iih.getImage();
}
In the loadImages() method we get the images for the game. The ImageIcon class is used for
displaying PNG images.
private void initGame()
{

dots = 3;

for (int z = 0; z < dots; z++)

{
x[z] = 50 - z * 10;
y[z] = 50;
}

locateApple();
timer = new Timer(DELAY, this);
timer.start();
}

In the initGame() method we create the snake, randomly locate an apple on the board, and
start the timer.
private void checkApple()
{

if ((x[0] == apple_x) && (y[0] == apple_y))


{

dots++;
locateApple();
}
}
If the apple collides with the head, we increase the number of joints of the snake. We call
the locateApple() method which randomly positions a new apple object.
In the move() method we have the key algorithm of the game. To understand it, look at how
the snake is moving. We control the head of the snake. We can change its direction with the
cursor keys. The rest of the joints move one position up the chain. The second joint moves
where the first was, the third joint where the second was etc.
for (int z = dots; z > 0; z--)

{
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
This code moves the joints up the chain.
if (leftDirection)
{
x[0] -= DOT_SIZE;
}
This line moves the head to the left.
In the checkCollision() method, we determine if the snake has hit itself or one of the walls.
for (int z = dots; z > 0; z--)
{

if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z]))


{
inGame = false;
}
}

If the snake hits one of its joints with its head the game is over.
if (y[0] >= B_HEIGHT)
{
inGame = false;
}
The game is finished if the snake hits the bottom of the board.

SNAKE

We will be representing the snake with a Linked List, that is because it has O(1) insertion,
which helps us increase the size of the snake at the pace of the game!
We need to add elements at the tail and retrieve position with the head.
This is a FIFO approach, i.e. represented by a Queue that we are implementing with a Linked
List.
We need to create methods for
Movement of snake i.e. incrementing the position in the direction of movements.
Check crashes i.e. if snake comes in contact with any prohibited cell, it shall declare a
crash!

// To represent a snake
import java.util.LinkedList;

public class Snake


{

private LinkedList<Cell> snakePartList = new LinkedList<>();


private Cell head;

public Snake(Cell initPos)


{
head = initPos;
snakePartList.add(head);
}

public void grow()


{
snakePartList.add(head);
}

public void move(Cell nextCell)


{
System.out.println("Snake is moving to " +
nextCell.getRow() + " " + nextCell.getCol());
Cell tail = snakePartList.removeLast();
tail.setCellType(CellType.EMPTY);

head = nextCell;
snakePartList.addFirst(head);
}

public boolean checkCrash(Cell nextCell)


{
System.out.println("Going to check for Crash");
for (Cell cell : snakePartList)
{
if (cell == nextCell)
{
return true;
}
}

return false;
}

public LinkedList<Cell> getSnakePartList()


{
return snakePartList;
}

public void setSnakePartList(LinkedList<Cell> snakePartList)


{
this.snakePartList = snakePartList;
}

public Cell getHead()


{
return head;
}

public void setHead(Cell head)


{
this.head = head;
}
}

GAME

Credits to the classes we've made so far the forthcoming section is actually surprisingly easy!
We need a class Game, which contains data members to take care of the snake and the board.
We need a set of fixed directions for movement, and a direction member to determine
movement.
Along with a boolean to check for the game to be over!
We need methods to initialise and receive the values.
We need to ensure that the game is updated as per the user, i.e. actually calling the functions
for moving the snake, getting the food etc.
One characteristic is that, even though direction of movement is somewhat characteristic to
the snake, the position is actually attributed to the cell, which is a part of the board. Since we
have the snake as well as access to current values here, and have also added direction
members here, it seems right to and modular to maintain directions here.
A function to update the direction here itself.
// To represent Snake Game
public class Game
{

public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1,


DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2;
private Snake snake;
private Board board;
private int direction;
private boolean gameOver;

public Game(Snake snake, Board board)


{
this.snake = snake;
this.board = board;
}

public Snake getSnake()


{
return snake;
}

public void setSnake(Snake snake)


{
this.snake = snake;
}

public Board getBoard()


{
return board;
}

public void setBoard(Board board)


{
this.board = board;
}

public boolean isGameOver()


{
return gameOver;
}

public void setGameOver(boolean gameOver)


{
this.gameOver = gameOver;
}

public int getDirection()


{
return direction;
}

public void setDirection(int direction)


{
this.direction = direction;
}

// We need to update the game at regular intervals,


// and accept user input from the Keyboard.
public void update()
{
System.out.println("Going to update the game");
if (!gameOver)
{
if (direction != DIRECTION_NONE)
{
Cell nextCell = getNextCell(snake.getHead());

if (snake.checkCrash(nextCell))
{
setDirection(DIRECTION_NONE);
gameOver = true;
}
else
{
snake.move(nextCell);
if (nextCell.getCellType() == CellType.FOOD)
{
snake.grow();
board.generateFood();
}
}
}
}
}

private Cell getNextCell(Cell currentPosition)


{
System.out.println("Going to find next cell");
int row = currentPosition.getRow();
int col = currentPosition.getCol();

if (direction == DIRECTION_RIGHT)
{
col++;
}
else if (direction == DIRECTION_LEFT)
{
col--;
}
else if (direction == DIRECTION_UP)
{
row--;
}
else if (direction == DIRECTION_DOWN)
{
row++;
}

Cell nextCell = board.getCells()[row][col];

return nextCell;
}

public static void main(String[] args)


{
System.out.println("Going to start game");

Cell initPos = new Cell(0, 0);


Snake initSnake = new Snake(initPos);
Board board = new Board(10, 10);
Game newGame = new Game(initSnake, board);
newGame.gameOver = false;
newGame.direction = DIRECTION_RIGHT;

// We need to update the game at regular intervals,


// and accept user input from the Keyboard.

// here I have just called the different methods


// to show the functionality
for (int i = 0; i < 5; i++) {
if (i == 2)
newGame.board.generateFood();
newGame.update();
if (i == 3)
newGame.direction = DIRECTION_RIGHT;
if (newGame.gameOver == true)
break;
}
}
}
6. Testing

a. Test Cases

Test Planning:
Like any project, the testing also should be driven by a plan. The test plan generates the
report for the execution and tracking of the entire testing project.

Preparing the test plan


What needs to be the tested-the scope of testing, including clear identification of what will be
the tested & what will not be tested.
How the testing is going to be performed – breaking down the testing into small and
manageable tasks and identifying the strategies to be used for carrying out the tasks.
Resource needed for testing
The timelines by which the testing activities will be performed.
Risks that may be faced in all of the above, with appropriate mitigation and contingency
plans.

Test Case Specification:


Using the test plan as the basis, the testing team design test case specification which then
becomes the basis for preparing for individual test cases.
A test case is nothing but a series of step executed on a product, using a predefined set of
input data, expected to produce a pre-defined set of outputs, in a given environment.
It describes “how” to implement those test cases
Test case specifications are useful as it enlists the specification details of the items.
Details of each Specification:

Test Case
Specification Description

Test Case Unique ID to identify/report the bug if present in the functionality of


ID(TC_ID) software

The purpose of the test. The lists can be generated to perform intended
Test Case task, for which software is developed. Results should always follow the
Objective test case objective

This can include environment setup, supporting software environment


setup. for the project, or any fields in which user will give the input. So
Pre-requisite that test cases can be planned accordingly.

This includes steps to be performed to give the input to the system, so


that system can perform its specified task and display the result
accordingly. If automated testing is used, then, these steps are translated
Steps to the scripting language of the tool.

The choice of input data will be depended on the test case itself and the
technique followed in the test case.
Input Data For e.g. equivalence partitioning, boundary value analysis etc.

Expected
Result It can be the user required output to be shown

This step should do a comparison of the expected and actual results to


Actual Result highlight any differences.

Whether expected results and actual result match, if it matches then


Status PASS or else FAIL
7. System Security

a. Checks and Control

We control the head of the snake by using the cursor keys.


Clicking the left arrow key change the direction of the head to point East, Left to West, Up to
North and Down to South.
The head keeps moving in the same direction until an arrow key is clicked to change its
direction.

b. Encryption, secure

1. Authentication and Authorization


When it comes to security the most fundamental concepts are Authentication and
Authorization. Unless we have a strong reason we should be following a widely accepted
framework for this purpose. We have Java EE Authentication and Spring Security to help us
out in this context. I have worked with spring security in the past and it can be customized to
suit your specific needs.

2. Security in the Web Layer


In our application stack, the web layer is most vulnerable to attacks. We have
many established standard practices and detection mechanisms to minimize these
risks. OWASP Top 10 list is a must have a checkpoint for security checks. The Open Web
Application Security Project (OWASP) mission is to make software security visible so that
individuals and organizations worldwide can make informed decisions about true software
security risks.
3. API Security
With the rise of mobile applications and stronger browsers expressing functionalities using
the API is more popular day by day. We need to follow the same security practices for the
web layer. All the API requests should be authenticated and we should use the principle of
least privilege. I found the presentation from Greg Patton in the AppSec EU15 titled The API
Assessment Primer is a great start for API security validations. Two major points focused in
his talk are,

Do not expose any operations that are not needed


Do not expose any data that is not required

Which is in line with the basic security principle of giving least privilege by default.
To authenticate the services, we can create simple token-based API authentication
mechanism based OAuth2 standards. If the services expose any sensitive data, it is better to
use https so that man-in-the-middle attacks can be avoided.

4. Validating the User Input


Be aware that any JavaScript input validation performed on the client can be bypassed by an
attacker that disables JavaScript or uses a Web Proxy. Ensure that any input validation
performed on the client is also performed on the server. Go through
the OWASP and WASC checklist to identify the potential validations you need to do in our
application.
8. Conclusion/ Future Enhancement

Apart from the class we will write, we have now completed the development of our program.
It consists of a total of 10 classes plus the one you will write. Ignoring comments and
documentation in the code, those 10 classes consists of around 1300 lines of spaced out code.
My sample answer for the part you will write, including the optional extras, consists of
approximately 500 lines, making a total of approximately 1800 lines. Before we finish, we
ought to say something about the order of development we saw here.
The choice we made, of considering the classes in a bottom up order, was more motivated by
the wish for you to be able to follow it, than a realistic reconstruction of a real development
experience.
In reality, when we develop programs, we usually have to work on several classes at once.
So, for example, if we try to follow a bottom up order after having had a top down high level
analysis, we typically need to go back to classes we have already developed in order to add
new features or modify existing ones, as we traverse up the dependencies towards the top.
This is less necessary in the top down development approach, but instead we initially need to
make stubs of our lower level classes.
Finally, we should address an obvious question, which you may well have been already
asking yourself. Why did we not divide the Game class into separate classes such as, Field,
Food, Tree, Game, Snake, and so on?
The short answer is this: we are the one that will be looking at that part of the program, in
your laboratory exercise! However, in that exercise we are requested to develop the Game
class without dividing it up, and then ask ourselves whether it would be a good idea to, and
what are the pros and cons.

 Port Snake to cell phone platform and One Laptop Per Child – OLPC (which uses Sugar
Desktop environment). The presence of several connectivity options(Bluetooth, WIFI,
GPRS, CDMA) in cell phones makes it a very attractive platform for a multiplayer game
like iSnake. Local WIFI network formed by kids using OLPC laptops can be used as a
platform for Snake's deployment.

 As Snake game server communicates with remote playing using a well-defined and very
simple protocol (Refer to ANNEX D), iSnake clients programmed in other
programming platform like Flash, Python, etc. can be developed.
9. Bibliography

1. https://zetcode.com/javagames/snake/

2. https://iq.opengenus.org/snake-game-java/

3. You Tube

You might also like