Documentation
Documentation
INTRODUCTION
The following is an example game written in Python based on the game called 'snake'
which has been around since the earliest days of home computing and has re-emerged in
It isn't the world's greatest game, but it does give you an idea of what you can achieve with
a relatively simple Python program and perhaps the basis by which to extend the principles
Hardware requirements:
Software Requirements:
1.3Concepts:-
To reinforce many of the C and programming concepts you have already met.
1
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.
To move the snake, use ‘up arrow' for up, ‘down arrow' for down, ‘left arrow' for left and
‘right arrow' for right. Again, there are constants you can change if you want to alter these
The aim of the game is to collect the dots (food) and avoid the obstacles (crosses, borders,
and the snake itself). As you collect food, the snake gets longer, so increasing your
likelihood of crashing into yourself. When you have collected enough food, you progress
onto the next level, where your snake gets longer, and the amount of food to collect to
You get scored according to the length of the snake and the number of 'x' obstacles on the
screen.
The speed increases every 5 level. You get a bonus when you complete the level of 1000,
increasing by 1000 each level (e.g. complete level 5, you get a 5000 bonus).
There is no concept of lives. Once you hit an obstacle, that's it, game over.
Make sure you do not have the caps lock on, otherwise the keys will fail to respond
1.4 Objectives:-
This game aims to change the way people think of traditional snake game. It will offer the
experience of commercial multilayer games to the player retaining the simplicity of traditional
snake game.
2
The major objectives of this project are:
Create a snake game that will have all the functionality of traditional snake games.
Introduce multilayer functionality in the game that will allow several players to play a
game simultaneously. It should be able to give the experience of a real time multiplayer
make the game more challenging and interesting. The movement and action of these
intelligent opponents will be controlled by computer whose aim will be to eat the food
3
CHAPTER 2
Problem Analysis
One of the most difficult tasks of system analysis is developing a clear, in-depth understanding
of the problem being investigated, without which it becomes impossible to specify the
requirements for a new project with any accuracy. Several questions should be posed for this.
Some of those may be:
It takes considerable skill to determine the true cause of a system problem. A systems analyst
might begin to define the problem by determining if the problem can be classified ac-cording to
one or more common types of systems problems. With knowledge of the common types of
systems problems, the analyst can diagnose a problem by examining its characteristics.
Organizations usually face problems or have opportunity due to the following facts:
After identification of the problem, it is defined and a general direction or method for solving
this problem is also determined. The management establishes the term of reference as well as
the resources to be provided for the project. System development is an iterative process and the
first identifiable stage of it is problem definition, whose final output is terms of reference.
1. Problem of reliability: Current system is not reliable. It seems to vary in quality and
result from one month to the next. Some items it gives good output, but sometimes the
output is worst.
2. Problem of accuracy: There are too many mistakes in reports and calculations.
3. Problem of timeliness: In the current system the reports and output produced is mostly
late and in most of the cases it is useless because it is not on time.
4. Problem of validity: The output and reports mostly contains misleading information.
The transactions and calculations are sometimes not valid.
5. Problem of economy: The current system is very costly. We have to spend lots of
money in manual filing, calculations and remembering the information, but still not get
the desired results.
6. Problem of capacity: The current system is suffering from problem of capacity also.
The workload is too much. Few peoples cannot handle all the working.
5
CHAPTER 3
FEASIBILITY STUDY
3.1 Steps in feasibility analysis:
Economic analysis is the most frequently used technique for calculating the effectiveness of a
proposed system. More commonly known as cost/benefit analysis; in this procedure we
determine the benefits and savings that are expected from a proposed system and compare them
with costs. We found the benefits outweigh the costs; we take a decision to design and
implement the new proposed system.
This is concerned with specifying equipment and software that will successfully satisfy the user
requirement. The technical needed of the system may vary considerable, but might include:
After examining technical feasibility, we give more importance to the configuration of the
system then the actual make of hardware. The configuration gives the complete picture about
the system’s requirements.
Ten to twelve workstations are required, these units should be interconnected through LAN so
that could operate and communicate smoothly. They should have enough speeds of input and
output to achieve a particular quality of printing.
It is mainly related to human organizational and political aspects. The points to be considered
are:
Generally project will not be rejected simply because of operational infeasibility but such
considerations are likely to critically affect the nature and scope of the eventual
recommendations.
For operational feasibility study we appointed a small group of people who are familiar with
information system techniques, who understand the of the business that are relevant to the
project and skilled in system analysis and design process.
7
Social feasibility is a determination of whether a proposed project will be acceptable to the
people or not. This determination typically examines the probability of the project being
accepted by the group directly affected by the proposed system change.
8
CHAPTER 4
SYSTEM ANALYSIS
System analysis and design refers to the process of examining a business situation with the
intent of improving it through better procedures and methods. Systems development can
generally be through of having two major components: System Analysis and System Design.
System design is the process of planning a new system or replace or complement an existing
system. But before this planning can be done, we must thoroughly understand the existing
system and determine how computers can best be used to make its operation more effective.
System analysis, then, is the process of gathering and interpreting facts, diagnosing problems
and using the information to recommend improvement to the system. In brief, we can say that
analysis specifies what the system should do. Design states hew to accomplish the objective.
In this project we have used Rapid Application Development (RAD) model; RAD is an
incremental software development process model that emphasizes an extremely short
development cycle. The following phases are encompassed:
Business modeling: All the information about the business functioning of the gateway
development is collected, how the data and information is flow from one end to another end
using the following questions: What information drives the department process? What
information is generated? Who generates it? Where does the information go? Who process it?
Data modeling: The information collected in business modeling phase is refined into a set of
data objects that are needed to support the project. The attributes of each object are identified
and the relationship between these objects defined.
Process modeling: Processing descriptions and functions like adding, modifying, deleting
student records, assigning marks, generating mark sheet, printing reports, providing
information, file handling etc. are created.
Application generation: The fourth generation techniques are used to generate application,
like reusing the predefined functions or creating reusable components.
9
Testing: Most of the functions are already tested, as they are predefined functions. However,
new components or functions are also tested after application generation.
10
CHAPTER 5
SYSTEM DESIGN
5.1 Introduction:
The system objectives outlined during the feasibility study serve as the basis from which the
work of the system design is initiated. Much of the activities involved at this stage is of
technical nature requiring a certain degree of experience in designing systems, sound
knowledge of computer related technology and through understanding of computers available
in the market and the various facilities provided by the vendors. Nevertheless, a system cannot
be designed in isolation without the active involvement of the user. The user has a vital role to
play at this stage too. As we know that data collected during feasibility study will be utilized
systematically during the system design. It should, however, be kept in mind that detailed study
of existing the system is not necessarily over with the completion of the feasibility study.
Depending on the plan of feasibility study, the level of detailed study will vary and the system
design stage will also vary in the amount of investigation that still needs to be done. This
investigation is generally an urgent activity during the system design as the designer needs to
study minute’s details in all aspects of the system. Sometimes, but rarely, this investigation
may from a separate stage between feasibility study and computer system design. Designing a
new system is a creative process, which calls for logical as well as lateral thinking. The logical
approach involves systematic moves towards the end product keeping in mind the capabilities
of the personnel and the equipment at each decision making step. Lateral thought implies
encompassing of ideas beyond the usual functions and equipment. This is to ensure that no
efforts are being made to fit previous solutions into new situations.
The system design process is not a step-by-step adherence of clear procedures and guidelines.
Though, certain clear procedures and guidelines have emerged in recent days, but still much of
design work depends on knowledge and experience of the designer.
11
When designer starts working on system design, he will face different type of problems. Many
of these will be due to constraints imposed by the user or limitations of the hardware and
software available in the market. Sometimes, it is difficult to enumerate the complexity of the
problems and solutions thereof since the variety of likely problems is so great and no solutions
are exactly similar. However, following considerations should be kept in mind during the
system–designing phase:
The primary objective of the design: Of course, is to deliver the requirements as specified in
the feasibility report. In general, the following design objectives should be kept in mind:
a. Practicality: The system must be stable and can be operated by people with average +.
b. Efficiency: This involves accuracy, timeliness and comprehensiveness of the system output.
c. Cost: It is desirable to aim for a system with a minimum cost subject to the condition that it
must satisfy all the requirements.
d. Flexibility: The system should be modifiable depending on the changing needs of the user.
Such modifications should not be entail extensive reconstructing or recreation of software. It
should also be portable to different computer systems.
e. Security: This is very important aspect of the design and should cover areas of hardware
reliability, fall back procedures, physical security of data and provision for detection of fraud
and abuse.
System design involves first logical design and then physical construction of the system. The
logical design describes the structure and characteristics of features, like the outputs, inputs,
files, databases and procedures. The physical construction, which follows the logical design,
produces actual program software, files and a working system.
5.3.1 Hardware: The existing hardware will obviously affect the system design.
5.3.2 Software: The available software (operating system, utilities, language etc.) in the market
will constraint the design.
12
5.3.3 Budget: The budget allocated for the project will affect the scope and depth of design.
5.3.4 Time-scale: The new system may be required by a particular time (e.g. the start of a
financial year).This may put a constraint on the designer to find the best design.
5.3.5 Interface with other systems: The new system may required some data from another
computerized system or may provide data to another system in which case the files must be
compatible in format and the system must operate with a certain processing cycle.
Batch processing
Real-time processing
Online processing
A combination of all the above
You are already aware of these techniques. It is quite interesting to note, however that a
combination of these is often found to be ideal in traditional data processing applications. This
increases throughput of the system as also brings down the response time of on-line activities.
In most of die business applications, 24-hour data is acceptable enough and hence it is possible
to update voluminous data after office-hours in batch mode.
The scope of the system design is guided by the framework for the new system developed
during analysis. More clearly defined logical method for developing system that meets user
requirements has led to new techniques and methodologies that fundamentally attempt to do
the following:
STRUCTURE DESIGN
6.1 Introduction:
Structure design is a data flow based methodology. The approach begins with a system
specification that identifies inputs and outputs and describes the functional aspects of the
system. The specifications then are used as a basis for the graphics representation. The step is
the definition of the modules and their relationship to one another in a form called a structure
chart, using a data dictionary and other structure tools.
Logical design proceeds from the top down. General features such as reports and inputs are
identified first. Then each is satisfied individually and in more detail. Hence, the structure
design partitions a program into small, independent modules. They are arranged in a hierarchy
that approximates a model of the business area and is organized in a top-down manner. Thus,
structured design is an attempt to minimize the complexity and make a problem manageable by
subdividing it into smaller segments which is called modularization or decomposition. In this
way, structuring minimizes intuitive reasoning and promotes maintainable provable systems.
14
Several development activities are carried out during structured design. They are data base
design, implementation planning, system test preparation, system interface specification, and
user documentation.
a. Data base design: This activity deals with the design of the physical database. A key is to
determine how the access paths art to be implemented.
c. System and program test preparation: Each aspect of the system has a separate test
requirement. System testing is done after all programming and testing completed. The test
cases cover every aspect of the proposed system, actual operations, and user interface and so
on. System program test requirements become a part of design specification–a pre requisite to
implementation.
In contrast to the system testing is acceptance testing. Which puts the system through a
procedure design to convince the user that the proposed system will meet the started and
requirements. Acceptance testing is technically similar to system testing but politically it is
different. Acceptance testing is conducted in the presence of the user, audit representatives, or
the entire staff.
15
CHAPTER 7
PROCESS MODELING
7.1 Data Flow Diagram:
Graphical description of a system`s data and how the processes transform the data is known as
Data Flow Diagram (or DFD).
Unlike detail flowcharts. DFDs do not supply detailed descriptions of modules but graphically
describe a system`s data and how the data interact with the system.
Arrows
Circles
Open–ended boxes
Squares
An arrow identifies data flow–data in motion. It is a pipeline through which information flows.
Like the rectangle in flowcharts, circles stand for a process that converts data/into in–
formation. An open–ended box represents a data store data at rest, or a temporary repository of
data. A square defines a source (originator) or destination of system data.
The following seven rules govern construction of data flow diagrams (DFD).
16
Control information such as record counts, passwords, and validation requirements are not
pertinent to a data-flow diagram.
If too many events seem to be occurring at a given point, an analyst can decompose a data
conversion (circle). The new data conversions from a parent-child relationship with the original
data conversion : the child circle.
7.2 Methodology
The complete iSnake application is divided into four major components:
iSnake Client Application
iSnake Game Server
Intelligent Autonomous Opponent Snakes
iSnake Game Server Manager (GSM) @ SF.net
iSnake client application refers to the application used to play snake game. A player joins
an already existing iSnake game server using this application.
17
7.2.2 Client Encoder/Decoder
This module performs the encoding and decoding of messages leaving/arriving the
client network interface module using the protocol standard described in ANNEX D: Inter
Snake Communication Protocol.
It provides an interface to the Game Controller module for communication with the
game server hosted at local/remote computer. It is responsible for triggering of appropriate
methods of Game Controller when message from Game Server is received.
It manages the task of sampling key strokes from local player and forwarding it to
Game Controller when requested. It maintains a queue of size 2 so that quick keystrokes are
not lost. It is active only when the game is in running mode.
Game Controller maintains the complete state of the game using game field matrix. It
is a 2D array of size 58x58 (equal to the game field dimensions). Each game field object has a
unique identifier in the game field. Game Controller updates the cells of this matrix in each
cycle to register the changes that occur in the game.
It represents the game field as seen by the player. Game Controller analyzes the game
field matrix in each cycle and updates the game field canvas to represent the state of game in
that game cycle. Double Buffering [using java.awt.Canvas.createBufferStrategy()] has been
18
implemented to avoid flickering of game field. Each block in the game field has dimension
10x10 pixels.
The update of game field canvas occurs in the way similar to the refreshing technique
of a cathode ray monitor. The game field matrix and game field canvas are updated in
separate thread. The update of game field canvas starts by scanning each column of the 1 st
row in the game field matrix, then 2 nd row and so on upto the 58th row. The game field is
refreshed twice during each game cycle (two refresh cycle for game field canvas for each
game cycle). This is done make the movements in the game field smoother.
This module includes all the components, except game field, visible to the player.
The look and feel of default swing components have been overridden to give the feel of a
game to the players. MIT OCW's course 1 “[6.831] User Interface Design and
Implementation” was very helpful during design of most of the user interface components
of this game.
19
7.3 iSnake Game Server
iSnake game server handles the multiplayer feature of this game and allows multiple
iSnake client applications to play the game hosted by that particular game server.
This module performs the encoding and decoding of messages leaving/arriving the
server network interface module using the protocol standard described in ANNEX D: Inter
Snake Communication Protocol.
20
Game server maintains the state of the game using a 2D array of size 58x58 (similar to
that used by Game Controller – refer to 5.1.4). The virtual game field is updated in every
game cycle to reflect the changes in game field.
It is maintained by the game server to check whether the food has been eaten and
whether any player has collide with the wall. It maintains the head coordinate (not the
coordinates for tails) of each player. The head coordinate of players is moved in each game
cycle and checked for the presence of wall/food in that coordinate position. Server Core
generates corresponding event (collide or food eaten) and all the active players are informed
about the event in the same cycle.
It manages the information about the players involved in the game. Player information
like name, location, score, snake's starting position, snake color, etc are maintained. A new
entry is added whenever a new player joins the game. Similarly, when the player leaves the
game, it is removed.
Game server maintains a buffer of random numbers obtained from Quantum Random
Bit Generator service [QRGB http://random.irb.hr ]. This gives the game server access to true
random number. These random data is used to generate the position of food and the starting
coordinate of each player's snake.
If the random number service is unreachable pseudo random numbers are generated
using java.util.Random class provided by Java.
21
Status server maintains all the information required to reply the current status of the
game server. The service of status server is utilized by iSnake Game Server
Manager(iSnake GSM)2 hosted at http://isnake.sf.net. The response of status server is a
well formed XML document that is parsed by iSnake – GSM to display information about
the game server in the website.
<iSnake>
<GameServerData>
<GameServerAddress>124.41.228.219</GameServerAddress>
<GameServerPort>9669</GameServerPort>
<NoOfPlayersOnline>5</GameServerLocation>
<GameServerStatus>Waiting</GameServerStatus>
</GameServerData>
</iSnake>
It is the most important component of the iSnake Game Server. It coordinates the
working of all the other modules in the application and handles all the messages received
from the remote players.
When the game is in "Waiting" mode, Server Core provides the facility of chat
messaging to the game players. During this state new players can join the game.
When all the players have sent signal to start the game, the Server Core changes
state to “Running” mode. If a new player tries to join the game, it receives a “NAK”
response. In this mode, Server Core maintains a game cycle time during which it receives
the movement coordinates (in terms of deltaX and deltaY) from the players. If a player
22
does not send any packet during this cycle time, server considers the movement coordinate
sent in last cycle for the current game cycle. After expiry of cycle time, game server
broadcasts a packet containing movement coordinates of each player to all the players
These are computer controlled snakes, in the game, whose aim is to challenge the
human players. We have two implementations of path finding algorithms to create
intelligent autonomous opponent snakes. These algorithms return the shortest possible path
from given source (S) and target (T) coordinate pair considering the obstacles (if any)
present in the game field. The code name3 for these two implementations are:
23
Illustration 3: Turn around time for Illustration 4: Length of path
two path finding algorithms returned by the two path finding
algorithms
24
7.5 iSnake Game Server Manager (GSM) @ SF.net
iSnake Game Server Manager (iSnake – GSM) hosted at http://isnake.sf.net is used to manage
all the information about iSnake game servers being hosted over the Internet.
The iSnake – GSM has been developed using PHP. Java Web Start technology has been used
to deploy iSnake application at our website which automatically downloads/installs iSnake
application and its library dependencies. This provides the gamers with the facility of “one
click launch” of the iSnake application. It also make the distribution of updates of the iSnake
application to the end users very convenient.
The iSnake application deployed at our website has been digitally signed by the iSnake team to
address the security issues related to launch of Internet applications
25
CHAPTER 8
CODING
import pygame
import time
import random
pygame.init()
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (34,177,76)
light_green = (0,255,0)
blue = (0,0,255)
display_Width = 800
display_Height = 600
boundary_size = 8
block_Size = 10
eatsound = pygame.mixer.Sound("snakeeat.wav")
crashsound = pygame.mixer.Sound("snakecrash.wav")
gameDisplay=pygame.display.set_mode((display_Width, display_Height))
pygame.display.set_caption('Slither')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
26
clock=pygame.time.Clock()
def background():
bgimage = pygame.image.load('bg0.png')
pygame.transform.scale(bgimage, (display_Width, display_Height))
gameDisplay.blit(bgimage, (0,0))
def intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#background()
gameDisplay.fill(white)
27
screen_message('Welcome To Slither', red, -250, 'large')
screen_message('RULES', red, -100, 'large')
screen_message('Feed The Snake By Collecting The Apples', black, 10)
screen_message('If Snake Hit the Wall It DIES!!!', black, 50)
screen_message('With every 5 Apples The Speed Of The Snake INCREASES', black, 90)
screen_message('More Apples You Eat More Longer You Get', black, 130)
def pause():
pause = True
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = False
screen_message('Game Paused', black, -100, 'large')
pygame.display.update()
def score(score):
text = smallfont.render('Score: '+ str(score), True, black)
gameDisplay.blit(text, [5,0])
pygame.display.update()
def gameloop():
global direction
lead_x=display_Width/2
lead_y=display_Height/2
lead_x_change= 0
lead_y_change= 0
s=0
gameExit = False
gameOver = False
snakelist= []
length=1
i=1
30
Frame_per_sec = 10
lead_x += lead_x_change
lead_y += lead_y_change
#background()
gameDisplay.fill(white)
32
if i%5==0 :
pygame.draw.rect(gameDisplay, light_green, [x_Apple, y_Apple,
block_Size+10,block_Size+10])
else:
pygame.draw.rect(gameDisplay, black, [x_Apple, y_Apple, block_Size,block_Size])
snake(snakelist,block_Size,length)
f_input = open("highscore.txt","r+")
h = f_input.read()
if int(h) < int(s) and gameOver == True:
h=s
f_input = open("highscore.txt","w")
f_input.write(str (h));
33
f_input.close()
pygame.display.update()
if i%5==0:
if lead_x >= x_Apple and lead_x < x_Apple+ block_Size + 10:
if lead_y >= y_Apple and lead_y < y_Apple+ block_Size + 10:
eatsound.play()
x_Apple= round(random.randrange(boundary_size, display_Width - block_Size)/10)*10
y_Apple= round(random.randrange(boundary_size, display_Height - block_Size)/10)*10
length= length+1
s=s+10
Frame_per_sec +=5
i=i+1
else:
if lead_x == x_Apple and lead_y == y_Apple:
eatsound.play()
x_Apple= round(random.randrange(boundary_size, display_Width - block_Size)/10)*10
y_Apple= round(random.randrange(boundary_size, display_Height - block_Size)/10)*10
length= length+1
s=s+1
i=i+1
score(s)
pygame.display.update()
clock.tick(Frame_per_sec)
pygame.quit()
quit()
34
intro()
gameloop()
//*****************************************//
pygame.init()
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (34,177,76)
light_green = (0,255,0)
blue = (0,0,255)
display_Width = 800
display_Height = 600
boundary_size = 8
block_Size = 10
eatsound = pygame.mixer.Sound("snakeeat.wav")
crashsound = pygame.mixer.Sound("snakecrash.wav")
gameDisplay=pygame.display.set_mode((display_Width, display_Height))
pygame.display.set_caption('Slither')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
clock=pygame.time.Clock()
def background():
bgimage = pygame.image.load('bg0.png')
pygame.transform.scale(bgimage, (display_Width, display_Height))
gameDisplay.blit(bgimage, (0,0))
def intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
35
quit()
#background()
gameDisplay.fill(white)
screen_message('Welcome To Slither', red, -250, 'large')
screen_message('RULES', red, -100, 'large')
screen_message('Feed The Snake By Collecting The Apples', black, 10)
screen_message('If Snake Hit the Wall It DIES!!!', black, 50)
screen_message('With every 5 Apples The Speed Of The Snake INCREASES', black, 90)
screen_message('More Apples You Eat More Longer You Get', black, 130)
def pause():
pause = True
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = False
screen_message('Game Paused', black, -100, 'large')
pygame.display.update()
def score(score):
text = smallfont.render('Score: '+ str(score), True, black)
gameDisplay.blit(text, [5,0])
pygame.display.update()
def gameloop():
global direction
lead_x=display_Width/2
lead_y=display_Height/2
lead_x_change= 0
lead_y_change= 0
s=0
gameExit = False
gameOver = False
snakelist= []
length=1
i=1
Frame_per_sec = 10
lead_x += lead_x_change
lead_y += lead_y_change
#background()
gameDisplay.fill(white)
if i%5==0 :
pygame.draw.rect(gameDisplay, light_green, [x_Apple, y_Apple, block_Size+10,block_Size+10])
else:
pygame.draw.rect(gameDisplay, black, [x_Apple, y_Apple, block_Size,block_Size])
snake(snakelist,block_Size,length)
38
f_input = open("highscore.txt","r+")
h = f_input.read()
if int(h) < int(s) and gameOver == True:
h=s
f_input = open("highscore.txt","w")
f_input.write(str (h));
f_input.close()
pygame.display.update()
if i%5==0:
if lead_x >= x_Apple and lead_x < x_Apple+ block_Size + 10:
if lead_y >= y_Apple and lead_y < y_Apple+ block_Size + 10:
eatsound.play()
x_Apple= round(random.randrange(boundary_size, display_Width - block_Size)/10)*10
y_Apple= round(random.randrange(boundary_size, display_Height - block_Size)/10)*10
length= length+1
s=s+10
Frame_per_sec +=5
i=i+1
else:
if lead_x == x_Apple and lead_y == y_Apple:
eatsound.play()
x_Apple= round(random.randrange(boundary_size, display_Width - block_Size)/10)*10
y_Apple= round(random.randrange(boundary_size, display_Height - block_Size)/10)*10
length= length+1
s=s+1
i=i+1
score(s)
pygame.display.update()
clock.tick(Frame_per_sec)
pygame.quit()
quit()
intro()
gameloop()
39
Partial Bounding Rectangle (pbr):
These rectangles touch either the source or the target node and not both. Two partial
bounding rectangles touching 'S' and 'T' form paths from source to the target node.
Notations:
brNM
denotes a bounding rectangle that spans ( or touches ) N nodes along the xaxis and M
nodes along the yaxis.
spbrNM
denotes a source partial bounding rectangle that spans ( or touches ) N nodes along the
xaxis and M nodes along the yaxis.
tpbrNM
denotes a target partial bounding rectangle that spans ( or touches ) N nodes along the
xaxis and M nodes along the yaxis.
hpNM
denotes a hopping point (coordinate specified with reference to source) along which
spbrNM and tpbrNM are formed. This coordinate point is common to both spbrNM and
tpbrNM
40
Numbering of Paths
For any given bounding rectangle (br) there are only two possible paths as show in
Illustration 9. Path numbering convention applied is:
Path1: The xcoordinate of the path first changes followed by change in y coordinate
Path2: The ycoordinate of the path first changes followed by change in x coordinate
A source (S) and target (T) can be placed in four possible ways such that they lie on
opposite ends of the diagonal. Considering the four position (A,B,C,D) as depicted in
Illustration 9, we have the following four cases:
41
dotted red) and Target bounding rectangle (tpbr -
dotted green)
Illustration Bounding rectangle (br - dotted
gray), Source bounding rectangle (spbr - Illustration : Two possible paths along the edges of
the bounding rectangle (dotted red line rectangle)
provided no obstacles exists along the path
Both path1 and path2 have equal traveling cost provided that no obstacles are present along those
paths. For any given br, if there exists a path from source to target inside the br then it will be the
shortest path.
For any given (S,T) pair, we move the hopping point along the diagonal joining S and T.
Special considerations is required when:
● obstacles (wall) are present along the paths formed using the bounding and partial bounding
rectangles.
● No possible path can be found using all the possible combinations of the partial bounding
rectangles.
● the bounding rectangle is not a square ( ie: for brNM, N ≠ M )
42
Description of the algorithm
Instead of considering all the possible cases at once, let us consider the working of algorithm in
several stages (with increasing complications).
all possible path of an stage the next stage is checked. The series of steps taken to obtain a path
from 'S' to 'T' are:
Figure A2 – initially the hopping point is hp66 (on the target). two paths formed along the
bounding rectangle br66 (shown in red dotted rectangle in Figure A2) are checked for
presence of obstacles. If no obstacles are found, either path1 or path2 are chosen (refer to
Illustration 9). As both path1 and path2 have same path length, choice between these two
paths is made based on some combination of sub paths and choosing the path whose length
is shortest.
Figure A3 four paths (refer to Illustration 10) formed along the source and target partial
bounding rectangle (spbr55, tpbr22) are checked for presence of obstacle.
Figure A4 four paths (refer to Illustration 10) formed along the source and target partial
bounding rectangle (tpsbr44, ptbr33) are checked for presence of obstacle.
Figure A5 four paths (refer to Illustration 10) formed along the source and target partial
bounding rectangle (tpsbr33, ptbr44) are checked for presence of obstacle.
Figure A6 four paths (refer to Illustration 10) formed along the source and target partial
bounding rectangle (tpsbr22, ptbr55) are checked for presence of obstacle.
Figure A7 This step is not necessary to execute as the task has already been performed in
Step 1 using the bounding rectangle (br66).
43
Computation overhead calculations
Let the time required to check whether a partial bounding rectangle has an obstacle
= T1
time required to check whether a bounding rectangle has an obstacle = T2
44
Backtracking
If 4.1.1.1 to 4.1.1.6 does not give a path from 'S' to 'T' the technique of backtracking will be
applied. To illustrate the process of backtracking let us consider the scenario shown in
Illustration .
The paths generated from the bounding rectangle (br44) and all the possible partial
bounding rectangles contain obstacle. Hence the process discussed above will not result in
any path from 'S0' to 'T'. For such scenario we can apply the process of backtracking.
45
Backtracking involves moving to the next outer (as inner bounding rectangles do not contain any path
for sure) bounding rectangle a path to the target is found. Illustration 13 shows the result of
backtracking. Backtracking from S0 to S1 (the next outer bounding rectangle) results in a bounding
rectangle br55. This bounding rectangle does not also result in any path from S1 to T. Hence, next
outer bounding rectangle is checked.
By joining the paths formed from the above two steps can be combined to form a path from
S0 to T.
46
Illustration : Path from node S0 to S2 is
calculated using the process discussed before
(after a path is found from S2 to T
Let source (S) and target (T) be placed as shown in Illustration 16. A path from S to T
contains two edges. Path1 contains edge1 and edge2. Path2 contains edge4 and edge3.
While determining whether a path contains obstacle, the algorithm must also determine
which edges contains obstacles (if any).
We can apply the following algorithm to determine the outer rectangles required during
backtracking for source.
} else {
} else {
} else {
no backtracking required
}
47
The outer rectangle for target, during backtracking, can be determined by applying similar
logic for edge2 and edge3.
This technique works for different orientation of source and target as described in Section
1.3.5 Numbering of Paths
While backtracking several sub paths are created while requires to be merged to form the
final path from source to target. Let us consider a case as depicted in Illustration 17.
Path from S to S' : depicted by red colored line from S to S' (SubPath1)
Path from S' to T : depicted by blue colored line from T to T' (SubPath2)
Path from T' to T : depicted by pink colored line from T' to T (SubPath3)
We need to combine these three paths to obtain a final path from S to T (depicted by
thick black line). If we add these three paths directly, the final path will contain
overlapping paths (which is not required). The following algorithm can be applied to
compute the final path (that does not contain any overlapping regions).
START
48
Step 1: Initialize FinalPath with the contents of SubPath1
FinalPath = SubPath1
Step 2: Now perform the following operations for each cell coordinate present in
SubPath2 and SubPath2 (K=2,3)
cellCoordinate = SubPathK.getCellCoordinate()
if(FinalPath contains cellCoordinate) {
remove cellCoordinate from FinalPath
} else {
add cellCoordinate to FinalPath
Step 3: FinalPath contains discontinuities at the bends of path. Search for
consecutive cell coordinate for which both x and y values of the coordinate change
(ie: |dx| = 1, |dy| = 1).
49
50
Illustration . The algorithm applied in “[A] Symmetric Bounding Rectangles (Simple Case)”
can be now applied by considering the dummy nodes as normal game field nodes free from
any obstacles.
This case arises when both 'S' and 'T' lie on same straight line (horizontal or vertical) as
shown in Illustration 20.
51
Illustration : The case can be converted to “[A]
Symmetric Bounding Rectangle (Simple Case)”
case by adding dummy nodes
Requirements
Constant time algorithm for obstacle detection
There must exist a constant time algorithm that can answer the question “Does the given
bounding or partial bounding rectangle contain any obstacle?”. The constant time
algorithm requirement means that the YES/NO decision of this algorithm should not depend
on the size of rectangle under consideration or the number of obstacles present in the game
field.
An important observation for iSnake game is that the obstacles in the game are not dynamic.
In other words, the obstacles remain constant until a given FOOD is eaten by one of the
players. Hence we can assume that the obstacle is constant during the execution of this path
finding algorithm.
We apply the following algorithm to detect whether a given bounding rectangle contains
any obstacles.
START
Step 1: Let (x1,y1) = one corner of the bounding rectangle
52
Step 2: Repeat step 2 for each cell coordinate in obstacle oc =
obstacle.getCellCoordinate() path1HasObstacle = true,
path2HasObstacle = true if( x >= x1 and x <= x2 ) {
if(!path1HasObstacle) {
if( x1y1.gggetY().equals(y) )
path1HasObstacle = true
}
if(!path2HasObstacle) {
if( x2y2.ggetY().equals(y) )
path2HasObstacle = true
}
}if ( y >= y1 and y <= y2 ) {
if(!path1HasObstacle) {
if( x2y2.getX().equals(x) )
path1HasObstacle = true
}
if(!path2HasObstacle) {
if( x1y1.getX().equals(x) )
path2HasObstacle = true
}
}
Step 3: if(path1HasObstacle) {
if(path2HasObstacle)
return NO PATH POSSIBLE
else
return PATH2 is OBSTACLE FREE
}
else {
53
if(path2HasObstacle)
return PATH1 is OBSTACLE FREE
else
return PATH1 and PATH2 are OBSTACLE FREE
}
END
Limitations
This algorithm does not consider the transparent game field boundary (entry to one side of the field
causes exit in the opposite side of the field as depicted in Illustration 22) during path
calculation. Due to this limitation the computed path is not optimal.
54
● The rectangle with the dotted boarder is the view port(vp) of each player. Other rectangles
attached with it in each side are the virtual view port(vvp) in their corresponding sides.
● Small yellow box is a wallunit. Group of attached wallunit is said to be wall.
● Finally considering all these, the aim of this algorithm is to find all (there may be multiple path
of same distance) shortest path from the snake (head) to food. However as a result it will return
only one among those paths.
55
The algorithm follows following steps:
1. This algorithm begins with splitting all the game field into small rectangles (Fundamental open
rectangle7 (FOR8)), say R1, R2, R3, ... Rn. If gamefield (only view port), as a whole is said to be G.
Then mathematically the wall, W can be defined as:
W = G R1 U R2 U R3 U ... U Rn
Broadly, this algorithm deals with splitting the game field into several (as many) rectangles such that,
the union of all these small rectangles result in the game field that exclude wall. ie, the snake can move
safely from any point in the rectangle(Ri) to any other point within the same rectangle(Ri)and hence
called Open rectangles (OR)
Next we define Gate9 (Gate as in real life is a way to move from a FOR to another adjacent FOR)
calculate the shortest distance between each two Gates of each FOR (eg: the shortest distance between
the rectangles R1 and R5 are determined by the distance between the two gates of R3 shared with R1
and R5 respectively).
2. After the calculation of the shortest path, a graph as shown in Illustration 4 is formed.
56
i. The dotted lines defines direct connection, the direct path.
ii. The dark line shows a 1 step indirect connection between those rectangles that are not
connected directly.
iii. Sij, beside with the vertex, (in graph) denotes that FORi is connected to FORj through this
vertex and vice versa. This can also be called indirect path. And it posses the path distance.
iv. There may be multiple indirect path. Eg: We can move form 2 to 5 (S25) in two
57
The above sample case shown in illustration 6 and 7, shows the path calculated by the algorithm from
the snake (red one pointed by an arrow A) to the food (blue one pointed by an arrow F). The points
pointed by the arrows A, B, C, D, E and F are points (Hoping Points) that the intelligent player must
pass through. And thus allowing multiple possibility for path.
The path is multiple because, there exist multiple way to go from A to B and E to F. Further the
rectangles as formed by the points A and B ( E and F ) can also be called Derived open rectangle (as it
doesn't contain any wall, and hence allows free movement of the snake inside it).
both sides until it strike to wall(unit).Name it Fundamental Open Rectangle (FOR1 and FOR2
or Just R1 and R2). Illustration8 and 9.
bottom in both direction (up and down) to get other two rectangle R3 and R4. Illustration11.
58
Till this step the rectangle was not bounded (either in all
four sides (envelop) or in two sides(top and bottom)
Step 3 Illustration
11: Step-3
6. As earlier again try to slice the gamefield in the anticlockwise direction starting from left. It
will result in two more rectangle R7 and R8.
59
7. For Further Optimization we proceed by breaking down the rectangle that touches itself (eg:
in this case, the top edged of rectangle R1 touch itself to its bottom edge). These type of rectangles are
divided in the middle. This results in best utilization of the transparency of the Game Field.
60
Special case for Game Field with no wall
If there is no wall we simply chop the game field vertically and horizontally from the middle resulting
in 4 FOR's. This results in maximum utilization of the transparency of the game field. The result is
shown in Illustration 17.
Salient Features:
● As most of the processing is done before the actual game starts, it must reduce the
the processing time during the game-time.
● The concept of open-rectangle allows multiple path, and hence within it the snake can be
moved randomly towards the specified point. And hence it is intelligent.
● Furthermore, during the calculation of the path the snake can move within the FOR in which
it currently lie.
Limitations:
● If the number of FOR increases to too high, then it will obviously be tough and slow to
determine the shortest path.
61
Program flow
Illustration : iSnake game application enters in STAGE-1 and exits through STAGE-5
Illustration : iSnake game application starts in STAGE-1 and this stage involves connection to
game server specified by the player
NOTE: "EXT" refers to the actions that are triggered by Client Network Interface module when
messages are received from game server
62
Illustration : In STAGE-2 players can chat with each other. The game will start only when all the
players connected to the game server send READY signal
NOTE: "EXT" refers to the actions that are triggered by Client Network Interface module when
messages are received from game server
63
Illustration : STAGE-3 involves receiving different game data (like wall coordinates,
food coordinate, snakes start position, etc)
NOTE: "EXT" refers to the actions that are triggered by Client Network Interface module when
messages are received from game server
NOTE: "EXT" refers to the actions that are triggered by Client Network Interface module when
messages are received from game server
64
NOTE: "EXT" refers to the actions that are triggered by Client Network Interface module when
messages are received from game server
65
CHAPTER 9
SNAPSHOTS
Snapshots 1:
66
Snapshots 2:
67
Snapshots 3:
Snapshots 4:
68
Snapshots 5:
69
Snapshots 6:
70
Snapshots 7:
71
CHAPTER 10
72
SYSTEM IMPLEMENTATION AND
REQUIREMENT
10.1 Introduction:
The decision to acquire hardware or software must be handled in the same way as any
other information decision, The variety of sizes and types of computing resources
available puts a burden on the analyst who must select hardware, software and advise the
Today, selecting a system is a serious and time-consuming. The time spent on the
selection process is a function of the applications and whether the system is a basic
There are various important factors, which should be considered prior to system
Specify the magnitudes of the problem; that is, clarify section entails a few
Provide user indoctrination. This is crucial, especially for first time users. Selling
the system to the user staff, provide adequate training and creating an environment
73
The selection process should be viewed as a project and a project team should be formed
with the help of management. The selection process consists of several steps, which are
discussed below:
10.1.1 Requirements analysis: The first step in selection is understanding the user`s
requirements within the framework of the organization`s objectives and the environment
specifications must reflect the actual applications to be handled by the system and include
10.1.3 Request for proposal: After the requirement analysis and system specifications
have been defined, a request for proposal is prepared and sent to selected vendors for
bidding.
10.1.4 Evaluation and validation: The evaluation phase ranks various vendor proposal
and determines the one best suited to the user`s requirements. It looks into items such as
price, availability and technical support. System validation ensures that the vendor can, in
10.1.5 Vendor selection: This step determines the vendor with the best combination of
reputation, reliability, service record, training, delivery time, lease/finance terms. The
74
Project Management
The first thing we did before starting the work on iSnake was to register a project at
Sourceforge4. Apart from hosting services, it provided us several code and project
management services.
Illustration 10 shows the svn commit statistics for the isnake code repository at
75
JUnit tests were developed to independently test some of the modules before integration.
The integration of modules developed by the three developers was performed in three
phases:
● Phase 1 Integration (Sep. 28, 2007) chat functionality of the game was tested
successfully
● Phase 3 Integration (Feb 17 26, 2008) – integration of all the modules for iSnake
Documentation
Documentation of every task being done in the project was a priority for all the team
members. Almost every portion of the source code contains full code documentation
76
There exists two path finding algorithms that implements intelligent opponent in the
game viz Blackmamba and Viper. These two algorithms have been fully documented
with illustrations5.
The protocol devised for communication between game server and clients has been
documented in ANNEXD.
Limitations
● The present implementation of iSnake can only be played in LAN. Due to large
latency time and bandwidth limitation, it cannot be played over the Internet.
● Path finding algorithms (Blackmamba and Viper) implemented in this game have
their own computation limitations which has been describe in ANNEX A,B.
● Full stress test of the application has not been done yet. Hence, the response of
still in its early development phase. There are some unresolved security issues.
Future Enhancements
● Port iSnake to cell phone platform and One Laptop Per Child – OLPC (which uses
77
options(Bluetooth, WIFI, GPRS, CDMA) in cell phones makes it a very attractive
platform for a multiplayer game like iSnake. Local WIFI network formed by kids
● As iSnake game server communicates with remote playing using a well defined
and very simple protocol (Refer to ANNEX D), iSnake clients programmed in
Conclusion
computer controlled intelligent opponents have been successfully tested in the game is a
large scale project. The experience of working in team and integration of modules
78
Important as learning point of view for children
Augmented Reality
Motion Capture
Cloud Gaming
Emerging Trends
REFERENCES
Books:
Beginning Java Objects: From Concepts to Code , Jacquie Barker,2009
Introduction to Java Programming: NIIIT publication , John Wiley,1998
79
The Complete Reference Java, McGrawhill: Herbert Schildth- reprint, 2008
Web Sites:
www.apache.org
www.wikipedia.com
80