0% found this document useful (0 votes)
33 views80 pages

Documentation

Uploaded by

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

Documentation

Uploaded by

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

CHAPTER 1

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

recent years on mobile phones.

 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

and create more interesting games of your own.

1.2 Hardware and Software Requirements:

Hardware requirements:

 Pentium-II processor or above


 Processor Speed 533 MHZ
 Color monitor
 Keyboard
 80-GB Hard Disk Drive or above
 128 MB RAM or above

Software Requirements:

 Microsoft Windows-XP or above


 Python
 Microsoft Access

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

settings. Press ‘ESC' to exit the game at any time.

 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

progress through the level gets larger

 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

game to the players.

 Introduce computer controlled intelligent opponent (unique feature of this game) to

make the game more challenging and interesting. The movement and action of these

intelligent opponents will be controlled by computer whose aim will be to eat the food

before human players capture it.

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:

 What is the problem?


 How complex is it?
 What are its likely causes?
 Why is it important that the problem be solved?
 What are possible solutions to the problem?
 What types of benefits can be expected once the problem is solved?

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:

 A new product or plant or branch


 A new market or new process
 Failure of an existing system
 Inefficiency of an existing system
 Structural error in the existing system etc

For identifying problems/opportunities, we scan the following:

 The performance of the system


 The information being supplied and its form
 The economy of processing
 The control of the information processing
4
 The efficiency of the existing system
 The security of the data and software
 The security of the equipment and personnel etc

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.

Careful analysis of this system suggests a number of different problems:

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:

Eight steps involved in the feasibility analysis are:

1. From a project team and appoint a project leader.


2. Prepare system flowcharts.
3. Enumerate potential proposed systems.
4. Define and identify characteristics of proposed system.
5. Determine and evaluate performance and cost effectiveness of each proposed
system.
6. Weight system performance and cost data.
7. Select the best proposed system.
8. Prepare and report final project directive to management.

3.2 Type of feasibilities:

3.2.1 Economic Feasibility:

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.

3.2.2 Technical Feasibility:

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:

 The facility to produce outputs in a given time.


 Response time under certain conditions.
6
 Ability to process a certain volume of transaction at a particular speed.
 Facility to communicate data to distant location.

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.

3.2.3 Operational Feasibility:

It is mainly related to human organizational and political aspects. The points to be considered
are:

 What changes will be brought with the system?


 What organizational structures are disturbed?
 What news skills will required?
 Do the existing staff members have these skills?
 If not, can they be trained in due course of time?

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.

3.2.4 Social Feasibility:

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.

3.2.5 Management Feasibility:

It is a determination of whether a proposed project will be acceptable to management. If


management does not accept a project or gives a negligible support to it, the analyst will tend
to view the project as a non-feasible one.

3.2.6 Legal Feasibility:

Legal feasibility is a determination of whether a proposed project infringes on known Acts,


Statutes, as well as any pending legislation. Although in some instances the project might
appear sound, on closer investigation it may be found to infringe on several legal areas.

3.2.7 Time Feasibility:

Time feasibility is a determination of whether a proposed project can be implemented fully


within a stipulated time frame. If a project takes too much time it is likely to be rejected.

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.

5.2 System Design Considerations:

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 The designer constraints:

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.

5.4 Processing Techniques:

The options available to the designer are:

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

5.5 Design Methodologies:

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:

 Improve productivity of analysts and programmers.


 Improve documentation and subsequent maintenance and enhancements.
 Cut down drastically on cost overruns and delays.
 Improve communication among the user, analyst designer, and programmer.
 Standardize the approach to analysis and design.
13
CHAPTER 6

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.

A design is said to be top-down if it consists of a hierarchy of modules. with each module


having a single entry and a single exit subroutine. The primary advantages of this design are as
follows:

 Critical interfaces are tested first.


 Early versions of the design, through incomplete, are useful enough to resemble the real
system.
 Structuring the design, parse, provides control and improves morale.
 The procedural characteristics define the order that determines processing.

6.2 Major System Design Activities:

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.

b. Program design: In conjunction with database design is a decision on the programming


language to be used and the flowcharting, coding, and debugging procedure prior to
conversion. The operating system limits the programming languages that will run of the
system.

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.

To construct data flow diagrams, we use:

 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).

 Arrows should not cross each other.


 Squares, circles, and files must bear names.
 Decomposed data flows must be balanced (all data flows on the decomposed diagram
must reflect flows in the original diagram).
 No two data flows, squares, or circles can have the same name.
 Draw all data flows around the outside of the diagram.
 Choose meaningful names for data flows, processes, and data stores.
 Use strong verbs followed by nouns.

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

7.2.1 iSnake Client Application

iSnake client application refers to the application used to play snake game. A player joins
an already existing iSnake game server using this application.

Illustration 1: Block diagram of iSnake Client


Application The main components of iSnake Client
application are:

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.

7.2.3 Client Network Interface

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.

7.2.3 Input Handler

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.

7.2.4 Game Field Matrix

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.

7.2.5 Game Field Canvas

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.

7.2.6 User Interface Components

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.

7.2.7 Game Controller

It is the most important component of the iSnake client application. It coordinates


the working of all the other modules in the application and handles all the messages
received from the game server. Game Controller maintains the game cycle when the game
is running. This game cycle is synchronized with the game cycle of the game server. All
the updates to game field matrix are done during this cycle time. After expiry of each game
cycle the game field is repainted to reflect the changes in the game field.

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.

Illustration 2: Block diagram of iSnake Game


Server The main components of iSnake Game
Server are:

7.3.1 Server Encoder/Decoder

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.

7.3.2 Server Network Interface


It provides an interface to the Server Core module for communication with the remote/local
players of the game being hosted. It is responsible for triggering of appropriate methods of
Server Core when message from remote/local players is received.

7.3.3 Virtual Game Field

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.

7.3.4 Player Information Manager

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.

7.3.5 Random Number Pool

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.

7.3.6 Status Server

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.

A typical response of Status Server is given below:

<?xml version=”1.0” encoding=”UTF8”?>

<iSnake>

<GameServerData>

<GameServerAddress>124.41.228.219</GameServerAddress>

<GameServerPort>9669</GameServerPort>

<NoOfPlayersOnline>5</GameServerLocation>

<GameServerStatus>Waiting</GameServerStatus>

</GameServerData>

</iSnake>

7.3.7 Server Core

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

2 Refer to “5.4 iSnake Game Server Manager (GSM) @ SF.net”


active in the game. The game server also checks if any player has eaten the food or if any
players have collided to the wall in each cycle.

7.4 Intelligent Autonomous Opponent Snakes

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:

 Blackmamba (refer to ANNEX A)

 Viper (refer to ANNEX B)

A detailed paper describing the algorithm used by these two implementation is


present in ANNEX A and ANNEX B. To know which of the two implementations perform
better, we profiled them using a simple JUnit test and the results were plotted using
gnuplot:

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.

Illustration 7.5: Block diagram of iSnake Game Server Manager at http://isnake.sf.net

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

smallfont = pygame.font.SysFont('comicsansms', 25)


medfont = pygame.font.SysFont('comicsansms', 50)
largefont = pygame.font.SysFont('comicsansms', 80)

def boundary(display_Width, display_Height, boundary_size):


pygame.draw.line(gameDisplay, black, (0,0), (display_Width,0), boundary_size)
pygame.draw.line(gameDisplay, black, (0,0), (0,display_Height), boundary_size)
pygame.draw.line(gameDisplay , black, (display_Width,0), (display_Width, display_Height),
boundary_size+2)
pygame.draw.line(gameDisplay , black, (0,display_Height), (display_Width, display_Height),
boundary_size+2)

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)

button("play", 150,500,100,50, green, light_green, action = "play")


button("quit", 550,500,100,50, green, light_green, action = "quit")
boundary(display_Width, display_Height, boundary_size)
pygame.display.update()

def text_to_button(msg, color, x, y, width, height, size = 'small'):


textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((x+(width/2)), y+(height/2))
gameDisplay.blit(textSurf, textRect)
def button(text,x,y,width,height,inactive_color,active_color,action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
if action == "play":
gameloop()
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
28
text_to_button(text, black, x, y, width, height)

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 text_objects(msg, color,size):


if size == 'small':
textSurface = smallfont.render(msg, True, color)
if size == 'medium':
textSurface = medfont.render(msg, True, color)
if size == 'large':
textSurface = largefont.render(msg, True, color)
return textSurface, textSurface.get_rect()
29
def screen_message(msg, color, y_displace=0, size='small'):
textSurf , textRect = text_objects(msg, color, size)
textRect.center = (display_Width / 2), (display_Height/2) + y_displace
gameDisplay.blit(textSurf, textRect)

def snake(snakelist, block_Size, length):


k=1
for XY in snakelist:
if (k == length):
pygame.draw.rect(gameDisplay, red, [XY[0], XY[1], block_Size, block_Size])
k += 1
else:
pygame.draw.rect(gameDisplay, black, [XY[0], XY[1], block_Size, block_Size])
pygame.draw.line(gameDisplay, white, (XY[0], XY[1]), (XY[0]+10, XY[1]+10), 1)
k+=1

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

x_Apple= round(random.randrange(boundary_size, display_Width -


block_Size-boundary_size)/10)*10
y_Apple= round(random.randrange(boundary_size, display_Height -
block_Size-boundary_size)/10)*10

while not gameExit:


while gameOver == True:
#background()
gameDisplay.fill(white)
screen_message("Game Over", red, -200, 'large')
screen_message("Do you want to replay Y/N", black, 50, 'medium')
f_input = open("highscore.txt","r")
h = f_input.read()
screen_message('High Score = '+str(h), black,-40, 'medium')
screen_message('Your Score = '+str(s), black,-110, 'medium')
boundary(display_Width, display_Height, boundary_size)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.QUIT:
gameExit = True
gameOver= False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
gameloop()
if event.key == pygame.K_n:
gameExit= True
gameOver= False
31
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and lead_x_change != block_Size:
lead_x_change = - block_Size
lead_y_change = 0
elif event.key == pygame.K_RIGHT and lead_x_change != -block_Size:
lead_x_change = block_Size
lead_y_change = 0
elif event.key == pygame.K_UP and lead_y_change != block_Size:
lead_y_change = - block_Size
lead_x_change = 0
elif event.key == pygame.K_DOWN and lead_y_change != -block_Size:
lead_y_change = block_Size
lead_x_change = 0
elif event.key == pygame.K_p:
pause()

if lead_x < boundary_size + 2 or lead_x >= display_Width-boundary_size - 2 or lead_y <


boundary_size or lead_y >= display_Height-boundary_size - 2:
crashsound.play()
gameOver = True

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

boundary(display_Width, display_Height, boundary_size)


snakehead=[]
snakehead.append(lead_x)
snakehead.append(lead_y)
snakelist.append(snakehead)

if len(snakelist) > length:


del snakelist [0]

for snakeSegment in snakelist[:-1]:


if snakeSegment == snakehead:
crashsound.play()
gameOver = True

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

smallfont = pygame.font.SysFont('comicsansms', 25)


medfont = pygame.font.SysFont('comicsansms', 50)
largefont = pygame.font.SysFont('comicsansms', 80)

def boundary(display_Width, display_Height, boundary_size):


pygame.draw.line(gameDisplay, black, (0,0), (display_Width,0), boundary_size)
pygame.draw.line(gameDisplay, black, (0,0), (0,display_Height), boundary_size)
pygame.draw.line(gameDisplay , black, (display_Width,0), (display_Width, display_Height), boundary_size+2)
pygame.draw.line(gameDisplay , black, (0,display_Height), (display_Width, display_Height), boundary_size+2)

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)

button("play", 150,500,100,50, green, light_green, action = "play")


button("quit", 550,500,100,50, green, light_green, action = "quit")
boundary(display_Width, display_Height, boundary_size)
pygame.display.update()

def text_to_button(msg, color, x, y, width, height, size = 'small'):


textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((x+(width/2)), y+(height/2))
gameDisplay.blit(textSurf, textRect)
def button(text,x,y,width,height,inactive_color,active_color,action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
if action == "play":
gameloop()
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)

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 text_objects(msg, color,size):


if size == 'small':
textSurface = smallfont.render(msg, True, color)
36
if size == 'medium':
textSurface = medfont.render(msg, True, color)
if size == 'large':
textSurface = largefont.render(msg, True, color)
return textSurface, textSurface.get_rect()

def screen_message(msg, color, y_displace=0, size='small'):


textSurf , textRect = text_objects(msg, color, size)
textRect.center = (display_Width / 2), (display_Height/2) + y_displace
gameDisplay.blit(textSurf, textRect)

def snake(snakelist, block_Size, length):


k=1
for XY in snakelist:
if (k == length):
pygame.draw.rect(gameDisplay, red, [XY[0], XY[1], block_Size, block_Size])
k += 1
else:
pygame.draw.rect(gameDisplay, black, [XY[0], XY[1], block_Size, block_Size])
pygame.draw.line(gameDisplay, white, (XY[0], XY[1]), (XY[0]+10, XY[1]+10), 1)
k+=1

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

x_Apple= round(random.randrange(boundary_size, display_Width - block_Size-boundary_size)/10)*10


y_Apple= round(random.randrange(boundary_size, display_Height - block_Size-boundary_size)/10)*10

while not gameExit:


while gameOver == True:
#background()
gameDisplay.fill(white)
screen_message("Game Over", red, -200, 'large')
screen_message("Do you want to replay Y/N", black, 50, 'medium')
f_input = open("highscore.txt","r")
h = f_input.read()
screen_message('High Score = '+str(h), black,-40, 'medium')
screen_message('Your Score = '+str(s), black,-110, 'medium')
boundary(display_Width, display_Height, boundary_size)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.QUIT:
gameExit = True
gameOver= False
37
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
gameloop()
if event.key == pygame.K_n:
gameExit= True
gameOver= False
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and lead_x_change != block_Size:
lead_x_change = - block_Size
lead_y_change = 0
elif event.key == pygame.K_RIGHT and lead_x_change != -block_Size:
lead_x_change = block_Size
lead_y_change = 0
elif event.key == pygame.K_UP and lead_y_change != block_Size:
lead_y_change = - block_Size
lead_x_change = 0
elif event.key == pygame.K_DOWN and lead_y_change != -block_Size:
lead_y_change = block_Size
lead_x_change = 0
elif event.key == pygame.K_p:
pause()

if lead_x < boundary_size + 2 or lead_x >= display_Width-boundary_size - 2 or lead_y < boundary_size or


lead_y >= display_Height-boundary_size - 2:
crashsound.play()
gameOver = True

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

boundary(display_Width, display_Height, boundary_size)


snakehead=[]
snakehead.append(lead_x)
snakehead.append(lead_y)
snakelist.append(snakehead)

if len(snakelist) > length:


del snakelist [0]

for snakeSegment in snakelist[:-1]:


if snakeSegment == snakehead:
crashsound.play()
gameOver = True

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

Blackmamba – path finding algorithm


Some definitions and notations
Bounding Rectangle (br)
It is a rectangle in which the source and the target lie at two opposite corners of the rectangle.
Source Bounding Rectangle (sbr0) and Target Bounding Rectangle (tbr0) represent the bounding
rectangles from source and target – which are the same rectangle.

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.

Source Partial Bounding Rectangle (spbr)


The pbr touching the source node 'S'.
Target Partial Bounding Rectangle (tpbr)
The pbr touching the target node 'T'.
Refer to Illustration

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:

1.3.5.1 'S' placed at position A and 'T' placed at position C


Path1 = ABC, Path2 = ADC
1.3.5.2 'S' placed at position B and 'T' placed at position D
Path1 = BAD, Path2 = BCD
1.3.5.3 'S' placed at position C and 'T' placed at position A
Path1 = CDA, Path2 = CBA
1.3.5.4 'S' placed at position D and 'T' placed at position B

Path1 = DCB, Path2 = DAB

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

Basis of this algorithm


In absence of any obstacles, the cost of moving from one node to another is constant throughout
the game field. Hence, the shortest path is along the bounding rectangle edges if no obstacles are
present in the path as shown in Illustration 9.

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.

Paths generated by partial bounding rectangles


Four paths are generated by the source and target partial bounding rectangles for the given
hopping point as shown in Illustration 10.

Illustration : Four possible paths generated by


source and target partial bounding rectangles
(spbr,tpbr - depicted using red and green dotted
lines respectively) for a given hopping point

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

[A] Symmetric Bounding Rectangles (Simple Case)


For illustration purpose, let us first consider a game field of 6x6 nodes where source and target
are placed at 'S' and 'T' respectively as shown in Figure A1. The following series of steps are
executed to find a path from source to target. If obstacle is found in

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:

Procedure of finding path for a given (S,T) pair

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

for a game field NxN (row x col)


also let (to create the worst case)
the source 'S' be located at (1,1)
the target 'T' be located at (N,N)
Total no. of possible hopping points (excluding the source) = N – 1

Hence, total time required to calculate a path6 = T2 + N * T1

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 .

Illustration : Game field scenario when all the


paths formed by bounding and partial bounding
rectangles contain obstacle.

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.

Illustration : Next outer bounding rectangle


(br66) is checked for a path from node S2 to T.
The next outer bounding rectangle (br66) is formed at node S1 as shown in
Illustration 14. This bounding rectangle has a path from S2 to T. Hence, the possible path is
calculated to reach from S2 to T.

As we now have a path from S2 to T, we need to calculate a path from S0 to S2 so that we


can ultimately reach T from S0. Now we calculate the possible path from S0 to S2 using the
steps discussed above as shown in Illustration 15.

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

Determining next outer bounding rectangle during backtracking


Although the vertex for next outer bounding rectangle (required for backtracking) can
be the next coordinate on the extended diagonal (as shown in Illustration 13,14), a
simple technique can greatly reduce the number of backtracking steps of both source
and target.

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.

if(edge1 contains obstacle) {

if(edge4 contains obstacle) {

source outer rectangle vertex = S'

} else {

source outer rectangle vertex = S'''

} else {

if(edge4 contains obstacle) {

source outer rectangle vertex = S''

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

Illustration : Sub paths formed during


backtracking. Final path from S to T obtained by
combining the sub paths.
Due to the presence of wall (green blocks), S and T has to backtrack to S' and T'
positions respectively. Here we obtain three sub paths which are:

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

Step 4: Correct these discontinuities by adding the missing cell coordinates.


END

Asymmetric Bounding Rectangles


Simple Case
A problem arises when the bounding rectangle is asymmetric as shown in Illustration .

Illustration : Case of asymmetric bounding


rectangle (br63)
The solution to this problem is to insert required number of dummy nodes between 'S' and
'T' so that the new bounding rectangle becomes symmetric as shown in

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.

Illustration : The bounding rectangle (br66) is


made symmetric by adding required no. of dummy
nodes

S and T lying on same straight line (vertical or horizontal)

This case arises when both 'S' and 'T' lie on same straight line (horizontal or vertical) as
shown in Illustration 20.

Illustration : Another case of asymmetric


bounding rectangle (br61)
The case can be converted to “[A] Symmetric Bounding Rectangle (Simple Case)” case
by adding dummy nodes as shown in Illustration 21.

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

(x2,y2) = diagonally opposite corner of the bounding rectangle


obstacle = a set coordinates defining the obstacle (wall)

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.

Illustration : Transparent boundary of the game


field
The hopping points are always taken from the diagonal line joining the source and target. Because
of property of the algorithm, it is not able to compute paths when a complex structure of wall,
as shown in Illustration 23, is present. This is the reason why Blackmamba implementation
enters infinite recursion for such obstacles.

Viper – path finding algorithm


Assumptions
This algorithm assumes game field as follows:

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.

● The border of the gamefield are transparent unless there is wall.

● Wall is the only thing that a snake can strike to.

Illustration : The game field (unfolded Envelop)

● There can be multiple wall in the same gamefield.

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

Principal and implementation of this algorithm.


This algorithm will not deal with finding only one shortest path instead it calculates multiple path
between the source and the destination, and all of these path have the same distance, the shortest
distance. Actually the result is not in the form of multiple path, merely it is a collection of the
points that it must pass through. It is the position of the points that make the path multiple. It is
described later in more detail.

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.

Illustration : GraphIn the above graph

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.

9 A gate must be common to only two FOR.

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

different ways: via 3 or 5.


Some data that are associated with the rectangle (node in the graph) is shown below.

Illustration : Data associated with each node


4. Finally after all these calculation, we can calculate the path between two FOR's, the source and the
destination with shortest distance. When two points (source and target) are given we can determine the
FOR's, they lie in and can compute the path between them.

Illustration : Path for a sample case.

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

For dividing the Game field into fundamental open rectangle:

The algorithm involves slicing the gamefield in cyclicorder in anti-


clockwise direction starting with the left edge. As the game field
initially has no terminating edge (as envelope) we start with
(visually) leftedge of the game field.

Illustration 8: Step 1 (a)


1. Initially starting from the Zeroth coordinate move to

both sides until it strike to wall(unit).Name it Fundamental Open Rectangle (FOR1 and FOR2
or Just R1 and R2). Illustration8 and 9.

2. Now the gamefield has shrinked to as shown in


Illustration10. (It now has changed to cylindrical shape
from envelope shape.)

3. Moving in anticlockwise direction, Slice fromIllustration 9: Step 1 (b)

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)

(cylinder)). From this step onwardthe sliced game field


would be bounded.

4. Now try to slice rectangle from top left, bottom left,bottom


right and topright respectively. Here we fail to slice the
rectangle from topleft and bottomright as there is wall(unit)
at the edge.

We can now create two new rectangles from bottomleftStep-2 and


topright namely R5 and R6. Illustration13.

5. Now slice away the boundary layer of the gamefield

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.

Illustration : Sliced Game Field with no


wall

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

Illustration STAGE-5 represents the state when game is being played

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

top management accordingly.

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

microcomputer or a mainframe. In either case, planning system selection and acquiring

experienced help where necessary pay off in the long run.

There are various important factors, which should be considered prior to system

selection. They are:

 Define system capabilities that make sense for the college.

 Specify the magnitudes of the problem; that is, clarify section entails a few

peripherals or a major decision concerning the mainframe.

 Hardware and software should be considered as a package.

 Develop a time frame for the selection process.

 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

conductive to implementation are prerequisites for system acquisition.

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

in which the system is being installed.

10.1.2 System specifications: System specification must be clearly defined. These

specifications must reflect the actual applications to be handled by the system and include

system objectives, Flowcharts, input-output requirements, file structure and cost.

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

fact, match his/her claims, especially system performance.

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

System chosen goes though contract negotiation before implementation.

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: Commit statistics for iSnake subversion


repository at http://isnake.svn.sourceforge.net

Illustration 10 shows the svn commit statistics for the isnake code repository at

sourceforge. We collaborated on project documents (including prototype designs, project

plan, TODO list, etc) using WIKI (http://isnake.wiki.sourceforge.net).

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 2 Integration (Oct. 06, 2007) successful testing of basic version of

multiplayer snake game

● Phase 3 Integration (Feb 17 26, 2008) – integration of all the modules for iSnake

0.1 Beta release.

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

conforming to Javadoc standards.

Illustration : Screen shot of a snippet of source code showing method comments

conforming to javadoc standards.

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 limitations of present implementation of iSnake are:

● 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

game server in unpredictable situations cannot be handled properly.

● iSnake's Game Server Manager (iSnake – GSM) located at http://isnake.sf.net is

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

Sugar Desktop environment). The presence of several connectivity

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

using OLPC laptops can be used as a platform for iSnake's deployment.

● As iSnake game server communicates with remote playing using a well defined

and very simple protocol (Refer to ANNEX D), iSnake clients programmed in

other programming platform like Flash, Python, etc can be developed.

Conclusion

We were successful in creating a multiplayer version of traditional snake game. The

computer controlled intelligent opponents have been successfully tested in the game is a

unique feature of iSnake.

We learned several project management techniques used by professionals to develop

large scale project. The experience of working in team and integration of modules

developed independently, with just requirement specifications, is a very important

achievement for the iSnake team.

10.2 future scope:

 Inhibited only by creativity and available technology

 Use game for skills based trainings.

78
 Important as learning point of view for children

 Use for understand technology

 Best for Education

 Virtual Reality Gaming (FIFA)

 Augmented Reality

 Motion Capture

 Cloud Gaming

 Quantum Computing and Gaming

 Emerging Trends

 Way of sharing technology

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

You might also like