1. Tujuan Praktikum
- Mengetahui Cara Kerja Program Aplikasi Permainan Tower of hanoi pada
bahasa pemrograman Matlab
2. Landasan Teori
2.1. Permainan Tower of hanoi
Tower of hanoi adalah sebuah permainan matematis atau teka-teki.
Permainan ini terdiri dari tiga tiang dan sejumlah cakram dengan ukuran
berbeda-beda yang bisa dimasukkan ke tiang mana saja. Permainan dimulai
dengan cakram-cakram yang tertumpuk rapi berurutan berdasarkan ukurannya
dalam salah satu tiang, cakram terkecil diletakkan teratas, sehingga membentuk
kerucut.
Tujuan dari teka-teki ini adalah untuk memindahkan seluruh tumpukan ke
tiang yang lain, mengikuti aturan berikut:
Hanya satu cakram yang boleh dipindahkan dalam satu waktu.
Setiap perpindahan berupa pengambilan cakram teratas dari satu tiang dan
memasukkannya ke tiang lain, di atas cakram lain yang mungkin sudah ada di
tiang tersebut.
Tidak boleh meletakkan cakram di atas cakram lain yang lebih kecil.
3. Perencanaan
Pada bagian perencanaan terdapat bagian Flowchart yang bertujuan untuk
merencanakan bagaimana sistem akan berjalan, dan Layout aplikasi yang bertujuan
untuk merencanakan Layout Aplikasi yang akan dibuat
Bima Gerry Pratama Praktikum Tower of hanoi
3.1. Flowchart
Mulai
X, Y, Z, n
Input n
Ya Move
n=1
X, Z
Tidak
X, Z, Y, n-1
Move
X, Z
Y, X, Z, n-1
Selesai
%
% Private properties
%
properties (Access = private)
% Program properties
solving = false; % Solving flag
randomBoard = false; % Random board flag
n; % Number of pegs
state; % State container
handles; % Block handles
minWidth; % Min block width
maxWidth; % Max block width
widths; % Block widths
height; % Block heights
pegs; % Peg positions
pegWidth; % Peg width
pegDot; % Peg dot location
pegDotD; % Peg dot diameter
to; % To peg
from; % From peg
numListStr; % Block counts list
colors; % Color scheme
% GUI handles
fig; % Figure handle
ax; % Axis handle
speedSlider; % Speed slider handle
solveButton; % Solve button handle
numList; % Block count list handle
colorList; % Color list handle
end
%
% Public methods
%
methods (Access = public)
%
Bima Gerry Pratama Praktikum Tower of hanoi
% Constructor
%
function this = TowersOfHanoi(n)
% Check if size was specified
if (nargin == 1)
% User-specified number of blocks
this.n = min(max(n,TowersOfHanoi.minNBlocks), ...
TowersOfHanoi.maxNBlocks);
else
% Default number of blocks
this.n = TowersOfHanoi.defaultNBlocks;
end
% Create GUI
this.CreateGUI();
% Initialize board
this.InitializeBoard();
end
%
% Override display function
%
function display(this) %#ok
% Empty
end
end
%
% Private methods
%
methods (Access = private)
%
% Handle key press
%
function HandleKeyPress(this)
% Check if the puzzle is currently being solved
if (this.solving == false)
% Process key press
key = get(this.fig,'CurrentCharacter') - 48;
if (any(key > 0) && any(key < 4))
% Valid key press
Bima Gerry Pratama Praktikum Tower of hanoi
if isempty(this.from)
% Save "from key"
this.from = key;
% Remove dot
delete(this.pegDot);
end
end
%
% Move piece
%
function MovePiece(this,fromP,toP)
% Get original rung
fromR = find(~isnan(this.state(:,fromP)),1,'first');
this.height];
this.state(toR,toP) = num;
this.handles{toR,toP} = this.handles{fromR,fromP};
set(this.handles{toR,toP},'Position',pos);
% Flush graphics
drawnow;
end
end
%
% Solve the puzzle
%
function SolvePuzzle(this)
try
% Check if the puzzle is already being solved
if (this.solving == false)
% Set solve button
set(this.solveButton,'String','Stop');
set(this.solveButton,'BackgroundColor','r');
this.solving = true;
%
% Solve the puzzle from an arbitrary position
%
function ArbitrarySolver(this,NBlocks,toP)
% Check if the puzzle is already being solved
if (this.solving == true)
% Find largest discrepancy
N = NBlocks;
while (sum(N == this.state(:,toP)) == 1)
N = N - 1;
end
Bima Gerry Pratama Praktikum Tower of hanoi
%
% Solve the puzzle from an ideal position
%
function IdealSolver(this,fromP,toP,NBlocks)
% Check if the puzzle is already being solved
if (this.solving == true)
% Check if there is work to do
if (NBlocks <= 0)
return;
else
% Recursively call IdealSolver()
this.IdealSolver(fromP,6 - toP - fromP,NBlocks
- 1);
end
end
%
% Pause game
%
function Pause(this)
% Get pause time from slider
time = (100 - get(this.speedSlider,'Value')) / 200;
%
% Check for solution
%
function CheckForSolution(this)
% Check for puzzle solution
solved = sum(this.state(:,3)) == (this.n * (this.n +
1) / 2);
%
% Reset board
%
function ResetBoard(this)
% Get number of blocks
this.GetNBlocks();
this.CleanUpBoard();
%
% Random board reset
%
function RandomBoardReset(this)
% Get number of blocks
this.GetNBlocks();
%
% Get number of blocks from GUI
%
function GetNBlocks(this)
% Get number of blocks
num = get(this.numList,'Value') + this.minNBlocks - 1;
%
% Exit game
%
function ExitGame(this)
% Set solving status to false for graceful(?) exit
this.solving = false;
%
% Clean up board
%
function CleanUpBoard(this)
% Clear axis
cla(this.ax);
Bima Gerry Pratama Praktikum Tower of hanoi
%
% Update color scheme
%
function UpdateColorScheme(this)
% Get new color scheme
listNum = get(this.colorList,'Value');
if (listNum == (length(this.colormaps) + 1))
this.colors = rand(this.n,3);
else
fnHandle = this.colormaps{listNum};
this.colors = fnHandle(this.n);
this.colors = this.colors(end:-1:1,:);
end
'FaceColor',this.colors(this.state(i,j),:));
end
end
end
end
%
% Initialize the board
%
function InitializeBoard(this)
% Update block dimensions
this.widths =
linspace(this.minWidth,this.maxWidth,this.n)';
this.height = 1 / (this.n + 1);
end
for N = this.n:-1:1
bool = isnan(this.state(:,inds(N)));
this.state(find(bool,1,'last'),inds(N)) = N;
end
else
% Standard setup
this.state(:,1) = (1:this.n)';
end
% Create pegs
for i = 1:3
pos = [(this.pegs(i) - this.pegWidth / 2),0, ...
this.pegWidth,0.97];
rectangle('Position',pos, ...
'Curvature',[this.kP this.kP], ...
'FaceColor',[0.5 0.5 0.5]);
end
% Create blocks
for j = 1:3
for i = 1:this.n
if ~isnan(this.state(i,j))
num = this.state(i,j);
pos = [(this.pegs(j) - this.widths(num) /
2), ...
((this.n - i) * this.height), ...
this.widths(num), ...
this.height];
this.handles{i,j} =
rectangle('Position',pos, ...
'Curvature',[this.kB
this.kB]);
end
end
end
%
% Create the GUI
%
function CreateGUI(this)
% Initialize GUI object dimensions
axPos = [0.05 0.25 0.9 0.6];
aspectratio = axPos(3) / axPos(4);
this.maxWidth = aspectratio * (9 / 30);
Bima Gerry Pratama Praktikum Tower of hanoi
this.minWidth = this.maxWidth / 2;
this.pegWidth = this.minWidth / 3;
this.pegs = aspectratio * [1/6 3/6 5/6];
this.pegDotD = this.pegWidth / 1.5;
% Create figure
this.fig = figure;
set(this.fig,'WindowKeyPressFcn',@(s,e)HandleKeyPress(this));
set(this.fig,'MenuBar','None');
set(this.fig,'NumberTitle','off');
set(this.fig,'Interruptible','on');
pan(this.fig,'off');
% Setup axis
this.ax = gca;
set(this.ax,'Position',axPos);
axis(this.ax,'equal');
axis([0 aspectratio 0 (1 + this.pegDotD)]);
title(this.ax,'Towers of Hanoi', ...
'FontUnits','normalized', ...
'FontSize',0.15, ...
'FontName','Lucida Handwriting');
axis(this.ax,'off');
'Callback',@(s,e)RandomBoardReset(this), ...
'Units','normalized', ...
'Position',[0.76 0.1 0.2 0.05]);
uicontrol(this.fig,'Style','pushbutton', ...
'FontUnits','normalized', ...
'String','Exit', ...
Bima Gerry Pratama Praktikum Tower of hanoi
'Callback',@(s,e)ExitGame(this),
...
'Units','normalized', ...
'Position',[0.52 0.03 0.2 0.05]);
this.colorList = uicontrol(this.fig,'Style','popup',
...
'FontUnits','normalized', ...
'Callback',@(s,e)UpdateColorScheme(this),...
'String',colorstr, ...
'Units','normalized', ...
'Position',[0.28 0.1 0.2 0.05]);
uicontrol(this.fig,'Style','text', ...
'FontUnits','normalized', ...
'BackgroundColor',[0.8,0.8,0.8],
...
'String','Color Scheme', ...
'Units','normalized', ...
'Position',[0.28 0.15 0.2 0.05]);
Pada tampilan awal aplikasi terdapat menu input jumlah balok dan terdapat 3
menara A, B, dan C yang letaknya berurutan dari kiri ke kanan.
1 Balok 1 dari A ke C
2 Balok 2 dari A ke B
Bima Gerry Pratama Praktikum Tower of hanoi
3 Balok 1 dari C ke B
4 Balok 3 dari A ke C
5 Balok 1 dari B ke A
6 Balok 2 dari B ke C
7 Balok 1 dari A ke C
Bima Gerry Pratama Praktikum Tower of hanoi
6. Kesimpulan
1. Program aplikasi permainan tower of hanoi berhasil diselesaikan
menggunakan bahasa pemrograman Matlab.
2. Program aplikasi tower of hanoi dapat memproses jumlah balok mulai dari 2
sampai dengan 15 buah balok.
3. Program aplikasi tower of hanoi dapat dapat memilih warna sesuai yang kita
inginkan
4. Program aplikasi tower of hanoi dapat memproses balok dengan kecepatan
yang dapat kita tentukan sendiri.