Snake Game Report
Snake Game Report
A
MINOR PROJECT REPORT
ON
“SNAKE GAME”
BACHELOR OF TECHNOLOGY
in
COMPUTER SCIENCE & ENGINEERING
(IBM BIG DATA ANALYTICS)
SUBMITTED BY
Kuldeep Sharma
A40219010
Batch: 2019-2023
PROJECT GUIDE
Dr. Nishika
(Asst. Professor, Department of CSE)
CERTIFICATE OF COMPLETION
This is to certify that the Project work entitled “Snake Game” submitted by
Kuldeep Sharma in fulfillment for the requirements of the award of
Bachelor of Technology Degree in Computer Science & Engineering at
PDMU, Bahadurgarh, Haryana is an authentic work carried out by him
under my supervision and guidance. To the best of my knowledge, the
matter embodied in the project has not been submitted to any other
University Institute for the award of any Degree.
Dr. Nishika
A.P. in CSE Department
Faculty of Engineering & Technology
(i)
I hereby declare that the work presented in this report entitled “Snake
Game”, in fulfilment of the requirement for the award of the degree
Bachelor of Technology in Computer Science & Engineering, submitted in
CSE Department, PDMU, Bahadurgarh, Haryana is an authentic record of
my own work carried out during our degree under the guidance of Dr.
Nishika.
The work reported in this has not been submitted by me for award of any
other degree or diploma.
Place: A40219010
(ii)
ACKNOWLEDGEMENT
KULDEEP SHARMA
A40219010
ABSTRACT
The project consists of designing of Snake Game in which we create and modify the
text file formats. It contains basic required options or features by which we can edit or
modify the text files .
Most of the tools that we have designed are made using the features of the awt
(abstract window toolkit) package in java ( java.awt.*) and Swing . The main impact
of Snake Game is the interaction with the user of the program via peripheral devices
like keyboard, mouse, etc. This thing is done through the Event Handling of various
mouse + windows events with the help of their proper event classes present in the java.
event.* package.
Contents
CERTIFICATE OF COMPLETETION..................................................(i)
DECLARATION BY THE CANDIDATE..........................................................(ii)
ACKNOWLEDGEMENT…................................................................................(iii)
ABSTRACT….......................................................................................................(iv)
LIST OF FIGURES...............................................................................................(viii-ix)
LIST OF TABLES.................................................................................................(x)
LIST OF ABBREVIATIONS...............................................................................(xi)
CHAPTER 1: INTRODUCTION.............................................................................. 1
1.1 About Project…..................................................................................................... 1
1.2 Learning outcomes…..............................................................................................1
1.3 Description of the game.........................................................................................1
CHAPTER 2:Introduction to Java...........................................................................2
2.1 History.................................................................................................................... 2
2.2 Java programming language is named Java.Why?..............................................2-3
2.3 Java Terminology…...........................................................................................3-4
2.4 Primary/Main Features of Java...........................................................................4-5
2.5 Introduction to Swing.........................................................................................6-7
2.5.1 Features of swing Class................................................................................7
2.5.2 Swing Classes Hierarchy..............................................................................7
2.5.3 The MVC Connection...................................................................................8
2.5.4 Components of Swing Class....................................................................8-10
2.5.5 Java Action Listener..............................................................................10-11
2.5.6 Java Swing Element...............................................................................11-18
CHAPTER 3: SOFTWARE REQUIREMENTS..............................................19-20
3.1 Introduction........................................................................................................ 19
3.2 Technology Specific requirements…...................................................................19
3.2.1 Hardware Requirements…....................................................................19
3.2.2 Software Requirements….................................................................... 20
CHAPTER 4: DESIGN MODULES.......................................................................20-23
CHAPTER-1
Introduction
1. About Project
This case study presents much of the development of a program to play a snake game, similar to that
found on certain old mobile phones. The core game playing functionality is actually left as a staged
laboratory exercise.
• 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 your 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 you would be able to
write yourself at this stage.(Caveat: this is only true for case studies that you are not supposed
to be doing yourself – watching someone else develop code that you are supposed to be doing
on your own is disastrous for your learning!)
How much you get from this case study depends on how much you put in. Ideally you should
carefully follow every part of it and check your depth of understanding at every opportunity.
All confusions or misunderstandings which it may reveal must be dealt with immediately.
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).
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
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 count down
reaches zero, it has escaped death.
The game offers a single ‘about’ and ‘help’ box, popped up and down by pressing ‘h’.
Figure 1: A screen dump of a game. The optional extra feature of a gutter trail is visible behind
the snake.
CHAPTER-2
Introduction to Java
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later acquired by
Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular programs.
2.1 History
Java’s history is very interesting. It is a programming language created in 1991. James Gosling,
Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms.
In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but
it soon withdrew from the process. At one time, Sun made most of its Java implementations
available without charge, despite their proprietary software status. Sun generated revenue
from Java through the selling of licenses for specialized products such as the Java Enterprise
System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-source
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code available
under open-source distribution terms.
The principles for creating java were simple, robust, secured, high performance, portable,
multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by James Gosling, who
is known as the Father of Java. Currently, Java is used in mobile devices, internet
programming, games, e-business, etc.
After the name OAK, the team decided to give a new name to it and the suggested words
were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and fun to
say, but they all wanted the name to reflect the essence of technology. In accordance with
James Gosling, Java the among the top names along with Silk, and since java was a unique
name so most of them preferred it.
Java is the name of an island in Indonesia where the first coffee (named java coffee) was
produced. And this name was chosen by James Gosling while having coffee near his office.
Note that Java is just a name, not an acronym .
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three
execution phases of a program. They are written, compile and run the program.
3. Java Development Kit(JDK): While we were using the term JDK when we learn about
bytecode and JVM. So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java
docs, etc. For the program to execute in java, we need to install JDK on our computer in order
to create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers
allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM,
applet supports, and plugins. For running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect
that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect
the objects that are not referenced. So Java makes the life of a programmer easy by handling
memory management. However, programmers should be careful about their code whether
they are using objects that have been used for a long time. Because Garbage cannot recover
the memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look
for .class files to load. By default, JDK provides many libraries. If you want to include external
libraries they should be added to the classpath.
1. Platform Independent : Compiler converts source code to bytecode and then the JVM
executes the bytecode generated by the compiler. This bytecode can run on any platform
be it Windows, Linux, macOS which means if we compile a program on Windows, then we
can run it on Linux and vice versa. Each operating system has a different JVM, but the
output produced by all the OS is the same after the execution of bytecode. That is why we
call java a platform-independent language.
3. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, Explicit memory allocation.
4. Robust: Java language is robust which means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible, that is why the java compiler is
able to detect even those errors that are not easy to detect by another programming
language. The main features of java that make it robust are garbage collection, Exception
Handling, and memory allocation .
5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java.
8. Portable: As we know, java code written on one machine can be run on another machine.
The platform-independent feature of java in which its platform-independent bytecode can
be taken to any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces overhead
during the runtime and at some time java uses Just In Time (JIT) compiler where the
compiler compiles code on-demand basics where it only compiles those methods that are
called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add
classes, new methods to existing classes and even create new classes through sub-classes.
Java even supports functions written in other languages such as C, C++ which are referred
to as native methods.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute
their applications without affecting the underlying system with help of a bytecode verifier.
Bytecode verifier also provides additional security as its role is to check the code for any
violation of access.
12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file
which corresponds to our applications(program) but contains code in binary format. It
provides ease t architecture-neutral ease as bytecode is not dependent on any machine
architecture. It is the primary reason java is used in the enterprising IT industry globally
worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose
either they are compiled language or they are interpreted language. But java integrates
arising enormous power as Java compiler compiles the source code to bytecode and JVM
executes this bytecode to machine OS-dependent executable code.
Swing is a Java Foundation Classes JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Swing offers much-improved functionality over AWT, new components, expanded components
features, excellent event handling with drag and drop support.
Swing has about four times the number of User Interface [U1] components as AWT and is part of the
standard Java distribution. By today’s application GUI requirements, AWT is a limited implementation,
not quite capable of providing the components required for developing complex GUI’s required in
modern commercial applications. The AWT component set has quite a few bugs and really does take
up a lot of system resources when compared to equivalent Swing resources. Netscape introduced its
Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
Many programmers think that JFC and Swing is one and the same thing, but that is not so.
JFC contains Swing [A UI component package] and quite a number of other items:
The simplest Swing components have capabilities far beyond AWT components as follows:
Swing buttons and the labels can be displaying images instead of or in addition to
text
The borders around most Swing components can be changed easily. For example: it
is easy to put a 1 pixel border around the outside of a Swing label
Table 1.1:
Class Description
A Component is the Abstract base class for about the non menu user-
interface controls of SWING. Components are represents an object
Component with graphical representation
Class Description
A JList component represents the user with the scrolling list of text
JList items
A JTextField object is a text component that will allow for the editing of
JTextField a single line of text
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users
Class Description
JProgressBar As the task progresses towards completion, the progress bar displays
the tasks percentage on its completion
A JSpinner this class is a single line input where the field that lets the
user select by using a number or an object value from an ordered
JSpinner sequence
The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:
component.addActionListener(instanceOfListenerclass);
3. JTextArea(int row, int column) : constructs a new text area with a given
number of rows and columns.
1. append(String s) : appends the given string to the text of the text area.
Constructors :
1. add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu
bar.
2. add(Component c) : Add component to the end of JMenu
3. add(Component c, int index) : Add component to the specified index of
JMenu
JList is part of Java Swing package . JList is a component that displays a set of
Objects and allows the user to select one or more items . JList inherits
JComponent class. JList is a easy way to display an array of Vectors .
“Look” refers to the appearance of GUI widgets and “feel” refers to the way the
widgets behave.
Sun’s JRE provides the following L&Fs:
In this article, we’ll see how to make frames using Swings in Java.
Methods
Constructors
JFrame(): It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc): It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank title.
JFrame(String title): It creates a new, initially invisible Frame with the
specified title.
1. ERROR_MESSAGE
2. WARNING_MESSAGE
3. QUESTION_MESSAGE
4. INFORMATION_MESSAGE
Methods Used :
CHAPTER 3
SOFTWARE REQUIREMENTS AND
SYSTEM SPECIFICATIONS
3.1 INTRODUCTION
A Software Requirements Specification (SRS) is a complete description of the behaviour
of the system to be developed. It fully describes what the software will do and how it will be
expected to perform. It includes a set of use cases that describe all the interactions the users will
have with the software. Use cases are also known as functional requirements. In addition to use
cases, the SRS also contains non-functional (or supplementary) requirements. Non- functional
requirements are requirements which impose constraints on the design or implementation (such
as performance engineering requirements, quality standards, or design constraints).
An SRS minimizes the time and effort required by developers to achieve desired goals and also
minimizes the development cost. A good SRS defines how an application will interact with
system hardware, other programs and human users in a wide variety of real-world situations.
Parameters such as operating speed, response time, availability, portability, maintainability,
footprint, security and speed of recovery from adverse events are evaluated.
1. NetBeans IDE
CHAPTER-4
DESIGN MODULES
4.1 Steps of Creation Design
CHAPTER -5
Implementation
5.1: The classes of the program
As is usual in the object oriented approach, the program will be developed as a number of
separate classes. Identifying the appropriate classes of a program is really an art which can
slowly be learned from experience. And like the result of any art, the quality of any choice of
classes is subjective (although most people will agree there are many more bad choices then
good ones!).
By thinking about our understanding of the game, we can form a list of classes which will
appear in the program.
Class Description
Cell The game grid is made up of cells. Each cell has a type and a number of
attributes. For example, a cell could be clear, or it could be a snake head
facing in a particular direction, etc..
Direction The snake in the game moves in one of four directions. This non-instantiable
class provides those four directions, and various methods to manipulate them
(such as obtaining the opposite of a direction).
Game This is the main behaviour of the game play. Its primary purpose is to provide
a method for making one move of the game.
We will also require some other classes to support the operating framework, including the
following.
Class Description
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.
Class Description
Snake This is the top level class, containing only the main method. This shall simply
create an instance of GameGUI, invoke its game playing method and print out
the score once the game has finished.
The laboratory exercise associated with this case study will involve you creating the Game
class, without needing to change the other classes of the program.
The rest of the program offers flexibility for you to implement optional extra features. This
flexibility is achieved by two mechanisms. 1) any key presses not recognised by the GameGUI
class are passed directly to a method called optionalExtraInterface() in the Game
class. 2) a large number of additional values of cell are available in the Cell class. These all
appear as different shades of the field background colour.
Particular suggested optional extras are as follows. 1) Make the food be able to move by itself
and run away from the snake. 2) Make the snake be able to leave grass or gutter trails behind
it, which the food cannot move across but which fade slowly away. 3) Make the snake have the
ability to blast away a tree just in front of it.
You can also think of your own extras, such as an auto-play demonstration mode, where the
snake steers itself, or having two snakes with the user switching control between them.
In this case study, we shall develop the program incrementally, class by class in a bottom-up
manner, that is, we shall attempt to fully design and implement each class before designing
any class which we think will need it. One reason for developing in this order is that it will
be easier for you to follow the discussion. Identifying the dependency relationships between
classes before they are designed is not easy, but the ability comes with experience. We obtain
them by thinking very abstractly about the classes from the main class downwards, i.e. in a
top-down manner.
Here is the list of classes we have identified so far: Cell, Direction, Game, GameGUI,
SpeedController, AboutBox, and Snake.
Snake will be the top level, it will create a GameGUI and invoke its playGame() method.
So, the main method will contain a code fragment something like the following.
A GameGUI will also interpret the key presses from the player, and invoke the appropriate
methods: e.g, to get the SpeedController to change speed or pause and resume; to create
and show the AboutBox, to change the direction of the snake in the Game, etc..
A Game will primarily offer the method move(). This will cause the game to change state,
progressing by one move. The new state will depend on the settings of the old state. Where
is the head of the snake? What direction is it facing? Where is the food? Etc.. There will
also be a method setSnakeDirection() which will be called from the GameGUI when
the player presses one of the arrow keys. There will be other methods too, such as
getScore(), cheat() and toggleTrees(). The state of the game will be represented by
a number of instance variables, the most obvious one being a 2-dimensional array of Cells to
make up the field.
A Cell will store information, such as is there a piece of snake in the cell? If so, what direction
is it facing? Or, is there a piece of food here? Or a tree? Etc.. It will have accessor methods
to access and mutator methods to mutate the information it stores, so the state of a cell can be
seen and changed.
The Direction class will be non-instantiable, it will simply provide 4 directions, and some
useful methods to manipulate them. For example, the method xDelta() will return what
value you need to add to an x coordinate, if you want to make a movement in a certain direction
given as its argument. (The amount returned will be -1, 0 or 1.) This combined with the
similar yDelta() will make the new position of the head of the snake easy to compute from
the direction it is facing.
An AboutBox will simply pop up to display some text given to it when it is created, and
provide a dismiss button to make it go away. This will be used to provide some help to the
player.
• Snake is the top level class. This will build an instance of GameGUI.
• Game will require Cell for the field of cells and Direction for the direction of the
snake.
• Cell will require Direction so it can store which direction the pieces of snake are
facing.
• Direction will not require any other of these classes.
So, we plan to develop the classes in the following order: Direction, Cell, Game,
SpeedController, AboutBox, GameGUI, and finally Snake.
In general, programs have some kind of behaviour and an interface connecting the behaviour
to the outside world. The behaviour is often referred to as the model, as it is this that must
implement the real world functionality required of the program.
The interface to a program can be divided into two categories: output and input, often referred
to as view and control, respectively.
There is much debate in the O.O. world about these three functions of a program. The so-called
M.V.C. argument (standing for model, view and control) suggests there is much to be gained
by separating the 3 functions into different classes in the final program. On the other hand,
some people prefer to combine them – there are no hard and fast rules.
Perhaps the main reason for separating the parts is that it more easily allows certain parts to
be changed without affecting the others. For example, somebody might find a better way of
modelling the real world requirements, but is quite happy with the existing user interface. Or
someone might make a better interface for an existing program which is otherwise quite
acceptable.
The inherent flexibility can be exploited from the initial design too. For example,
a program might have a number of different interfaces to support different operating
environments, whilst having only one model part. Perhaps the most obvious examples are those
programs which have both a text and a graphical interface.
The most persuasive argument for separating the model from the other two parts in a learning
environment is that it permits us to study quite complex programs long before we need to
discover the details of complex graphical user interfaces: we can simply hide the specifics of
the control and view parts of the program at this point in time.
Once we separate the model from the view and control, we need to find a way to link them
together so that they work properly. For example, the user pressing a button in a control object
needs to cause something to happen in a model object, and then whatever state change that
results in must be shown by a view object.
There are various strategies for keeping track of the relationship between corresponding
instances of these classes, and we shall not attempt to describe them all here. There is no best
way to do it for all cases, and there are alternative approaches within the context of a single
program. One of the factors affecting the choice is whether a model object can have more than
one associated instance of a view or control object, or vice versa. In some programs, there is a
one to one correspondence, but in others we might wish to have more than one view and control
objects for one model object, and sometimes we might wish to have no view objects, etc..
Less commonly, we might wish to have an instance of a view class without a corresponding
model instance.
This program will need to model the behaviour of a snake moving around a field of cells, and
eating food etc.. It must also provide a view of that behaviour, so that the player can easily see
the snake, the food and the trees behaving in ‘real time’. It must additionally provide a control
mechanism for the player to be able to steer the snake, change the speed, etc..
We will keep a clean separation between the model and the view classes. This means, for
example, we shall have a class called Cell and a separate one called CellImage. The former
will be concerned with the model of a cell, and the latter merely about allowing the picture of
a cell to appear on the screen. Similarly, the class Game will be concerned with the behaviour
of a game which consists of cells, whereas GameImage will be responsible for allowing
images of games to be seen on the screen (and will be composed of CellImages).
However, we are not necessarily going to separate the view from the control: indeed these often
fit together nicely in a graphical user interface context. The controlling input from the user will
be handled by the GameGUI class, which will also provide a view for the score message bar,
and will contain the game image.
Class Description CellImage Provides images for cells. Each instance of CellImage will
have a corresponding instance of Cell, which it will store as an instance variable, and it will
provide the image of that cell.
GameImage Provides images for games. Each instance of GameImage will have a
corresponding instance of Game, which it will store as an instance variable, and it will provide
the image of that game.
• An instance of GameGUI will be created by the main method. This will create an instance
of Game and then also an instance of GameImage. A reference to the game instance will
be passed to the instance of the game image, so that the game image knows which game
to provide a view for.
• The instance of GameImage will construct an instance of CellImage for every cell in the
game it has been given. It will keep track of all these cell images, and also combine them
to produce the image of the game.
• The instance of the class GameImage will have an update() method. This will be
invoked
after every move, and at other times, by the instance of GameGUI. This method will
invoke a similar update() method on each instance of CellImage, which will repaint
the image of the corresponding cell, if the cell has been changed since the image was last
painted.
As suggested above, the attraction of this strategy is that the model classes for the game and the
cells need to have absolutely no knowledge of the image classes. This is particularly persuasive
Now we can start the development of the program. The first class on our list is Direction.
This will provide the 4 directions for snake movement, together with some useful methods for
manipulating directions. We do not intend that the class will be instantiated – all its public
items will be accessed statically.
The primary purpose of this class is to provide 4 constant values, one each for the 4 directions
that a snake can move in. We shall also have a 5th direction, to model no movement. One of the
common ways of implementing a small range of constant values is to model them as integers,
and we shall use this approach to implement the 5 directions. However, it should be noted that
this technique has a significant danger and you have met a better alternative, which was not
available in Java when this case study was first created. (What is that alternative?)
Next we develop the code for the class. We need to choose an integer to represent each of the
direction values we need to provide. The most common way of doing this is simply to count
upwards from 0, directly assigning the values to each variable.
Create tile :
//border of gameplay
g.setColor(Color.white);
g.drawRect(24,74,851,577);
g.setColor(Color.BLACK);
g.fillRect(25, 75, 850, 575);
rightmouth=new ImageIcon("rightmouth.png");
rightmouth.paintIcon(this,g,snakexlength[0],snakeylength[0]);
for(int a=0;a<lengthofsnake;a++)
{
if(a==0 && right)
{
rightmouth=new ImageIcon("rightmouth.png");
rightmouth.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
if(a==0 && left)
{
leftmouth=new ImageIcon("leftmouth.png");
leftmouth.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
if(a==0 && up)
{
upmouth=new ImageIcon("upmouth.png");
upmouth.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
if(a==0 && down)
{
downmouth=new ImageIcon("downmouth.png");
downmouth.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
if(a!=0)
{
snakeimage=new ImageIcon("snakeimage.png");
snakeimage.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
}
for(int b=1;b<lengthofsnake;b++)
{
if(snakexlength[b]==snakexlength[0] &&
snakeylength[b]==snakeylength[0])
{
right=false;
left=false;
up=false;
down=false;
g.setColor(Color.WHITE);
g.setFont(new Font("arial",Font.BOLD,50));
g.drawString("Game Over!", 300, 300);
g.setFont(new Font("arial",Font.BOLD,20));
g.drawString("Spcae to RESTART", 350, 340);
}
}
g.dispose();
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
moves++;
if(!left)
{
right=true;
}
else
{
right=false;
left=true;
}
up=false;
down=false;
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
moves++;
if(!right)
{
left=true;
}
else
{
left=false;
right=true;
}
up=false;
down=false;
}
if(e.getKeyCode()==KeyEvent.VK_UP)
{
moves++;
if(!down)
{
up=true;
}
else
{
up=false;
down=true;
}
left=false;
right=false;
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
moves++;
if(!up)
{
down=true;
}
else
{
down=false;
up=true;
}
left=false;
right=false;
}
if(e.getKeyCode()==KeyEvent.VK_SPACE)
{
scores=0;
moves=0;
lengthofsnake=3;
repaint();
}
16 Conclusion
Apart from the class you 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, GameSnake, and so on? The short answer is this: you are the one that will be looking
at that part of the program, in your laboratory exercise! However, in that exercise you are
requested to develop the Game class without dividing it up, and then ask yourself whether it
would be a good idea to, and what are the pros and cons.