Java Programming (Individual Assignment)
Java Programming (Individual Assignment)
Subject : Java
1
Asia 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.
2
Asia 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.
3
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Contents
Introduction......................................................................................................................................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
4
Asia 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.
The player may win the game by solving the puzzle in minimum moves.
5
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Flow charts
1. Context level
6
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
7
Asia 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].
After initializing the first rod the user is asked to select the playing mode—manual or
auto
8
Asia 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
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++)
Auto Play
If auto play is selected:
o Generate the order of disc movements
9
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Polymorphism
This concept is used to have different methods which have the same method name but has
different argument lists.
}
public Disc(){
this.id = 0;
this.width = 0;
10
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
For this program data structures are being used to represent three rods.
Ex:
One stack holds an array of the type “Disc”, which are objects of another class – Disc.
Pop()
Push()
isEmpty()
isFull()
11
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Implementation
Source code
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 HanoiLayout(){
//set the title of the frame
super("Hanoi Tower Simulation v1.0 by Praveena Sarathchandra - [email protected]");
this.setLayout(new BorderLayout());
12
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
//panel creation
Panel panel1 = new Panel(new FlowLayout());
panel2 = new MidPanel("images/bg.png");
panel2.setLayout(null);
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.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 panel3
panel3.setBackground(new Color(237,237,255));
panel3.setPreferredSize( new Dimension(0,100));
Label lbl3 = new Label("Minimum moves to win:");
13
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
this.setSize(800,600);
this.setVisible(true);
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"
14
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
try{
getn = Integer.parseInt(user_discs);
}
if( "Autoplay".equals(actionBtn)){
Main.doAuto();
}
this.setVisible(true);
15
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
package gui;
}
public Disc(){
this.id = 0;
this.width = 0;
16
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
package main;
import javax.swing.*;
import gui.*;
public class Main {
getn = 3;
try {
getn = Integer.parseInt(user_discs);
layout.rod_basey[0] = 323;
layout.rod_basey[1] = 323;
layout.rod_basey[2] = 323;
17
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
generateFirstRod(n);
layout.lblMoves.setText(Integer.toString(minMoves));
layout.panel2.add(ldiscs[i]);
}
}
moving_disc_id = rods[fromRod].discs[rods[fromRod].top].id;
} catch (ArrayIndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(null, "Selected from-rod is empty!");
return;
18
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
if (rods[toRod].top == -1
|| moving_disc_id > rods[toRod].discs[rods[toRod].top].id) {
rods[toRod].push(popped);
basex = layout.rod_basex[toRod];
basey = layout.rod_basey[toRod];
layout.rod_basey[toRod] -= 16;
layout.rod_basey[fromRod] += 16;
checkGameEnd();
} else {
JOptionPane
.showMessageDialog(null,
"Illegal move! You cannot place large disc on top of
a small discs");
return;
}
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");
}
}
}
doAuto(getn, 0, 2, 1);
}
19
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
if (n == 1) {
doMove(source, dest);
} else if (n > 1) {
doMove(source, dest);
20
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Cases
Test Case: 1
Test Case: 2
Test Case: 3
21
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Case: 4
Test Case: 5
22
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Case: 6
Test Case 7
Test Case: 8
23
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Test Case: 9
Test Case: 10
Test Case: 11
24
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
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.
25
Asia 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.
26
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
Further Development
Implement a Scoring method according to time taken for players to end the
game
27
Asia Pacific Institute of Information Technology
Hanoi Tower Simulation – Java Programming
References
28
Asia Pacific Institute of Information Technology