Upload
praveenasarathchandra
View
609
Download
2
Embed Size (px)
Citation preview
Hanoi Tower Simulation – Java Programming
Names of Student : Praveena Sarathchandra (CB003403)
Intake Code : DF0931ICT
Subject : Java
Project Title : Java Programming Individual Assignment
Date Assigned : 24th November 2009
Date Due : 15th January 2010
1Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Abstract
This assignment is intended to develop a game to simulate the popular “Hanoi tower” which has been invented by a French mathematician called Edouard Lucas, in 1883.
This mathematical puzzle is using the java technology and its object oriented concepts. This program which I have developed lets the player to choose the playing modes—either manual or auto. This also has the capability of handling any number of disks that the player prefers to have. Player should move all the discs which are initially loaded into left most rod to the right most rod using the minimum number of moves to win the game.
2Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Acknowledgment
I wish to take this opportunity to convey my sincere gratitude for the guidance and assistance of all who helped to make this project a success.
I would like to convey my sincere gratitude upon Mr. Dilhan Thilakaratne, my Java lecturer, who was always helping us out to learn the underlying concepts and the importance of the Java technology.
My heartfelt appreciation is extended to all colleagues and all others who helped in different ways.
3Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
ContentsIntroduction......................................................................................................................................7
Flow charts.......................................................................................................................................8
1. Context level.........................................................................................................................8
Explanation......................................................................................................................................9
Initialization.................................................................................................................................9
Manual Play...............................................................................................................................10
Auto Play...................................................................................................................................10
Object Oriented concepts used......................................................................................................11
Polymorphism............................................................................................................................11
Data Structures used......................................................................................................................12
Implementation..............................................................................................................................13
Source code................................................................................................................................13
Test Cases......................................................................................................................................22
Conclusion.....................................................................................................................................26
Limitations.....................................................................................................................................27
Further Development.....................................................................................................................28
Implement drag and drop functionality..................................................................................28
Implement a method to store top scores of players................................................................28
Implement a Scoring method according to time taken for players to end the game..............28
References......................................................................................................................................29
Figure 1 With manual play..............................................................................................................7Figure 2 With autoplay....................................................................................................................8Figure 3 - Rod1 representation in the array.....................................................................................9
4Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Introduction
Java is one of the most popular programming languages available in the industry. Because of its unique capabilities and robustness it has widespread surpassing other languages.
Java is a “write once – run anywhere” language which means it is platform independent. This is a major reason for its popularity.
This program written in Java simulates the popular math puzzle game—the Tower of Hanoi. It consists of three rods and initially discs are loaded to the first rod in such a way that bigger disc appearing at the bottom.
In this program the player has the option to select any number of discs he wants to have between 3 and 10. This program has the following playing options to choose.
Manual play Auto play
If the player wants to try out the puzzle by himself he can choose the “Manual play”. This is the default playing mode enabled after the program is launched. If the user wants to see a demonstration of how to play the game he can choose the “Auto play” option. This shows how to solve the puzzle step by step.
Player may start the game by picking the top most disc in the first rod and dropping it into one of the other rods. The objective is to move all discs which are initially loaded in the first rod to the right most rod. It is allowed to move any disc which is in the top of the rod but when placing it in another rod it is required that the target rod’s top disc should be bigger—thus smaller discs always appear on top of bigger discs.
To achieve a minimum number of moves and win the game, the following rules should be satisfied.
Cane move only one disc at a time Recently moved disc should not be moved again A legal move happens only when a smaller disc placed on top of a larger disc or if any
disc moved to empty destination rod.
The player may win the game by solving the puzzle in minimum moves.
5Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Flow charts
1. Context level
Figure 1 context flow chart
6Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
7Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Explanation
Initialization User starts the application User enters number of discs he wants to have (n) Initialization is done according to the data gathered. Three arrays for each rod are
initialized so as to keep information about discs and their order. (rod1[n], rod2[n], rod3[n])Another array is created (top_of_rod[3]) to keep top most discs of each rod. Three variables are used to keep records of current index of each rod array. (ci1, ci2, ci3)Another three variables (c1, c2, c3) are used to record number of discs available on each rod.
Disc order is arranged and saved in the array of first rod (rod1). For this an incrementing variable, starting from 1, called “element” is used in such a way that smallest disc (disc1) is represented by the number one, placed inside rod1[0].
Figure 2 - Rod1 representation in the array
After initializing the first rod the user is asked to select the playing mode—manual or auto
8Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Manual Play If manual play is selected:
o User selects which disc to move and to which rod it should be moved
o If selected from-rod has a disc on top, and if to-rod doesn’t have any discs or the
disc on to-rod is bigger than moving disc do the move. o Ex. Moving from rod1 to rod2
From_rod = 0 and to_rod = 1
Variable value Actual rod represented by the variableFrom_rod = 0 / To_rod = 0 Rod1From_rod = 1 / To_rod = 1 Rod2From_rod = 2 / To_rod = 2 Rod3
Remove the moving disc from the from-rod array (ex. Rod1[ci1++] = 0 ) and decrease disc count (C1--)
Insert moving disc into to-rod array. (ex. Rod2[ci2--] = top_of_rod[from_rod]C2++)
o On illegal operations show error
o Check if user has moved all the disc onto rod3, else loop the procedure.
o If minimum movements were achieved show “congratulations”, else tell user to
try with minimum moves.
Auto Play If auto play is selected:
o Generate the order of disc movements
Ex. If the player enters 4 disc, the order generated is as follows:1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1
o If minimum number of moves reached start arranging discs according to
generated order
9Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Object Oriented concepts used
Polymorphism
This concept is used to have different methods which have the same method name but has different argument lists.
Example of usage of polymorphism
public Disc(int width, int id){this.id = id;this.width= width;
}public Disc(){
this.id = 0;this.width = 0;
}
10Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Data Structures used
For this program data structures are being used to represent three rods.
Ex:
public class Stack {
public Disc discs[];
public int top;
}
One stack holds an array of the type “Disc”, which are objects of another class – Disc.
Top variable is increased and decreased according to each successful movement.
Stack is operated using methods such
Pop()
Push()
isEmpty()
isFull()
11Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Implementation
Source code
Class Name: HanoiLayout.java
package gui;
import java.awt.BorderLayout;import java.awt.Choice;import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Label;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import main.Main;
public class HanoiLayout extends JFrame implements ActionListener{
public JPanel panel2; //panel holding rodsprivate JButton btnMove; //"Move" buttonprivate JButton btnNewGame; //"New Game" buttonprivate JButton btnAuto; //"Auto play" buttonpublic JLabel lblMoves; //"Min moves" labelpublic JLabel lblTotMoves; //"Total moves"private Choice selFrom; //"Select from rod" combo boxprivate Choice selTo; //"Select to rod" combo boxpublic int rod_basex[]= new int[3]; //arrays holding x and y public int rod_basey[]= new int[3]; //coordinates for each rods public HanoiLayout(){
//set the title of the framesuper("Hanoi Tower Simulation v1.0 by Praveena Sarathchandra - [email protected]");
this.setLayout(new BorderLayout());
12Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setResizable(false);
//panel creationPanel panel1 = new Panel(new FlowLayout());panel2 = new MidPanel("images/bg.png");panel2.setLayout(null);
Panel panel3 = new Panel(null);
//components for top panel
panel1.setBackground(new Color(237,237,255));panel1.setPreferredSize( new Dimension(0,100));Label lbl1 = new Label("Move disc from ");lbl1.setFont(new Font("arial",Font.BOLD,15));Label lbl2 = new Label("To");lbl2.setFont(new Font("arial",Font.BOLD,15));
selFrom = new Choice();selTo = new Choice();
btnMove = new JButton("Move");btnMove.setFont(new Font("arial",Font.BOLD,15));btnMove.addActionListener(this);
btnNewGame = new JButton("New Game");btnNewGame.setFont(new Font("arial",Font.BOLD,15));btnNewGame.addActionListener(this);
btnAuto = new JButton("Autoplay");btnAuto.setFont(new Font("arial",Font.BOLD,15));btnAuto.addActionListener(this);
selFrom.add("Rod 1");selFrom.add("Rod 2");selFrom.add("Rod 3");selTo.add("Rod 1");selTo.add("Rod 2");selTo.add("Rod 3");
panel1.add(lbl1);panel1.add(selFrom);panel1.add(lbl2);panel1.add(selTo);panel1.add(btnMove);panel1.add(btnNewGame);panel1.add(btnAuto);
//components of panel3panel3.setBackground(new Color(237,237,255));panel3.setPreferredSize( new Dimension(0,100));Label lbl3 = new Label("Minimum moves to win:");
13Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
lbl3.setFont( new Font("arial",Font.BOLD,18));lbl3.setForeground(Color.darkGray);lbl3.setBounds(50, 40, 220, 30);
Label lbl4 = new Label("Total moves:");lbl4.setFont( new Font("arial",Font.BOLD,18));lbl4.setForeground(Color.darkGray);lbl4.setBounds(600, 40, 100, 30);
lblMoves = new JLabel("0");lblMoves.setFont( new Font("arial", Font.BOLD, 18));lblMoves.setBounds(lbl3.getX() + 220, lbl3.getY(), 50,30 );
lblTotMoves = new JLabel("0");lblTotMoves.setFont( new Font("arial", Font.BOLD, 18));lblTotMoves.setBounds(720, lbl4.getY(), 50,30 );
//adding components to the panelspanel3.add(lbl3);panel3.add(lbl4);panel3.add(lblMoves);panel3.add(lblTotMoves);
//adding panels into framethis.add(BorderLayout.NORTH, panel1);this.add(BorderLayout.CENTER, panel2);this.add(BorderLayout.SOUTH, panel3);
this.setSize(800,600);this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String actionBtn = e.getActionCommand();int getn = 3;String user_discs;
if( "Move".equals(actionBtn)){ //if clicked button is "Move"
if(selFrom.getSelectedIndex() != selTo.getSelectedIndex()){Main.doMove(selFrom.getSelectedIndex(),selTo.getSelectedIndex() );
}else {JOptionPane.showMessageDialog(null, "Select different rods");
}
} if( "New Game".equals(actionBtn)){ //if clicked button is "New Game"
14Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
user_discs = JOptionPane.showInputDialog(null,"Enter number of discs you want to have (3-10)", getn);
try{getn = Integer.parseInt(user_discs);
if(getn >= 3 && getn <=10){this.setVisible(false);Main.initialize(getn); //if input discs are vaild initilize the gamethis.setVisible(true);
}else{JOptionPane.showMessageDialog(null, "Please input number of discs
between 3 and 10"); }
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "Please input a number"); //if user
inputs non-numeric characters}
}if( "Autoplay".equals(actionBtn)){
Main.doAuto();
}this.setVisible(true);
}
}
class MidPanel extends JPanel{
private Image backgroundImage;
public MidPanel(String fileName) { try{
backgroundImage = ImageIO.read(new File(fileName)); //load background image to panel2
}catch(IOException e){ System.err.println("Unable to load background image");
} }
public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(backgroundImage, 0, 0, null); }
}
15Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Class Name: Disc.java
package gui;
public class Disc {public int width = 0;public int id = 0;public static final int HEIGHT = 16;
public Disc(int width, int id){this.id = id;this.width= width;
}public Disc(){
this.id = 0;this.width = 0;
}
}
16Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Class Name: Main.java
package main;import javax.swing.*;import gui.*;public class Main {
static HanoiLayout layout;static Stack rods[]; //stack holding each rodstatic JLabel ldiscs[]; //holds each label objectstatic int getn; //holds number of discs as entered by user
public static void main(String[] args) {
Main main = new Main();main.genLayout();
getn = 3;
String user_discs = JOptionPane.showInputDialog(null,"Enter number of discs you want to have (3-10)", getn);
try {getn = Integer.parseInt(user_discs);
if (getn >= 3 && getn <= 10) {layout.setVisible(false);initialize(getn);layout.setVisible(true);
} else {JOptionPane.showMessageDialog(null,
"Please input number of discs between 3 and 10");}
} catch (NumberFormatException e1) {JOptionPane.showMessageDialog(null, "Please input a number");
}
}
public static void initialize(int n) {
// reset the panel componentslayout.panel2.removeAll();layout.panel2.updateUI();layout.lblTotMoves.setText("0");
//set starting x and y coordinates for rodslayout.rod_basex[0] = 50;layout.rod_basex[1] = 285;layout.rod_basex[2] = 525;
layout.rod_basey[0] = 323;layout.rod_basey[1] = 323;layout.rod_basey[2] = 323;
17Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
int minMoves = (int) Math.pow(2, n) - 1;
rods = new Stack[] { new Stack(n), new Stack(n), new Stack(n) };
for (int i = 0; i < n; i++) {rods[0].push(new Disc(215 - (i * 20), i + 1));layout.rod_basey[0] -= 16;
}
ImageIcon image = new ImageIcon("images/disc.png");
ldiscs = new JLabel[n];
for (int j = 0; j < n; j++) {ldiscs[j] = new JLabel(image);
}
generateFirstRod(n);
layout.lblMoves.setText(Integer.toString(minMoves));
}
public void genLayout() {layout = new HanoiLayout();
}
public static void generateFirstRod(int n) {for (int i = 0; i < n; i++) {
ldiscs[i].setBounds(50 + (i) * 10, 340 - (i + 1) * 16,rods[0].discs[i].width, 16);
layout.panel2.add(ldiscs[i]);
}}
public static void doMove(int fromRod, int toRod) {int basex = 0, basey = 0;int moving_disc_id = 0;
// check if user popping from empty rodtry {
moving_disc_id = rods[fromRod].discs[rods[fromRod].top].id;
} catch (ArrayIndexOutOfBoundsException e) {JOptionPane.showMessageDialog(null, "Selected from-rod is empty!");return;
}
18Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
// check if move is legal
if (rods[toRod].top == -1|| moving_disc_id > rods[toRod].discs[rods[toRod].top].id) {
Disc popped = rods[fromRod].pop();
rods[toRod].push(popped);
basex = layout.rod_basex[toRod];basey = layout.rod_basey[toRod];
ldiscs[moving_disc_id - 1].setLocation(basex + 10 * (moving_disc_id - 1), basey);
layout.rod_basey[toRod] -= 16;layout.rod_basey[fromRod] += 16;
int totmoves = Integer.parseInt(layout.lblTotMoves.getText());++totmoves;layout.lblTotMoves.setText(Integer.toString(totmoves));
checkGameEnd();
} else {JOptionPane
.showMessageDialog(null,"Illegal move! You cannot place large disc on top of
a small discs");return;
}
}
public static void checkGameEnd() {
if (rods[2].isFull()) {if (layout.lblTotMoves.getText().equals(layout.lblMoves.getText())) {
JOptionPane.showMessageDialog(null,"*****Congratulations!*****\n\n\tYou win");
} else {JOptionPane
.showMessageDialog(null,"Well done!. Now try with the minimum
moves to win the game");}
}}
public static void doAuto() {
doAuto(getn, 0, 2, 1);}
19Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
static void doAuto(int n, int source, int dest, int inter) {
if (n == 1) {doMove(source, dest);
} else if (n > 1) {
doAuto(n - 1, source, inter, dest);
doMove(source, dest);
doAuto(n - 1, inter, dest, source);}
}
}
20Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Cases
Test Case : 1
Summary Getting the number of disks that player needs to have
Preconditions application launched
Required Input Data number of disks
Test Case Execution Steps 1. Launch application2. Read number of disks3. Click on “Next” button
Expected Outcome Initialize stacks to hold disks of each rod. Load disks into first rod. Initialize variable to hold number of movements. Show minimum numbers of moves to win.
Actual Outcome Stacks initialized and GUI was updated according to the data structure which was populated.
Test Case : 2
Summary Entering non-numeric characters as number of discs
Preconditions application launched
Required Input Data number of disks
Test Case Execution Steps 1. Launch application2. Read number of disks3. Click on “Next” button
Expected Outcome Validate input. Show error if non-numeric characters entered.
Actual Outcome “Please input a number” error is shown
Test Case : 3
Summary Selecting the playing mode
Preconditions Application launched and number of disks chosen.
Required Input Data Clicking on “Autoplay”
Test Case Execution Steps 1. Select the playing mode2. Click on “Start” button
21Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Expected Outcome Start the time counter. Start the chosen game mode
Actual Outcome Time counter is not implemented. Autoplay is started after clicking the button. Autoplay steps are not visible to the user.
Test Case : 4
Summary Moving a disc in manual mode
Preconditions Playing mode chosen. Time counter started.
Required Input Data Selection of “from” rod and “to” rod
Test Case Execution Steps 1. Select the “from” rod from the combo box which has a bigger disc in it
2. Select the “to” rod from the combo box which already has a smaller disc in it
3. Click on “move” button
Expected Outcome Deny the movement. Show error saying it is not allowed
Actual Outcome Timer isn’t implemented.
Test Case : 5
Summary Moving a disc in manual mode
Preconditions Playing mode chosen. Time counter started
Required Input Data Selection of “from” rod and “to” rod
Test Case Execution Steps 1. Select the “from” rod from the combo box which already has a smaller disc in it
2. Select the “to” rod from the combo box which has a bigger disc in it
3. Click on “move” button
Expected Outcome Do the move. Increase the movement counter by one
Actual Outcome Disc are moved from the from- rod to the to-rod. Movement counter increased by one
Test Case : 6
Summary Moving the same disk twice or more times, in a row.
Preconditions Playing mode chosen. Time counter started
22Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Required Input Data Selection of “from” rod and “to” rod
Test Case Execution Steps 1. Select the “from” rod from the combo box which has the previously moved disc.
2. Select the “to” rod from the combo box which has a bigger disc in it
3. Click on “move” button
Expected Outcome Show Tip “You should not move the same disk twice In a row to achieve the minimum moves to win the game”
Actual Outcome Tip is not shown.
Test Case 7
Summary Selecting “from-rod” and “to-rod”
Preconditions Playing mode chosen. Time counter started
Required Input Data Selection of “from” rod and “to” rod
Test Case Execution Steps 1. Select a rod from the “from-rod” combo box
2. Select the same rod in the “to-rod”3. Click on “move” button
Expected Outcome Show error “Illegal move”
Actual Outcome Error is shown after clicking on the move button
Test Case : 8
Summary Ending the game with minimum moves.
Preconditions All discs except the smallest disc moved to third rod. Move counter is less than minimum required moves.
Required Input Data Smallest disc is moved to the third rod
Test Case Execution Steps 1. Select the “from” rod which has the smallest disc in it.
2. Select “to” rod as the third rod3. Click on “move” button
Expected Outcome Show “congratulations” and ask the player if he wants to play again with more discs.
Actual Outcome Show “*****Congratulations!*****You win”
Test Case : 9
23Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Summary Ending the game with moves greater than minimum moves
Preconditions All discs except the smallest disc moved to third rod. Move counter is greater than minimum required moves.
Required Input Data Smallest disc is moved to the third rod
Test Case Execution Steps 4. Select the “from” rod which has the smallest disc in it.
5. Select “to” rod as the third rod6. Click on “move” button
Expected Outcome Show minimum number of moves. Ask the player if he wants to see a demonstration
Actual Outcome
Test Case : 10
Summary Ending the game before player succeeds
Preconditions Game is started.
Required Input Data Clicking on the “End Game” button while playing
Test Case Execution Steps 1. Start the game2. Click on “End game” button
Expected Outcome Asking user whether he really needs to terminate the current session. If so show playing modes again.
Actual Outcome
Test Case : 11
Summary Playing the game with “Autoplay” enabled
Preconditions Autoplay is chosen as the playing mode. Number of disks is entered by user.
Required Input Data Clicking on the auto play button
Test Case Execution Steps Click on the Autoplay button
Expected Outcome Start showing autoplay steps
Actual Outcome Final step is displayed
Test Case : 12
Summary Marks calculation
Preconditions Game is finished
Required Input Data Total score
24Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Case Execution Steps Start gameFinish game
Expected Outcome Show final marks
Actual Outcome Couldn’t implment
Conclusion
By doing this assignment I humbly would like to say that I gained a lot of experience in terms of
java’s practical implementation. The object oriented methods that we have learned from the
lessons in the class were practiced in real life. It was a good opportunity for us to apply our
knowledge of java.
I also got the chance to do a lot of research when coding this program. This made myself to
sharpen my techniques and knowledge of OOP concepts.
Overall I personally think this program was as success and all the guidelines were followed
without any mistake.
25Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Limitations
User cannot use drag and drop features to move disks between the rods. No mechanism to store high scores recorded by players. This program has the capacity of handling any number of disks that user prefers to have,
but it is limited to a certain number (3-10) as far as the space available in the program window is concerned.
26Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Further Development
Implement drag and drop functionality
Implement a method to store top scores of players.
Implement a Scoring method according to time taken for players to end the game
Animate autoplay movements
27Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
References
A Sun Developer Network. (2010). Lesson: Using Swing Components.Available: http://java.sun.com/docs/books/tutorial/uiswing/components/index.html. Last accessed 10 February 2010.
28Asia Pacific Institute of Information Technology