java programming - creating a snake and ladders game and object oriented concepts

65
ASIA PACIFIC INSTITUTE OF INFORMATION TECHNOLOGY Sudantha Sulochana Gunawardena (CB003198) Module Code : AAP004-3-2-JP INTAKE CODE : DF08A1ICT ASSIGNMENT TITLE : Java Programming SUBMITTED TO : Mr.Dilhan Thilakarathne HAND IN DATE : 10 th August 2009 HAND OUT DATE : 13 th October 2009

Upload: sudantha-sulochana

Post on 18-Nov-2014

138 views

Category:

Documents


0 download

DESCRIPTION

Creating a Snake and Ladders Game using Java AWT and Object oriented concepts

TRANSCRIPT

Page 1: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

ASIA PACIFIC INSTITUTE OF INFORMATION

TECHNOLOGY

Sudantha Sulochana Gunawardena

(CB003198)

Module Code : AAP004-3-2-JP

INTAKE CODE : DF08A1ICT

ASSIGNMENT TITLE : Java Programming

SUBMITTED TO : Mr.Dilhan Thilakarathne

HAND IN DATE : 10th August 2009

HAND OUT DATE : 13th October 2009

Page 2: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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

Page 3: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Table of contents

Acknowledgment..............................................................................................................2

Table of contents..............................................................................................................3

Assumptions.....................................................................................................................4

Object Oriented Concepts................................................................................................5

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

3

Page 4: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

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

Page 5: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Object Oriented Concepts

Classes

The following table shows the classes which used in this application and included

methods of them.

Class Name Purpose Included Methods/Other

Player Class To store and retrieve player information

and statistics.

getPlayerName()

setPlayerName()

setPlayerScore()

getPlayerScore()

Main Class Provide the main interface to the users

locate the snake board

Main() method

Changeplayer()

Specialvalues()

Control Class Store all the game controls ,Image

paths and button names

LoadMain()

Dice Class Generate the Dice random number and

provide it

RandomNumber()

Score Card

Class

Provide the interface for the score card Scorecard()

Welcome Class Provide interface to get the player

information

Welcome()

Music Class Store and provide sound facilities setMusic()

5

Page 6: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

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

Page 7: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Abstraction

According to Sun Microsystems (2009) abstraction is selecting needed characteristics

from a class.

For Example Dice may have endless characteristics like color, width, weight from them

for this application development only need few characteristics like current number, so

it’s necessary only to implement methods for needed characteristics.

Encapsulation

According to Kioskea.net(2009) it describes that encapsulation is restrict access to

certain data or in simple words hiding information .

In this application development encapsulation is used it certain matters like the current

value of a player. Using the access modifier ‘private’ the current value of a player is

hidden and given access only by its class.

Also in a another case the player count should be accessed by several classes in the

application so using access modifier ‘public ’ it given the access to the other classes .

7

Page 8: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Inheritance

Meyer, Bertrand (1997). Object-Oriented Software Construction, describes that

Inheritance in object oriented programming is a relationship with a abstract classes.

Most of the classes which are visible for uses are inheritances from java.awt abstract

class for example following diagram shows the inheritance of the main class in the

application.

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

Page 9: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

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.

β = 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

The equation to get the y position location is:

y=β+m∗a

9

Snake board

Box

0,0 0,10

n

β

m

Frame

Page 10: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

When a location with a snake or a ladder occurs there should be a proper way of

landing on the directed location. Logic for this when a number of a location with a snake

or ladder is occurred you have to redirect to the directed location .Using the same

equation above this can be achieved inside a conditional clauses like IF,ELSE or a

SWITCH .

For demonstration purposes if we think that the number occurred and it should be

redirected to the new location which have the array dimension of 4, 7

The equation to get the new X position location is:

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

Page 11: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Pseudo code

Generate the Random Number Between 1-6

Function RandomNumber

PASS IN : NOTHING

START

declare Random Number

set Integer MAX to 5

RandomNumber = GenerateRandam Number(MAX)

PASS OUT : Random Number

RETURN with Random Number

Endfunction

11

Page 12: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Move the disk on the board

Function TravelLocation

PASS IN : Random Number

declare board(100,100) as integer

declare Die1

declare Die2

Set moveCount to 1

FOR each row on the board

FOR each column on the board

IF(board(row,colum) is occupied THEN

CALL swiftPlayers

INCREMENT moveCount

END IF

END FOR

END FOR

PASS OUT : Row,Colum

12

Page 13: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Endfunction

Swift between the two players

Function SwiftPlayers

PASS IN : Boolean

declare PlayerFlag Boolean to true

IF PlayerFlag value is True THEN

Set PlayerFlag Value to False

ELSE IF

PlayerFlag value is False THEN

Set PlayerFlag Value to True

ELSE

END IF

PASS OUT : Boolean

Endfunction

13

Page 14: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Travel though snake and ladders

IF currentValue==snakevalue THEN

Move the Disk to NewLocaton

ElSE IF currentValue==Laddervalue THEN

Move the Disk to NewLocation

ELSE

Disk ==NextLocation

END IF

Set/Get Player Name

Function SetPlayer

PASS IN : NOTHING

Declare PlayerName as a String value

PlayerName = Display ” Enter Player Name”

PASS OUT : Player Name

Endfuction

14

Page 15: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Function GetPlayer

PASS IN : Nothing

Display ” Enter Player Name is : ”

PASS OUT Player Name

Endfuction

Winning Message

Function Winnermsg

PASS IN : UserLocation

IF UserLocation>=96 AND newDieValue >=4 THEN

Display “You Won ! “

END IF

PASS OUT : NOTHING

Endfunction

15

Page 16: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Set Player Rank

IF userWinningcount ==0 THEN

Display “Noob”

ELSE IF userWinningcount <3 THEN

Display ”Beginner”

ELSE IF userWinningcount >3 THEN

Disply “Expert”

16

Page 17: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Screen Design

Frame Name

Frame Welcome

Frame Title Frame Welcome

Image

Figure 1 – Welcome Screen

Description The above figure shows the welcome frame of the game which provides user registration .Players can enter their names and continue to the game.

Features User Registration Users can enter their information and register.

Get the Play instructions Users can get play instructions if they need.

17

Page 18: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Quit the Game Can quit the application.

Frame Name

Frame main

Frame Title Snake and Ladders

Image

Figure 2 – Main Frame

Description As the figure above this frame the Snake board and the menu will be located, When click the Die button the die will be thrown and the number will be generated. New Game button will be load a new game. And the two disks for players will be located and as the number generation it will be moved in the snake board.

Features Snake Board The Snake board will be located on this Frame

Die Give Which the number to play.

18

Page 19: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Disks The disks will be moved in the snake board.

Frame Name

Frame Instructions

Frame Title How to Play

Image

Figure 3 – How to Play Frame

Description This Frame will provide the game instructions to the player.

Features Play Instructions Provide Player instructions.

19

Page 20: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Frame Name

Frame Score Card

Frame Title Score Card

Image

Figure 4 - Score card

Description Provide users their Play statistics for them

Features Save Player Statistics Statistics will be saved for each users.

Player Rank Show the player with his rank ‘Beginner’ or ‘Expert’.

20

Page 21: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Test Plans

ID Test Description Expected Outcome

Test Data/Test Actions Actual outcome

Welcome Class

1 Test of User 1 Text Field

Accepted Player 1

2 Test of User 2 Text Field

Accepted Player 1

Test of Text Field Validations

Message Box Blank

3 Test of OK Button Show Main Frame

Mouse Click

4 Test of How to use Button

Show how to use Frame

Mouse Click

5 Quit button in welcome Frame

Quit the Application

Mouse Click

6 Test of Quit Button

Quit the Application

Mouse Click

7 Maximize Button in Frame

NOT Maximize the Frame

Mouse Click

Table 2 – Test Plan 1

21

Page 22: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

ID Test Description Expected Outcome

Test Data/Test Actions Actual outcome

Main Class

1 Test menu item ‘New Game’

Reset the Game board

Mouse Click

2 Test menu item ‘Instructions’

Show Instructions

Frame

Mouse Click

3 Test menu item ‘Exit’

Quit the Application

Mouse Click

4 Test menu item ‘Score Card’

Show the Score Card

Mouse Click

5 Test menu item ‘About’

Show the about Frame

Mouse Click

6 Test of Roll Die Button Move the Disks

Mouse Click

7 Test of New Game Button

Reset the Game board

Mouse Click

Table 2 – Test Plan 2

22

Page 23: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

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:

public void setMusic(boolean status)

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.

23

Page 24: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

Figure 4 - Swing JOptionPane

Limitations

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.

24

Page 25: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

References

Sun Microsystems, Inc. (2009). Java 2 SDK SE Developer Documentation. Unite

States: Sun Microsystems, Inc.

Massachusetts Institute of Technology. Java Audio. In: Using

GALAXY/Communicator with Java. Unite States: Computer Science and Artificial

Intelligence Laboratory .

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.

25

Page 26: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

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.

26

Page 27: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

APPENDIX

27

Page 28: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

/**

* @author Sudantha Sulochana Gunawardena

* ----------------

* DF08A1ICT

* CB003198

* ----------------

* © Sudantha Gunawardena 2009 All Rights Reserved

* ----------------

* [email protected]

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

import java.awt.MenuBar; // for Menu

import java.awt.MenuItem;

import java.io.FileNotFoundException; // For Music Files

import java.io.IOException;

//--------------------------------------

//MAIN CLASS

//have to extend the main class to GUI and Action Listers

public class Main extends Frame implements ActionListener,WindowListener

{

28

Page 29: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

static int var_player1=0;

static int var_player2=0;

//**************************GLOBALDECLARATIONS***********************************

Dimension DIM=new Dimension();

Boolean setplayerflag=false;

static int dieval=0;

Graphics g=null;

//*******************************************************************************************

//*******************************IMAGE DECLARATIONS********************************

Image snakeboard=null;

Image background=null;

Image die=null;

Image reddisk=null;

Image bluedisk=null;

//********************************************************************************************

static int check_die=0;

static int P1_x=785;

static int P1_y=500;

static int P2_x=675;

static int P2_y=500;

static int const_val=30; //LOGIC

static int Colum_size=55; //54

static int hight=100;

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

29

Page 30: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

{20,19,18,17,16,15,14,13,12,11},

{1,2,3,4,5,6,7,8,9,10},

};

//*******************************OBJECT CREATION****************************************

player player1 =new player();

player player2 =new player();

music msc=new music();

control con=new control();

Button roll=new Button(con.BTN_DIE);

die rolldie=new die();

msg diskply1=new msg();

Dimension dime=new Dimension();

//***************************************************************************************

//Constrcutor of the class

public Main()

{

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

//new game button

Button btnreset=new Button(con.BTN_RESET);

btnreset.addActionListener(this);

30

Page 31: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

btnreset.setSize(80,35);

btnreset.setLocation(roll.getX(),roll.getY() +55);

this.add(btnreset);

//Menu

Menu m1 = new Menu("Game");

MenuItem mi1 = new MenuItem(con.BTN_RESET);

mi1.addActionListener(this);

MenuItem mi2 = new MenuItem(con.BTN_SCORE);

mi2.addActionListener(this);

MenuItem mi3 = new MenuItem(con.BTN_MUTE);

mi3.addActionListener(this);

MenuItem mi4=new MenuItem(con.BTN_EXIT);

mi4.addActionListener(this);

m1.add(mi1);

m1.add(mi2);

m1.add(mi3);

m1.add(mi4);

Menu m2 = new Menu("Help");

MenuItem mi21 = new MenuItem(con.BTN_HOW_TO);

MenuItem mi31 = new MenuItem(con.BTN_ABOUT);

mi21.addActionListener(this);

mi31.addActionListener(this);

m2.add(mi21);

m2.add(mi31);

MenuBar mb = new MenuBar();

setMenuBar(mb);

mb.add(m1);

mb.add(m2);

//*********************************************************************************

reset(); // reset

}

//*****************************MAIN METHOD************************************************

public static void main(String[] args) throws FileNotFoundException, IOException

{

welcome wel=new welcome(); //create a object of the welcome class

31

Page 32: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

}

//**************************************************************************************

//*****************************ACTIONPERFOMEDMETHOD**************************

public void actionPerformed(ActionEvent e)

{

String actionCommand=e.getActionCommand();

if(con.BTN_DIE.equals(actionCommand))

{

try {

msc.dieMusic();

} catch (FileNotFoundException ex)

{

con.errmsg();

} catch (IOException ex)

{

con.errmsg();

}

dieval=rolldie.rangen(); // get the generated random number to dieval

cplayer(); //call swift player method

}

else if (con.BTN_RESET.equals(actionCommand))

{

//reset

con.msgbox("Get Ready for a new Game ! ","New Game");

this.setVisible(false);

Main newMain= new Main();

player1.current_val=0;

player2.current_val=0;

check_die=0;

this.setVisible(true);

roll.setEnabled(false);

}

else if(con.BTN_EXIT.equals(actionCommand))

{

System.exit(0);

32

Page 33: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

}

else if(con.BTN_ABOUT.equals(actionCommand))

{

about abt=new about(); // show about class

}

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

} catch (IOException ex)

{

con.errmsg();

}

}

}

//***************************************************************************************

//*****************************PAINT METHOD*****************************************

public void paint(Graphics g)

{

Toolkit tool = Toolkit.getDefaultToolkit();

snakeboard= tool.getImage(con.graphic_path);

background= tool.getImage(con.back_pic); //background picture

33

Page 34: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

reddisk=tool.getImage(con.RedDisk);

bluedisk=tool.getImage(con.BlueDisk);

//Draw Strings

g.drawImage(background, 0, 0,this);

g.drawImage(snakeboard, 50, 50,this);

g.drawImage(reddisk,P1_x,P1_y,this);

g.drawImage(bluedisk,P2_x,P2_y,this);

//draw the DIE

if(dieval==1)

{

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

34

Page 35: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

g.drawImage(die, 700, 550, this);

}

else if(dieval==6)

{

die= tool.getImage(con.six_path);

g.drawImage(die, 700, 550, this);

}

g.setColor(Color.darkGray);

g.setFont(con.myfont);

g.drawString(con.PLAYER+" 's Turn !", 50, 700); // print whos turn

}

//*****************************************************************************************

//*****************************PLAYER SWIFT***************************************

public void cplayer() // swfit between two players

{

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

}

35

Page 36: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

else if(setplayerflag==false &&check_die<100)

{

setplayerflag=true;

player1.setValue(dieval);

check_die=player1.getValue();

System.out.println("p1 :"+check_die);

setDisk(check_die,false);

roll.setEnabled(false);

//

con.PLAYER=con.PLAYER1_NAME;

repaint();

}

else

{

if(setplayerflag==false)

{

player2.win();

roll.setEnabled(false);

var_player2=var_player2+10; // set player score

con.player2_score=var_player2;

roll.setEnabled(false);

}

else if(setplayerflag==true)

{

player1.win();

roll.setEnabled(false);

var_player1=var_player1+10; // set player score

con.player1_score=var_player1;

}

}

}

//*********************************************************************************

public void reset()

{

P1_x=20;

36

Page 37: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

P1_y=600;

P2_x=15;

P2_y=585;

repaint();

}

int x1=0;

int y1=0;

int x2=0;

int y2=0;

public void setDisk(int randomNum,boolean user) // move the disks

{

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

37

Page 38: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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)

{

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

}

}

public void special(boolean us_er) // set snake and ladders

{

if(check_die==9)//(7,7)

{

if (us_er==true)

{

x2=7;

y2=7;

player2.current_val=28;

38

Page 39: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

}

else if(us_er==false)

{

x1=7;

y1=7;

player1.current_val=28;

}

}

else if(check_die==36) //(,)

{

if (us_er==true)

{

x2=5;

y2=3;

player2.current_val=66;

}

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;

39

Page 40: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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;

}

}

else if(check_die==54) //(7,8)

{

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)

40

Page 41: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

{

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)

{

}

}

}

//*****************************WINDOW ACTIONS*************************************

public void windowOpened(WindowEvent e) {

}

public void windowClosing(WindowEvent e) {

System.exit(0);

}

public void windowClosed(WindowEvent e) {

System.exit(0);

}

//**********************************************************************************

}

41

Page 42: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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;

}

//set the die

public void setValue(int val)

{

int total = 0;

if (current_val>=95 && val>=4)

42

Page 43: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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

43

Page 44: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

{

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

{

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

//*********************************************************************************

44

Page 45: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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

45

Page 46: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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

{

//*****************************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";

46

Page 47: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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***********************************************

47

Page 48: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

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

//**********************************************************************************

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

}

//**********************************************************************************************

//*****************************ERR HADLING MSG***********************************************

public void errmsg()

48

Page 49: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

{

JFrame err=null;

JOptionPane.showMessageDialog(err,"An Error occured","Error",JOptionPane.ERROR_MESSAGE);

}

//**********************************************************************************************

}

MUSIC CLASS

package com.game.option; //package infomation

{

public void setMusic(boolean status) throws FileNotFoundException, IOException

{

InputStream in = new FileInputStream("C:\\REGGAE.mid");

AudioStream as = new AudioStream(in);

if (status==true)

{

AudioPlayer.player.start(as);

}

else if (status==false)

{

AudioPlayer.player.stop(in);

}

}

49

Page 50: Java Programming - Creating a Snake and Ladders Game and Object oriented concepts

Java Programming (AAP004-3-2-JP)

public void dieMusic() throws FileNotFoundException, IOException

{

InputStream is = new FileInputStream("C:\\Die.wav");

AudioStream as = new AudioStream(is);

AudioPlayer.player.start(as);

}

}

50