Java Programming - Creating A Snake and Ladders Game and Object Oriented Concepts
Java Programming - Creating A Snake and Ladders Game and Object Oriented Concepts
TECHNOLOGY
Acknowledgment
This was a great opportunity for me to put into practice which we learned in few lectures
and my own development knowledge on Java Programming.
First and foremost I would our sincere graduate to My Java Programming lecturer
Mr.Dilhan Thilakarathne for his great guidance in this project.
And special thanks goes to Mr.Balachandran Gnanasekaraiyer who thought me the
concepts on Java, object oriented methods and Harvard referencing which help on this
project as well.
Finally, I would like to thank each and every person who helped me in numerous ways
to make this project a success.
2
Java Programming (AAP004-3-2-JP)
Table of contents
Acknowledgment...............................................................................................................2
Table of contents...............................................................................................................3
Assumptions......................................................................................................................4
Classes...........................................................................................................................5
Objects...........................................................................................................................6
Abstraction.....................................................................................................................7
Encapsulation.................................................................................................................7
Inheritance......................................................................................................................8
Polymorphism................................................................................................................8
Logical Design...................................................................................................................9
Pseudo code....................................................................................................................11
Screen Design.................................................................................................................17
Test Plans........................................................................................................................21
Special Features..............................................................................................................23
Limitations........................................................................................................................24
References.......................................................................................................................25
Conclusion.......................................................................................................................26
Conclusion
3
Java Programming (AAP004-3-2-JP)
Assumptions
That two players are playing the game simultaneously and sharing the same
computer and input/output devices.
That player knows the aim of the game be the first player to reach the end by
moving across the board from First Square to the hundred square.
That player knows that when the disk lands in a square with base of the ladder
that he have to move up and when he lands on a square with a snake that he
have to return to a less valued square .
That when two players are playing that the both players have equal winning
probability.
That player has basic knowledge how to deal with computer based graphical
user interfaces.
That user who runs this application have installed Java run time (JRE)
environment on his running machine.
4
Java Programming (AAP004-3-2-JP)
Classes
The following table shows the classes which used in this application and included
methods of them.
Class Name Purpose Included Methods/Other
setPlayerScore()
getPlayerScore()
Main Class Provide the main interface to the users Main() method
locate the snake board Changeplayer()
Specialvalues()
Score Card Provide the interface for the score card Scorecard()
Class
5
Java Programming (AAP004-3-2-JP)
Also common methods like paint method, Action performed method will be included in
most of the classes.
Objects
Most of these classes are used in the application are used as instances of them.
Especially the instances ‘control class’ will use in commonly because most of the
application control methods are located in that class.
There will be two instances of player class will be used as player 1 and player 2 for the
two players. Because both players have most common characteristics.
Packages
In this application mainly two packages used .Classes are related to game play is falls
under com.game package and ‘control classes’ will be falls under com.game.option
package.
Getters/Setters
Getters/Setters methods are specially used in player class to retrieve and change the
player information, Location and score.
6
Java Programming (AAP004-3-2-JP)
Abstraction
Encapsulation
7
Java Programming (AAP004-3-2-JP)
Inheritance
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
com.game.Main
Polymorphism
Sierra, Kathy; Bert Bates (2005). Head First Java describes that polymorphism is
means the ability to take more than one form. That means same methods can used in
different behaviors. In this application for example the paint method is used
polymorphism.
8
Java Programming (AAP004-3-2-JP)
Logical Design
To move the Disk though the snake board a 2-Dimentional array is used. There are 100
values in the 2-Dimentional array which is same as the snake board. Nested Loop can
travel trough the array and find the necessary location. According to java API Document
an object of a class ‘Dimension’ can store an X axis and the Y axis of a given array or
an value with having the X axis and the Y axis of the location we can relocate the disk at
a given location.
0,0 0,10
m
Box
n
β = constant distance between frame and snake board, n/m= width, height of a box ,
a=Location retrieved by 2-Dimentional array.
The equation to get the x position location is:
x=β+n*a
9
Java Programming (AAP004-3-2-JP)
x=β+n*4
The equation to get the new Y position location is:
y=β+n*7
The shifting of the players can be done though a simple Boolean logic and player
location and score can be easily retrieve using simple counting methods.
10
Java Programming (AAP004-3-2-JP)
Pseudo code
Function RandomNumber
PASS IN : NOTHING
START
Endfunction
Function TravelLocation
Set moveCount to 1
11
Java Programming (AAP004-3-2-JP)
CALL swiftPlayers
INCREMENT moveCount
END IF
END FOR
END FOR
Endfunction
Swift between the two players
Function SwiftPlayers
PASS IN : Boolean
ELSE IF
END IF
Endfunction
12
Java Programming (AAP004-3-2-JP)
IF currentValue==snakevalue THEN
ELSE
Disk ==NextLocation
END IF
Function SetPlayer
PASS IN : NOTHING
Declare PlayerName as a String value
PlayerName = Display ” Enter Player Name”
PASS OUT : Player Name
Endfuction
13
Java Programming (AAP004-3-2-JP)
Function GetPlayer
PASS IN : Nothing
Endfuction
Winning Message
Function Winnermsg
PASS IN : UserLocation
Endfunction
14
Java Programming (AAP004-3-2-JP)
15
Java Programming (AAP004-3-2-JP)
Screen Design
Image
Features User Registration Users can enter their information and register.
Get the Play instructions Users can get play instructions if they need.
Quit the Game Can quit the application.
16
Java Programming (AAP004-3-2-JP)
Image
17
Java Programming (AAP004-3-2-JP)
Image
18
Java Programming (AAP004-3-2-JP)
Image
Features Save Player Statistics Statistics will be saved for each users.
Player Rank Show the player with his rank ‘Beginner’ or
‘Expert’.
19
Java Programming (AAP004-3-2-JP)
Test Plans
20
Java Programming (AAP004-3-2-JP)
21
Java Programming (AAP004-3-2-JP)
Special Features
Audio Stream
Background music and event sounds are provided using java audio streams. All the
methods that provide sound to the application are located in the ‘music’ class and
instances of this class are created to get the sounds.
According to K.Sierra, B.Bates(2005) in their book Head first java describes that in this
audio stream method the file is taken from a input stream so File not found exception,
I/O exception should be handled.
For example the setMusic method in Music class:
throws java.io.FileNotFoundException,
java.io.IOException
The above figure shows that the setMusic method is handling both File not found
exception and I/O Exception
Java Swing
To provide message boxes to users some components in java Swing library is used
.Specially JFrame component and JOptonPane component is used to deliver message
box dialogs.
Limitations
22
Java Programming (AAP004-3-2-JP)
Two players have to play the game simultaneously and can NOT play only by a
single user.
The two players who have registered first have to play the game and player
names cannot be change in middle of a game.
Players have to share the same hardware resources and can NOT play using
networked environments.
When player finishes a game he has to press ‘new game’ button to start a new
game without resetting the board automatically.
23
Java Programming (AAP004-3-2-JP)
References
Marc Loy, Robert Eckstein (2003). Java Swing. 2nd ed. Unite States: O'Really
Media,Inc.
Kathy Sierra, Bert Bates (2005). Head first Java. 2nd ed. Unite States: O'Really
Media,Inc.
24
Java Programming (AAP004-3-2-JP)
Conclusion
Designing this game with object orientated concepts and java programming language is
a quiet challenge. After several weeks of coding and research I could come up with
efferent solutions which match with the assignment requirements.
25
Java Programming (AAP004-3-2-JP)
APPENDIX
26
Java Programming (AAP004-3-2-JP)
/**
* @author Sudantha Sulochana Gunawardena
* ----------------
* DF08A1ICT
* CB003198
* ----------------
* © Sudantha Gunawardena 2009 All Rights Reserved
* ----------------
* sudantha@vista.aero
* http://sudanthas.blogpspot.com
MAIN CLASS
package com.game; //package infomation
//-------------IMPORTS-----------------
import com.game.option.music;
import java.awt.Color;
import java.awt.Frame; // for the Frame
import java.awt.Toolkit; //toolkit import to Graphics and set screen size
import java.awt.event.ActionEvent; //what to do when action
import java.awt.event.ActionListener; // listern to user interaction
import java.awt.Image;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
//--------------------------------------
//MAIN CLASS
//have to extend the main class to GUI and Action Listers
public class Main extends Frame implements ActionListener,WindowListener
{
27
Java Programming (AAP004-3-2-JP)
//**************************GLOBALDECLARATIONS***********************************
Dimension DIM=new Dimension();
Boolean setplayerflag=false;
Graphics g=null;
//*******************************************************************************************
//*******************************IMAGE DECLARATIONS********************************
Image snakeboard=null;
Image background=null;
Image die=null;
Image reddisk=null;
Image bluedisk=null;
//********************************************************************************************
int[][] board =
{
{100,99,98,97,96,95,94,93,92,91},
{81,82,83,84,85,86,87,88,89,90},
{80,79,78,77,76,75,74,73,72,71},
{61,62,63,64,65,66,67,68,69,70},
{60,59,58,57,56,55,54,53,52,51},
{41,42,43,44,45,46,47,48,49,50},
{40,39,38,37,36,35,34,33,32,31},
{21,22,23,24,25,26,27,28,29,30},
{20,19,18,17,16,15,14,13,12,11},
{1,2,3,4,5,6,7,8,9,10},
28
Java Programming (AAP004-3-2-JP)
};
//*******************************OBJECT CREATION****************************************
//*******************************FRAME*********************************************
this.setBackground(Color.lightGray); // set the frame background color
this.setSize(Toolkit.getDefaultToolkit().getScreenSize()); //set the Frame size as the screen size
this.setLayout(null); //Define the layout Manager
this.setTitle("SnakesSS and Ladders");
this.addWindowListener(this); //add the window Listner
//*********************************************************************************
//*****************************AWT OBJECTS*****************************************
//#Action Buttion#
Button roll=new Button(con.BTN_DIE);
roll.addActionListener(this);
roll.setSize(80,35);
roll.setLocation(675,425);
this.add(roll);
//Menu
29
Java Programming (AAP004-3-2-JP)
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi4);
//*********************************************************************************
reset(); // reset
//*****************************MAIN METHOD************************************************
public static void main(String[] args) throws FileNotFoundException, IOException
{
}
//**************************************************************************************
//*****************************ACTIONPERFOMEDMETHOD**************************
30
Java Programming (AAP004-3-2-JP)
if(con.BTN_DIE.equals(actionCommand))
{
try {
msc.dieMusic();
} catch (FileNotFoundException ex)
{
con.errmsg();
}
else if(con.BTN_EXIT.equals(actionCommand))
{
System.exit(0);
}
else if(con.BTN_ABOUT.equals(actionCommand))
{
about abt=new about(); // show about class
31
Java Programming (AAP004-3-2-JP)
}
else if(con.BTN_HOW_TO.equals(actionCommand))
{
inst ins =new inst();
}
else if(con.BTN_SCORE.equals(actionCommand))
{
scorecard scr=new scorecard();
}
else if(con.BTN_MUTE.equals(actionCommand))
{
try {
msc.setMusic(false); // mute sound
} catch (FileNotFoundException ex)
{
con.errmsg();
con.errmsg();
}
//***************************************************************************************
//*****************************PAINT METHOD*****************************************
public void paint(Graphics g)
{
snakeboard= tool.getImage(con.graphic_path);
background= tool.getImage(con.back_pic); //background picture
reddisk=tool.getImage(con.RedDisk);
bluedisk=tool.getImage(con.BlueDisk);
//Draw Strings
g.drawImage(background, 0, 0,this);
32
Java Programming (AAP004-3-2-JP)
die= tool.getImage(con.one_path);
g.drawImage(die, 700, 550, this);
else if(dieval==2)
{
die= tool.getImage(con.two_path);
g.drawImage(die, 700, 550, this);
}
else if(dieval==3)
{
die= tool.getImage(con.three_path);
g.drawImage(die, 700, 550, this);
}
else if(dieval==4)
{
die= tool.getImage(con.four_path);
g.drawImage(die, 700, 550, this);
}
else if(dieval==5)
{
die= tool.getImage(con.five_path);
g.drawImage(die, 700, 550, this);
}
else if(dieval==6)
{
die= tool.getImage(con.six_path);
g.drawImage(die, 700, 550, this);
}
33
Java Programming (AAP004-3-2-JP)
g.setColor(Color.darkGray);
g.setFont(con.myfont);
g.drawString(con.PLAYER+" 's Turn !", 50, 700); // print whos turn
//*****************************************************************************************
//*****************************PLAYER SWIFT***************************************
if(setplayerflag==true &&check_die<100 )
{
setplayerflag=false;
player2.setValue(dieval);
check_die=player2.getValue();
System.out.println("p2 : "+check_die);
setDisk(check_die,true);
con.PLAYER=con.PLAYER2_NAME;
repaint();
//y_P2=player2.setY(dieval);
}
check_die=player1.getValue();
System.out.println("p1 :"+check_die);
setDisk(check_die,false);
roll.setEnabled(false);
//
con.PLAYER=con.PLAYER1_NAME;
repaint();
34
Java Programming (AAP004-3-2-JP)
}
else
{
if(setplayerflag==false)
{
player2.win();
roll.setEnabled(false);
//*********************************************************************************
P1_x=20;
P1_y=600;
P2_x=15;
P2_y=585;
repaint();
int x1=0;
int y1=0;
int x2=0;
int y2=0;
35
Java Programming (AAP004-3-2-JP)
int i=0;
int j=0;
randomNum = check_die;
for(i=0;i<board.length;i++)
{
for(j=0;j<board.length;j++)
{
if (board[i][j]==check_die)
{
dime.width=i;
dime.height=j;
break;
}
//System.out.println(check_die);
//System.out.println(""+y+","+x);
if(user==false)
{
y1=dime.width;
x1=dime.height;
special(user);
P1_x=const_val+60+x1*Colum_size-35;
P1_y=hight-40+y1*(Colum_size);
//set special
repaint();
}
else if(user==true)
{
36
Java Programming (AAP004-3-2-JP)
y2=dime.width;
x2=dime.height;
special(user);
P2_x=const_val+60+x2*Colum_size-30;
P2_y=hight-40+y2*(Colum_size);
repaint();
if(check_die==9)//(7,7)
{
if (us_er==true)
{
x2=7;
y2=7;
player2.current_val=28;
}
else if(us_er==false)
{
x1=7;
y1=7;
player1.current_val=28;
x2=5;
y2=3;
player2.current_val=66;
37
Java Programming (AAP004-3-2-JP)
}
else if(us_er==false)
{
x1=5;
y1=3;
player1.current_val=66;
}
else if(check_die==78)//(1,3)
{
if (us_er==true)
{
x2=3;
y2=1;
player2.current_val=84;
}
else if(us_er==false)
{
x1=3;
y1=1;
player1.current_val=84;
}
}
else if(check_die==94) //(1,5)
{
if (us_er==true)
{
x2=7;
y2=3;
player2.current_val=68;
}
else if(us_er==false)
{
x1=7;
y1=3;
player1.current_val=68;
38
Java Programming (AAP004-3-2-JP)
if (us_er==true)
{
x2=8;
y2=7;
player2.current_val=29;
}
else if(us_er==false)
{
x1=8;
y1=7;
player1.current_val=29;
}
else if(check_die==57) //(8,1)
{
if (us_er==true)
{
x2=1;
y2=8;
player2.current_val=19;
}
else if(us_er==false)
{
x1=1;
y1=8;
player1.current_val=19;
}
else if(check_die>99)
{
39
Java Programming (AAP004-3-2-JP)
}
}
//*****************************WINDOW ACTIONS*************************************
public void windowOpened(WindowEvent e) {
PLAYER CLASS
package com.game; //package infomation
public class player
{
int x=0,y=0;
//*******************************OBJECT CREATION***********************************
control con=new control();
//**********************************************************************************
int current_val=0; // keep the current position of the player
int score=0; // keep the player score
//set the player name
public void setPlayerName()
{
//assign the player name to the PlayerName String
}
//get the player name
public String getPlayerName()
{
String getName = con.PLAYER; // retrive to Player Name
return getName;
}
40
Java Programming (AAP004-3-2-JP)
int total = 0;
if (current_val>=95 && val>=4)
current_val=100;
}
else
{
total=current_val+val;
current_val = total;
}
}
public int getValue()
{
int val=0;
val=current_val;
return val;
}
public void setScore(int newScore)
{
score=score+newScore;
}
public int getscore()
{
int current_score=0;
current_score=score;
return current_score;
}
public void win()
{
msg winner=new msg();
setScore(100);
winner.setVisible(true);
}
}
MSG CLASS
package com.game; //package infomation
public class msg extends Frame implements ActionListener
{
java.awt.Font myfont =new java.awt.Font("Arial",Font.TRUETYPE_FONT,18);
Image win=null;
//*******************************OBJECT CREATION***********************************
control con=new control();
//****************************************************************************************
//Constrcutor of the class
public msg()
{
41
Java Programming (AAP004-3-2-JP)
//*******************************FRAME*********************************************
this.setSize(450, 150);
this.setTitle(con.PLAYER+" is Winner !");
this.setLayout(new FlowLayout());
this.setResizable(false);
this.setAlwaysOnTop(true);
this.setLocation(450, 150);
//*********************************************************************************
//*****************************AWT OBJECTS*****************************************
Button btnok=new Button(con.BTN_OK);
btnok.setSize(75,50);
btnok.setLocation(this.getX()-10,this.getY()-150);
btnok.addActionListener(this);
this.add(btnok);
//****************************************************************************************
}
//*****************************PAINT METHOD********************************************
public void paint(Graphics g)
{
Toolkit tool = Toolkit.getDefaultToolkit();
win=tool.getImage(con.win);
g.drawImage(win,0,0, this);
g.setColor(Color.DARK_GRAY);
g.setFont(myfont);
g.drawString(con.PLAYER, 50, 50);
}
//****************************************************************************************************
//*****************************ACTION PERFOMED METHOD***********************************
public void actionPerformed(ActionEvent e)
{
String actionCommand=e.getActionCommand();
if(con.BTN_OK.equals(actionCommand))
{
this.setVisible(false);
scorecard sc=new scorecard();
}
}
}
CONTROL CLASS
package com.game;
//-------------IMPORTS-----------------
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class control
42
Java Programming (AAP004-3-2-JP)
{
//*****************************ALL GRAPHIC PATHS*****************************************************************
final String
graphic_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\Snakes&Ladears.jpg";
final String back_pic="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\background.jpg";
final String one_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\one.jpg";
final String two_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\two.jpg";
final String three_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\three.jpg";
final String four_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\four.jpg";
final String five_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\five.jpg";
final String six_path="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\six.jpg";
final String RedDisk="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\red_die.gif";
final String BlueDisk="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\blue_die.gif";
final String win="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\win.jpg";
final String welcome_img="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\welcome.jpg";
final String scorecard_img="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\scorecard.jpg";
final String instruction_img="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\howto.jpg";
final String about_img="C:\\Users\\admin\\Documents\\APIIT\\JAVA\\Project\\Code\\snake\\src\\com\\snake\\about.jpg";
//***************************************************************************************************************
//*****************************ALL BUTTON NAMES************************************
final String BTN_DIE="Roll";
final String BTN_RESET="New Game";
final String BTN_EXIT="Exit";
final String BTN_OK="OK";
final String BTN_ABOUT="About";
final String BTN_SCORE="Score Card";
final String BTN_WEL_PLAY="Play !";
final String BTN_MUTE="Mute Sounds";
final String BTN_HOW_TO="How to Play";
//**********************************************************************************
//*****************************PLAYER NAMES ***************************************
static String PLAYER="Roll the Die to Start Player";
static String PLAYER1_NAME="Atair";
static String PLAYER2_NAME="Flammer";
public static int player1_score=0;
public static int player2_score=0;
//**********************************************************************************
//*****************************OTHER************************************************
Dimension Diemt =new Dimension();
Dimension genbtn=new Dimension(50,25); //give dimention to general buttons;
//**********************************************************************************
//*****************************FONTS***********************************************
//basic font
java.awt.Font myfont =new java.awt.Font("Arial",Font.TRUETYPE_FONT,18);
//small font
java.awt.Font smallfont =new java.awt.Font("Arial",Font.PLAIN,8);
//**********************************************************************************
43
Java Programming (AAP004-3-2-JP)
//*****************************METHODS***********************************************
public void ShowMain() // show the main Frame
{
Main frm=new Main();
frm.setVisible(true);
}
//***********************************************************************************
//*****************************MESSAGE BOX***********************************************
public void msgbox(String msg,String head)
{
JFrame frame=null;
JOptionPane.showMessageDialog(frame,msg,head,JOptionPane.INFORMATION_MESSAGE);
}
//**********************************************************************************************
MUSIC CLASS
package com.game.option; //package infomation
{
if (status==true)
{
AudioPlayer.player.start(as);
}
else if (status==false)
{
AudioPlayer.player.stop(in);
}
44
Java Programming (AAP004-3-2-JP)
AudioPlayer.player.start(as);
45