Snake Game Report

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

lOMoARcPSD|35064103

Snake Game report

computer application (PDM University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Manish . ([email protected])
lOMoARcPSD|35064103

A
MINOR PROJECT REPORT
ON
“SNAKE GAME”

Submitted in partial of the requirement for the award of degree of

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)

Department of Computer Science & Engineering


Faculty of Engineering & Technology
P.D.M. University, Bahadurgarh.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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)

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

DECLARATION BY THE CANDIDATE

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.

Date: KULDEEP SHARMA

Place: A40219010

(ii)

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

ACKNOWLEDGEMENT

I express my sincere gratitude to DR. JASVINDER KAUR (Head, Department of


CSE) and DR. NISHIKA (Assistant Professor, Department of CSE), for their valuable
guidance and timely suggestions during the entire duration of my dissertation work,
without which this work would not have been possible. I would also like to convey my
deep regards to all other faculty members who have bestowed their great effort and
guidance at appropriate times without which it would have been very difficult on my
part to finish this work.

KULDEEP SHARMA
A40219010

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

4.1 Steps of Creation Design ….................................................................................22-23


4.2 Data Flow Diagram............................................................................................. 23
CHAPTER 5: IMPLEMENTATION…................................................................. 24-29
5.1 Objectives.............................................................................................................24
5.2 Method Used...................................................................................................... 24-25
5.3 Steps to Create Game..........................................................................................25-29
CHAPTER 6: RESULTS.........................................................................................30-35
CHAPTER 7: TESTING AND DEBUGGING…..................................................36-37
7.1 Testing Framework.............................................................................................. 36
7.2 Testing Techniques............................................................................................... 37
7.2.1 Unit Testing….......................................................................................37
7.2.2 Integration Testing.................................................................................37
CHAPTER 8: CONCLUSION AND FUTURE SCOPE…...................................38
8.1 Conclusion…........................................................................................................38
8.2 Limitation….........................................................................................................38
8.3 Future Scope......................................................................................................... 39
REFERENCES ……………………………………………………………………………………………………….40

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

1.2: Learning outcomes

The intentions of this case study are as follows.

• 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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

1.3: Description of the game

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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 count down
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.

Figure 1 shows a sneak preview of the finished game program.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Figure 1: A screen dump of a game. The optional extra feature of a gutter trail is visible behind
the snake.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

Java is a class-based, object-oriented programming language and is designed to have as few


implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine.
The syntax of Java is similar to C/C++.

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

is known as the Father of Java. Currently, Java is used in mobile devices, internet
programming, games, e-business, etc.

2.2 Java programming language is named JAVA. Why?

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 .

2.3 Java Terminology :

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.

 Writing a program is done by a java programmer like you and me.


 The compilation is done by the JAVAC compiler which is a primary Java compiler
included in the Java development kit (JDK). It takes the Java program as input and
generates bytecode as output.
 In the Running phase of a program, JVM executes the bytecode generated by the
compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode
produced by the compiler. Every Operating System has a different JVM but the output they
produce after the execution of bytecode is the same across all the operating systems. This is
why Java is known as a platform-independent language.

2.Bytecode in the Development process: As discussed, the Javac compiler of JDK


compiles the java source code into bytecode so that it can be executed by JVM. It is saved
as .class file by the compiler. To view the bytecode, a disassembler like javap can be used.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

2.4 Primary/Main Features of Java

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.

2. Object-Oriented Programming Language : Organizing the program in the terms of


collection of objects is a way of object-oriented programming, each of which represents an
instance of the class.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

a. The four main concepts of Object-Oriented programming are:


i. Abstraction
ii. Encapsulation
iii. Inheritance
iv. Polymorphism.

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.

6. Distributed: We can create distributed applications using the java programming


language. Remote Method Invocation and Enterprise Java Beans are used for creating
distributed applications in java. The java programs can be easily distributed on one or
more systems that are connected to each other through an internet connection .

7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent


execution of two or more parts of a program for maximum utilization of CPU.

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

2.5 Introduction to Java Swing

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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

 Swing is a Set Of API ( API- Set Of Classes and Interfaces ).


 Swing is Provided to Design a Graphical User Interfaces.
 Swing is an Extension library to the AWT (Abstract Window Toolkit).
 Includes New and improved Components that have been enhancing the looks and
Functionality of GUI’s.
 Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets And
Applets.
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent And The Swing Components are
lightweight.
 Swing Supports Pluggable look and feels And Swing provides more powerful components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
 Further Swing Follows MVC.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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:

 Cut and paste: Clipboard support.


 Accessibility features: Aimed at developing GUI’s for users with disabilities.
 The Desktop Colors Features Has been Firstly introduced in Java 1.1.
 The Java 2D: it has Improved colors, images, and also texts support.

2.5.1 Features Of Swing Class :


 Pluggable look and feel.
 Uses MVC architecture.
 Lightweight Components.
 Platform Independent.
 Advance features such as JTable, JTabbedPane, JScollPane etc.
 Java is a platform-independent language and runs on any client machine, the GUI
look and feel, owned and delivered by a platform specific O/S, simply does not
affect an application’s GUI constructed using Swing components.
 Lightweight Components : Starting with the JDK 1.1, its AWT supported
lightweight component development. For a component to qualify as lightweight, it
must not depend on any non-Java [O/s based) system classes. Swing components
have their own view supported by Java’s look and feel classes.
 Pluggable Look and Feel: This feature enables the user to switch the look and
feel of Swing components without restarting an application. The Swing library
supports components look and feel that remains the same across all platforms
wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application.

2.5.2 Swing Classes Hierarchy

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Fig. 2.1: Swing Class Hierarchy

2.5.3 The MVC Connection :

 In general, a visual component is a composite of three distinct aspects:


1. The way that the component looks when rendered on the screen
2. The way such that the component reacts to the user
3. The state information associated With the component
 Over the years, one component architecture has proven itself to be exceptionally
effective:- Model-View-Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated
with the Component
 The view determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
 The controller determines how the component reacts to the user

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

 Swing components do not have to be rectangular. Buttons, for example, can be


round
 Now The Latest Assertive technologies such as screen readers can easily getting the
information from Swing components. For example: A screen reader tool can easily
capture the text that is displayed on a Swing button or label

2.5.4 Components of Swing Class

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

Container A Container is a component that can container SWING Components

A JComponent is a base class for all swing UI Components In order to


use a swing component that inherits from JComponent, component
must be in a containment hierarchy whose root is a top-level Swing
JComponent container

JLabel A JLabel is an object component for placing text in a container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls designed to allow the user


JColorChooser to manipulate and select a color

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Class Description

A JCheckBox is a graphical(GUI) component that can be in either an on-


JCheckBox (true) or off-(false) state

The JRadioButton class is a graphical(GUI) component that can be in


JRadioButton either an on-(true) or off-(false) state. in the group

A JList component represents the user with the scrolling list of text
JList items

A JComboBox component is Presents the User with a show up Menu of


JComboBox choices

A JTextField object is a text component that will allow for the editing of
JTextField a single line of text

JPasswordField A JPasswordField object it is a text component specialized for


password entry

A JTextArea object s a text component that allows for the editing of


JTextArea multiple lines of text

A ImageIcon control is an implementation of the Icon interface that


Imagelcon paints Icons from Images

A JScrollbar control represents a scroll bar component in order to


JScrollbar enable users to Select from range values

JOptionPane JOptionPane provides set of standard dialog boxes that prompt users

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Class Description

for a value or Something

A JFileChooser it Controls represents a dialog window from which the


JFileChooser user can select a file.

JProgressBar As the task progresses towards completion, the progress bar displays
the tasks percentage on its completion

A JSlider this class is lets the user graphically(GUI) select by using a


JSlider value by sliding a knob within a bounded interval.

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

2.5.5 Java ActionListener Interface

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.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:

1. Implement the ActionListener interface in the class:

public class ActionListenerExample Implements ActionListener

2. Register the component with the Listener:

component.addActionListener(instanceOfListenerclass);

3. Override the actionPerformed() method:

public void actionPerformed(ActionEvent e){

//Write the code here

2.5.6 Java Swing Elements :


Let’s take a brief introduction some of these Java swing elements :

1. Java Swing | JTextField


JTextField is a part of javax.swing package. The class JTextField is a component that
allows editing of a single line of text. JTextField inherits the JTextComponent class
and uses the interfaceSwingConstants.
The constructor of the class are :

1. JTextField() : constructor that creates a new TextField


2. JTextField(int columns) : constructor that creates a new empty TextField
with specified number of columns.
3. JTextField(String text) : constructor that creates a new empty text field
initialized with the given string.
4. JTextField(String text, int columns) : constructor that creates a new
empty textField with the given string and a specified number of
columns .

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

5. JTextField(Document doc, String text, int columns) : constructor that


creates a textfield that uses the given text storage model and the given
number of columns.

Methods of the JTextField are:

1. setColumns(int n) :set the number of columns of the text field.


2. setFont(Font f) : set the font of text displayed in text field.
3. addActionListener(ActionListener l) : set an ActionListener to the text
field.
4. int getColumns() :get the number of columns in the textfield.

2. Java Swing | JTextArea


JTextArea is a part of java Swing package . It represents a multi line area that
displays text. It is used to edit the text .
JTextArea inherits JComponent class. The text in JTextArea can be set to different
available fonts and can be appended to new text . A text area can be customized
to the need of user .
Constructors of JTextArea are:

1. JTextArea() : constructs a new blank text area .

2. JTextArea(String s) : constructs a new text area with a given initial text.

3. JTextArea(int row, int column) : constructs a new text area with a given
number of rows and columns.

4. JTextArea(String s, int row, int column) : constructs a new text area


with a given number of rows and columns and a given initial text.

Commonly used methods :

1. append(String s) : appends the given string to the text of the text area.

2. getLineCount() : get number of lines in the text of text area.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

3. setFont(Font f) : sets the font of text area to the given font.

4. setColumns(int c) : sets the number of columns of the text area to


given integer.

5. setRows(int r) : sets the number of rows of the text area to given


integer.

6. getColumns() : get the number of columns of text area.

7. getRows() : get the number of rows of text area.

3. Java Swing | JMenuBar


JMenuBar, JMenu and JMenuItems are a part of Java Swing package.
JMenuBar is an implementation of menu bar . the JMenuBar contains
one or more JMenu objects, when the JMenu objects are selected
they display a popup showing one or more JMenuItems .
JMenu basically represents a menu . It contains several JMenuItem
Object . It may also contain JMenu Objects (or submenu).

Constructors :

1. JMenuBar() : Creates a new MenuBar.


2. JMenu() : Creates a new Menu with no text.
3. JMenu(String name) : Creates a new Menu with a specified name.
4. JMenu(String name, boolean b) : Creates a new Menu with a specified name
and boolean
value specifies it as a tear-off menu or not. A tear-off menu can be opened
and dragged away from its parent menu bar or menu.

Commonly used methods:

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

4. add(JMenuItem menuItem) : Adds menu item to the end of the menu.


5. add(String s) : Creates a menu item with specified string and appends it to
the end of menu.
6. getItem(int index) : Returns the specified menuitem at the given index.
7.

4. JLabel | Java Swing


JLabel is a class of java Swing . JLabel is used to display a short string or an image
icon. JLabel can display text, image or both . JLabel is only a display of text or image
and it cannot get focus . JLabel is inactive to input events such a mouse focus or
keyboard focus. By default labels are vertically centered but the user can change the
alignment of label.

Constructor of the class are :

1. JLabel() : creates a blank label with no text or image in it.


2. JLabel(String s) : creates a new label with the string specified.
3. JLabel(Icon i) : creates a new label with a image on it.
4. JLabel(String s, Icon i, int align) : creates a new label with a string, an
image and a specified horizontal alignment

Commonly used methods of the class are :

1. getIcon() : returns the image that the label displays.


2. setIcon(Icon i) : sets the icon that the label will display to image i.
3. getText() : returns the text that the label will display.
4. setText(String s) : sets the text that the label will display to string s.

5. Java Swing | JFileChooser


JFileChooser is a part of java Swing package. The java Swing package is part of
JavaTM Foundation Classes(JFC) . JFC contains many features that help in
building graphical user interface in java . Java Swing provides components such
as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

prompt the user to choose a file or a directory .


In this article we will see how to use JFileChooser in java swing .

Constructors of JFileChooser are :

1. JFileChooser() – empty constructor that points to user’s default


directory .

2. JFileChooser(String) – uses the given path .

3. JFileChooser(File) – uses the given File as the path.

4. JFileChooser(FileSystemView) – uses the given FileSystemView .

5. JFileChooser(String, FileSystemView) – uses the given path and the


FileSystemView.

6. JFileChooser(File, FileSystemView) – uses the given current directory


and the FileSystemView .

6. JLabel | Java Swing


JLabel is a class of java Swing . JLabel is used to display a short
string or an image icon. JLabel can display text, image or both .
JLabel is only a display of text or image and it cannot get focus .
JLabel is inactive to input events such a mouse focus or keyboard
focus. By default labels are vertically centered but the user can
change the alignment of label.

Constructor of the class are :

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

1. JLabel() : creates a blank label with no text or image in it.


2. JLabel(String s) : creates a new label with the string
specified.
3. JLabel(Icon i) : creates a new label with a image on it.
4. JLabel(String s, Icon i, int align) : creates a new label with
a string, an image and a specified horizontal alignment

Commonly used methods of the class are :

1. getIcon() : returns the image that the label displays


2. setIcon(Icon i) : sets the icon that the label will display to image i
3. getText() : returns the text that the label will display
4. setText(String s) : sets the text that the label will display to string s.

7. Java Swing | JList

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 .

Constructor for JList are :

1. JList(): creates an empty blank list


2. JList(E [ ] l) : creates an new list with the elements of the array.
3. JList(ListModel d): creates a new list with the specified List Model.
4. JList(Vector l) : creates a new list with the elements of the vector.

8. Java Swing | ScrollPaneLayout Class

The layout manager used by JScrollPane. JScrollPaneLayout is based on nine


components: a viewport, two scrollbars, a row header, a column header, and
four “corner” components.

Constructor of the class:

 ScrollPaneLayout(): It is used to Construct a new ScrollPanelLayout.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Commonly Used Methods:

 removeLayoutComponent(Component comp): Removes the specified


component from the layout.
 getColumnHeader(): It returns the JViewport object that is the column
header.
 getVerticalScrollBar(): Returns the JScrollBar object that handles the
vertical scrolling.
 getHorizontalScrollBar(): Returns the JScrollBar object that handles the
horizontal scrolling.
 addLayoutComponent(String st, Component c): Adds the specified
component to the layout.
 getViewport(): Returns the JViewport object that displays the scrollable
contents.
 getCorner(String key):It is used to returns the Component at the
specified corner.
Below programs illustrate the use of ScrollPanelLayout class:

1. The following program illustrates the use of ScrollPaneLayout by


arranging several JLabel components in a JFrame, whose instance class
is “Geeks“. We create one JScrollPane component named “scrollpane”
and one JList component named “list“. We set the size and visibility of
the frame by using setSize() and setVisible() method. The layout is set
by using setLayout() method.

9. Java Swing | Look and Feel


Swing is GUI Widget Toolkit for Java. It is an API for providing Graphical User
Interface to Java Programs. Unlike AWT, Swing components are written in Java
and therefore are platform-independent. Swing provides platform specific Look
and Feel and also an option for pluggable Look and Feel, allowing application to
have Look and Feel independent of underlying platform.
Initially there were very few options for colors and other settings in Java Swing,
that made the entire application look boring and monotonous. With the growth
in Java framework, new changes were introduced to make the UI better and thus
giving developer opportunity to enhance the look of a Java Swing Application.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

“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:

1. CrossPlatformLookAndFeel: this is the “Java L&F” also known as


“Metal” that looks the same on all platforms. It is part of the Java API
(javax.swing.plaf.metal) and is the default.
2. SystemLookAndFeel: here, the application uses the L&F that is default
to the system it is running on. The System L&F is determined at
runtime, where the application asks the system to return the name of
the appropriate L&F.
For Linux and Solaris, the System L&Fs are “GTK+” if GTK+ 2.2 or later
is installed, “Motif” otherwise. For Windows, the System L&F is
“Windows”.
3. Synth: the basis for creating your own look and feel with an XML file.
4. Multiplexing: a way to have the UI methods delegate to a number of
different look and feel implementations at the same time.

10. Java Swing | JDialog


JDialog is a part Java swing package. The main purpose of the dialog is to add
components to it. JDialog can be customized according to user need .
Constructor of the class are:

 JDialog() : creates an empty dialog without any title or any specified


owner
 JDialog(Frame o) :creates an empty dialog with a specified frame as its
owner
 JDialog(Frame o, String s) : creates an empty dialog with a specified
frame as its owner and a specified title
 JDialog(Window o) : creates an empty dialog with a specified window as
its owner
 JDialog(Window o, String t) : creates an empty dialog with a specified
window as its owner and specified title.
 JDialog(Dialog o) :creates an empty dialog with a specified dialog as its
owner

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

 JDialog(Dialog o, String s) : creates an empty dialog with a specified


dialog as its owner and specified title.

Commonly used methods

 setLayout(LayoutManager m) : sets the layout of the dialog to specified


layout manager
 setJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified
menubar
 add(Component c): adds component to the dialog
 isVisible(boolean b): sets the visibility of the dialog, if value of the
boolean is true then visible else invisible
 update(Graphics g) : calls the paint(g) function
 remove(Component c) : removes the component c
 getGraphics() : returns the graphics context of the component.
 getLayeredPane() : returns the layered pane for the dialog
 setContentPane(Container c) :sets the content pane for the dialog
 setLayeredPane(JLayeredPane l) : set the layered pane for the dialog
 setRootPane(JRootPane r) : sets the rootPane for the dialog
 getJMenuBar() : returns the menubar of the component
 setTransferHandler(TransferHandler n) : Sets the transferHandler
property, which is a mechanism to support transfer of data into this
component.
 setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to
add and setLayout are forwarded to the contentPane.
 setRootPane(JRootPane root) :Sets the rootPane property of the dialog.
 setGlassPane(Component glass) : Sets the glassPane property of the
dialog.
 repaint(long time, int x, int y, int width, int height): Repaints the
specified rectangle of this component within time milliseconds.
 remove(Component c): Removes the specified component from the
dialog.
 isRootPaneCheckingEnabled() : Returns whether calls to add and
setLayout are forwarded to the contentPane or not .
 getTransferHandler() : returns the transferHandler property.
 getRootPane() : Returns the rootPane object for this dialog.
 getGlassPane() : Returns the glassPane object for this dialog.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

 createRootPane() : Called by the constructor methods to create the


default rootPane.
 addImpl(Component co, Object c, int i) : Adds the specified child
Component to the dialog.

11. Jframe | Swing


Swing is a part of JFC (Java Foundation Classes). Building Graphical User
Interface in Java requires the use of Swings. Swing Framework contains a
large set of components that allow a high level of customization and
provide rich functionalities and is used to create window-based
applications.
Java swing components are lightweight, platform-independent, provide
powerful components like tables, scroll panels, buttons, lists, color
chooser, etc.

In this article, we’ll see how to make frames using Swings in Java.

Ways to create a frame:

Methods

1. By creating the object of Frame class (association)


2. By extending Frame class (inheritance)
3. Create a frame using Swing inside main()

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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

 JFrame(String title, GraphicsConfiguration gc): It creates a JFrame with


the specified title and the specified GraphicsConfiguration of a screen
device.

12.Message Dialogs in Java (GUI)


Message dialogs provide information to the user. Message dialogs
are created with the JOptionPane.showMessageDialog() method.

We call the static showMessageDialog() method of the JOptionPane class to


create a message dialog. We provide the dialog’s parent, message text, title, and
message type. The message type is one of the following constants :

1. ERROR_MESSAGE
2. WARNING_MESSAGE
3. QUESTION_MESSAGE
4. INFORMATION_MESSAGE

Methods Used :

 setLayout(…): method helps us to set the layout of the container, often a


JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever
layout we want to add on container.
 setBounds(…): method is used to set the location and size of components like
JButton, and is only useful if null layout is used in JFrame.
 setVisible(…): method is used to set the Visibility status of JFrame.
1. setVisible(true) will set JFrame visible to user.
2. setVisible(false) will set JFrame not visible to user.
 getSource(): An event object contains a reference to the component that
generated the event. To extract that reference from the event object we use
getSource() Method.
 add(): It is used to add components like JButton etc, to the container of
JFrame.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

3.2 TECHNOLOGY SPECIFIC REQUIREMENTS


3.2.1 Hardware Requirements

1. A desktop or laptop or computer for the system users.


2. A desktop or a laptop computer to run the program on in the room with the
following specifications: -
 Intel i3 10th GEN (11021-U)
 8 GB RAM DDR2 or Higher.
 256 GB SSD storage space.

3.2.2 Software Requirements

1. NetBeans IDE

2. Java( version 8.0.3010.9)


3. Java (TM) SE Development Kit (version 17.0.1)

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

CHAPTER-4
DESIGN MODULES
4.1 Steps of Creation Design

 Step 1: Create project.


First, open file and then click “project” to create.

 Step 2: Create project name.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Second, name your project.

 Step 3: Create JFrame.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Third, create “JFrame” form.

 Step 4: Create JFrame name.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Fourth, name your JFrame form.

 Step 5: Project Design.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Fifth, The actual design of the project.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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 list for Snake Game: main model classes

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 list for Snake Game: operating support classes

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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

SpeedController A speed controller is something which controls the speed of the


game,
to make it easier or harder for the player as they choose. This will
be achieved rather simply by the program calling a method to cause
a delay between every move. A controller will have various speed
settings, the ability to increase or decrease speed, and to pause and
resume the game.
AboutBox This will provide a pop-up box which can display information about
the program and help on how to use it.

Finally, we shall need a class to contain the main method.

Class list for Snake Game: top level 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.

5.2: The laboratory exercise and optional extra features

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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

snake steers itself, or having two snakes with the user switching control between them.

5.3: High level design, and development approach

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.

get the gameSize from the command line (default 18)


GameGUI gameGUI = new GameGUI(gameSize)
int score = gameGUI.playGame()
output the score

A GameGUI will create an instance of Game and SpeedController. Its playGame()


method will look something like this.

set initial game state


while user has not asked to quit
{
speedController.delay(by some amount)
moveValue
= some function of (speedController.getCurrentSpeed())
game.move(moveValue)
update the game’s image
}
return game.getScore()

A GameGUI will also interpret the key presses from the player, and invoke the appropriate

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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 SpeedControllerwill have a number ofmethods, such as speedUp(), slowDown(),


pause(), resume() and, most importantly, delay().

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.

Let us analyse the anticipated dependencies between these classes.

• Snake is the top level class. This will build an instance of GameGUI.

• GameGUI will need an AboutBox to show help text, a SpeedController to regulate


the speed of the game, and a Game to play.
• AboutBox will not require any other of these classes.
• SpeedController will not require any other of these classes.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

• 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.

5.4: Concept: model, view and control

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.

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

5.5: Separating behaviour and image: design policy

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.

Let us make a list of the extra classes we have just identified.

Class list for Snake Game: image classes

Class Description CellImage Provides images for cells. Each instance of CellImage will

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

Class list for Snake Game: image classes


Class Description SpeedControllerImage Provides the image and control for speed
controllers.
Having made the decision to develop separate classes for model and view, we next must figure
out the way we would like to do it. For example, for each instance of Cell which we create, we
will also need to create an instance of CellImage. We must decide on a strategy for keeping
track of the relationship between corresponding instances of these classes. There are numerous
ways we could do this. The approach we have chosen in this case study has actually been taken
so that you can develop the Game class without having to worry about view and control classes!
So, if we were not in such a learning context, we might have taken a different approach.
Here is the policy we shall use in this case study.

• 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.

• When an instance of CellImage is created, it is passed a reference to the instance of


Cell for which it must provide an image.

• 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

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

given that the Game class is to be written by you!


A second attraction is that we can also hide most of the details of the image and control classes
for this current discussion.

5.6: Development of Direction

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?)

5.6.1: Variable and method interface designs


Direction will have the following public variables.
Variable interfaces for class Direction.
Variable Type Description
NONE int A static final integer value representing the direction that is a model of
no direction.
NORTH int A static final integer value representing the direction that is north.
EAST int A static final integer value representing the direction that is east.
SOUTH int A static final integer value representing the direction that is south.
WEST int A static final integer value representing the direction that is west.
The class will also have the following public methods.
Method interfaces for class Direction.
Method Return Arguments Description
opposite int int Static (class)method that returns the opposite direction
to the given one.
xDelta int int Static (class) method that takes an integer representing
a direction, and returns -1, 0, or 1: this being the
change needed to the x component of a cell co-ordinate
in order to move in the given direction.
12

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

Method interfaces for class Direction.

Method Return Arguments Description


yDelta int int Static (class) method that takes an integer representing
a direction, and returns -1, 0, or 1: this being the
change needed to the y component of a cell co-ordinate
in order to move in the given direction.
rightTurn int int Static (class) method that takes an integer representing
a direction, and returns the integer representing the
direction that is a right turn from the given one.
leftTurn int int Static (class) method that takes an integer representing
a direction, and returns the integer representing the
direction that is a left turn from the given one.

5.7: Code for Direction

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.

public class Gameplay extends JPanel implements KeyListener,ActionListener{


private int[] snakexlength=new int[750];
private int[] snakeylength=new int[750];

private boolean right=false;


private boolean left=false;
private boolean up=false;
private boolean down=false;

private ImageIcon rightmouth;


private ImageIcon leftmouth;
private ImageIcon upmouth;
private ImageIcon downmouth;
private ImageIcon snakeimage;

Create tile :

//border of title image


g.setColor(Color.white);
g.drawRect(24,10,851,55);

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

titleImage = new ImageIcon("snaketitle.jpg");


titleImage.paintIcon(this, g, 25, 11);

//border of gameplay
g.setColor(Color.white);
g.drawRect(24,74,851,577);
g.setColor(Color.BLACK);
g.fillRect(25, 75, 850, 575);

//draw the scores


g.setColor(Color.WHITE);
g.setFont(new Font("arial",Font.PLAIN,14));
g.drawString("Scores : "+scores,780, 30);

g.drawString("Length : "+lengthofsnake,780, 50);

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");

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

downmouth.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}

if(a!=0)
{
snakeimage=new ImageIcon("snakeimage.png");
snakeimage.paintIcon(this,g,snakexlength[a],snakeylength[a]);
}
}

enemyimage = new ImageIcon("enemy.png");

if(enemyxpos[xpos]==snakexlength[0] && enemyypos[ypos]==snakeylength[0])


{
lengthofsnake++;
scores++;
xpos = random.nextInt(34);
ypos = random.nextInt(23);
}
enemyimage.paintIcon(this, g, enemyxpos[xpos], enemyypos[ypos]);

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);

}
}

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

g.dispose();
}

5.8: Code for Keypressed

public void keyPressed(KeyEvent e) {

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++;

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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();
}

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

5.9: Development of the top level class Snake


The top level class will contain just a main method. Its job will be to create an instance of

public class Gameplay extends JPanel implements KeyListener,ActionListener{

private int[] snakexlength=new int[750];


private int[] snakeylength=new int[750];

private boolean right=false;


private boolean left=false;
private boolean up=false;
private boolean down=false;

Downloaded by Manish . ([email protected])


lOMoARcPSD|35064103

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.

Downloaded by Manish . ([email protected])

You might also like