Lagi-lagi tutorial Java sederhana
Woi, ketemu lagi. Mumpung lagi semangat-semangatnya nulis tutorial nih. Kali ini saya akan memberikan tutorial sederhana, yaitu bagaimana cara membuat splash screen yang biasanya ditampilkan sebelum sebuah program dijalankan. Sebenarnya, jika Anda memakai NetBeans, sangat mudah sekali kalau ingin membuat splash screen. Tutorialnya ada di sini. Sedangkan yang saya buat, bisa diaplikasikan meski pakai text editor biasa.
Teknik ini memanfaatkan class JWindow dari package javax.swing dan peran sebuah thread untuk melakukan sleep. Anda bisa mengacak-acak (baca: mempelajari) source code di bawah ini.
/*
* DO NOT REMOVE THIS COPYRIGHT
*
* This source code is created by Muhammad Fauzil Haqqi
* You can use and modify this source code but
* you are forbidden to change or remove this license
*
* Nick : Haqqi
* YM : xp_guitarist
* Email : fauzil.haqqi@gmail.com
* Blog : http://fauzilhaqqi.blogspot.com
*/
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
/**
*
* @author Haqqi
*/
public class SplashScreen extends JWindow {
//*********************//
//*** Variable area ***//
//*********************//
private BufferedImage image;
//************************//
//*** Constructor area ***//
//************************//
public SplashScreen(BufferedImage image) {
this.image = image;
}
//*******************//
//*** Method area ***//
//*******************//
public void showSplash(int duration) {
// primary panel, get from frame's content pane
JPanel pane = (JPanel) getContentPane();
// set the size based on image size
int width = image.getWidth();
int height = image.getHeight();
pane.setPreferredSize(new Dimension(width, height));
// label to display the image
JLabel label = new JLabel(new ImageIcon(image));
pane.add(label);
pack();
// set window to center of the screen
setLocationRelativeTo(null);
setVisible(true);
// sleep for a while
try {
Thread.sleep(duration);
} catch (InterruptedException ex) {}
setVisible(false);
dispose();
}
public static void main(String[] args) {
BufferedImage image = null;
try {
image = ImageIO.read(SplashScreen.class.getResource("logo-banner.gif"));
} catch (IOException ex) {}
SplashScreen ss = new SplashScreen(image);
ss.showSplash(2000);
}
}
Satu class tersebut, bisa Anda manfaatkan untuk splash screen dengan gambar yang berbeda, terserah Anda. Anda cukup parsing URL yang tepat dari gambar Anda. Pada contoh di atas, file gambar terletak dalam satu folder dengan file java dari class SplashScreen. Jadi saya menggunakan method getResource() untuk mendapatkan URL-nya.
Selamat mencoba!!!
read more...
ANNOUNCEMENT!!!
This blog is dead!!! I moved it to my new blog in http://haqqi.net. Thank you for reading this blog. Hope you will read my new blog too.
Tutorial Java : Membuat Splash Screen
Sep 10, 2009Posted by Haqqi at 3:03 PM 2 comments
Labels: Bahasa Indonesia, My Source Code
Tutorial Java : Game Sederhana - Snake HQ
Sep 9, 20091 jam coding sambil smsan
Rabu pagi, jam 00.10 saya tiba-tiba bangun entah kenapa. Seperti biasa, laptop saya masih menyala di atas kepala saya. Habis matiin laptop, ngecek sms di HP, eh ternyata ada balesan. Saya bales, ternyata dibales lagi. Akhirnya gak jadi ngelanjutin tidur, malah smsan. Nah, di posting ini, bukan itu intinya. Sambil smsan, saya bingung mau ngapain. Ya udah, langsung buka laptop lagi, niat ngelanjutin bikin artikel tentang membuat game Java. Kebetulan saya mau memasukkan source code sebuah rancangan game sederhana. Mau nggak mau ya saya buka NetBeans dan mulai coding.
Source code yang saya buat nggak sulit-sulit amat sih, dan nggak panjang-panjang amat, makanya saya posting di sini. Ini cuma rancangan sederhana game Snake HQ, game sejenis ular-ularan yang nanti makan apel dan jadi tambah panjang. Semoga tutorial di posting ini bisa membantu para pembaca yang pingin mulai belajar game Java.
Source code ini saya buat dengan menggunakan NetBeans 6.7.1 serta JDK 6u16. Pembuatannya di laptop saya, dengan OS Windows XP SP3.
Oke, kita mulai. Pertama-tama, kita tentukan sampai mana target rancangan ini diselesaikan. Kebetulan karena ini iseng-iseng, saya cuma berniat sampai animasi sederhana dan deteksi tepi area agar kalau ular tersebut sampai di tepi, bisa tembus di sisi lain. Ini belum sampai deteksi dabrakan dengan dinding, makanan (apel), maupun tabrakan antara kepala dan badan ular tersebut. Karena itu, class utama yang kita butuhkan hanya 2, yaitu untuk panel utama game dan ular yang akan berjalan. Class tambahan lain, akan dibahas kemudian.
Kita mulai dari class ular. Sementara ini, attribut yang kita butuhkan hanya koordinat ular, arah ular menghadap, dan panjang maksimal (bisa fleksibel nantinya). Sedangkan behaviour yang bisa dilakukan ular antara lain adalah mengubah arah menghadap, mengupdate koordinat seluruh anggota badan setiap berjalan, termasuk untuk tembus ke sisi lain saat menabrak tepi panel. Berikut source code-nya.
/*
* DO NOT REMOVE THIS COPYRIGHT
*
* This source code is created by Muhammad Fauzil Haqqi
* You can use and modify this source code but
* you are forbidden to change or remove this license
*
* Nick : Haqqi
* YM : xp_guitarist
* Email : fauzil.haqqi@gmail.com
* Blog : http://fauzilhaqqi.blogspot.com
*/
package snakehq;
import java.awt.Point;
/**
* Snake class, a representation of a snake
*
* @author Haqqi
*/
public class Snake {
//*********************//
//*** Variable area ***//
//*********************//
// coordinates of body
private Point[] body;
// facing
private int face;
// maximum snake's length
private final int maxLength = 10;
// orientation
public static final int NORTH = 0;
public static final int EAST = 1;
public static final int SOUTH = 2;
public static final int WEST = 3;
// snake pixel size
public static final int SNAKE_SIZE = 10;
//************************//
//*** Constructor area ***//
//************************//
public Snake() {
body = new Point[maxLength];
for(int i = 0; i < maxLength; i++) {
body[i] = new Point(20 - i, 15);
}
face = EAST;
}
//*******************//
//*** Method area ***//
//*******************//
public Point[] getBody() {
return body;
}
public void moveEast() {
if(face != WEST)
face = EAST;
}
public void moveWest() {
if(face != EAST)
face = WEST;
}
public void moveNorth() {
if(face != SOUTH)
face = NORTH;
}
public void moveSouth() {
if(face != NORTH)
face = SOUTH;
}
public void update() {
// update body
for(int i = body.length - 1; i > 0; i--) {
body[i].x = body[i-1].x;
body[i].y = body[i-1].y;
}
// update head
Point head = body[0];
if(face == NORTH) {
if(head.y <= 0)
head.y = Panel.AREA_HEIGHT - 1;
else
head.y--;
}
else if(face == EAST) {
if(head.x >= Panel.AREA_WIDTH - 1)
head.x = 0;
else
head.x++;
}
else if(face == SOUTH) {
if(head.y >= Panel.AREA_HEIGHT - 1)
head.y = 0;
else
head.y++;
}
else if(face == WEST) {
if(head.x <= 0)
head.x = Panel.AREA_WIDTH - 1;
else
head.x--;
}
}
}
Pembuatan class Snake ini tidaklah sulit. Bagian terpenting dari game sederhana ini adalah kerangka game yang berupa panel. Berikut source code-nya.
/*
* DO NOT REMOVE THIS COPYRIGHT
*
* This source code is created by Muhammad Fauzil Haqqi
* You can use and modify this source code but
* you are forbidden to change or remove this license
*
* Nick : Haqqi
* YM : xp_guitarist
* Email : fauzil.haqqi@gmail.com
* Blog : http://fauzilhaqqi.blogspot.com
*/
package snakehq;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* Panel class, the skeleton of the game
*
* @author Haqqi
*/
public class Panel extends JPanel {
//*********************//
//*** Variable area ***//
//*********************//
private Snake snake;
private Thread animation;
public static final int PANEL_WIDTH = 400;
public static final int PANEL_HEIGHT = 300;
public static final int AREA_WIDTH =
PANEL_WIDTH / Snake.SNAKE_SIZE;
public static final int AREA_HEIGHT =
PANEL_HEIGHT / Snake.SNAKE_SIZE;
//************************//
//*** Constructor area ***//
//************************//
public Panel() {
setPreferredSize(new Dimension(
PANEL_WIDTH, PANEL_HEIGHT));
snake = new Snake();
initThread();
addKeyListener(new KeyManager());
setFocusable(true);
requestFocusInWindow();
animation.start();
}
//*******************//
//*** Method area ***//
//*******************//
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.addRenderingHints(new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
drawSnake(g2);
}
// render the snake
private void drawSnake(Graphics2D g2) {
Point[] s = snake.getBody();
int pixel = Snake.SNAKE_SIZE;
// fill the head
g2.fillOval(s[0].x * pixel, s[0].y * pixel,
pixel,pixel);
// draw body outline
for(int i = 0; i < s.length; i++) {
g2.drawOval(s[i].x * pixel, s[i].y * pixel,
pixel, pixel);
}
}
// initiate animation thread
private void initThread() {
animation = new Thread(new Runnable() {
public void run() {
while(true) {
try {
// sleep a while for animation
Thread.sleep(300);
} catch (InterruptedException ex) {}
snake.update();
SwingUtilities.invokeLater(
new Runnable(){
public void run() {
repaint();
}
});
}
}
});
}
// Keyboard handler of the game
private class KeyManager extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int c = e.getKeyCode();
switch(c) {
case KeyEvent.VK_RIGHT:
snake.moveEast();
break;
case KeyEvent.VK_LEFT:
snake.moveWest();
break;
case KeyEvent.VK_UP:
snake.moveNorth();
break;
case KeyEvent.VK_DOWN:
snake.moveSouth();
break;
}
}
}
/**
* Main method that run firstly when the program starts
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Snake HQ");
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
f.add(new Panel());
f.pack();
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
Panel ini hanya mempunyai 2 atribut/object penting. Yang pertama, jelas adalah si ular. Yang kedua, adalah thread yang digunakan untuk mengatur animasi. Proses animasi itu sendiri diatur dalam method initThread(). Coba saja pelajari apa yang dilakukan program dalam thread tersebut. Bagian lain yang penting adalah private class KeyManager. Class ini digunakan untuk menangkap event yang terjadi pada keyboard.
Untuk rendering, semua diatur dalam override method paintComponent(). RenderingHints di-set agar tampilan lebih lembut. Setelah itu, lakukan penggambaran seluruh badan ular. Kembali ke thread animation. Yang membuat ular seperti berjalan, adalah penghentian program selama beberapa milisecond, kemudian badan ular di-update sesuai method update dari class Snake tersebut. Terakhir, panel diletakkan dalam sebuah JFrame (window), yang diconstruct dalam method main.
Source code bisa didownload di:
http://haqqilibrary.googlecode.com/files/SnakeHQ.zip
Selamat mencoba!!!
read more...
Posted by Haqqi at 9:48 AM 1 comments
Labels: Bahasa Indonesia, My Source Code
Tutorial Java : Wrap Text into JLabel
Jul 18, 2009Here is one of my source codeNow I'm writing for my next article in PC Media. In my program, I need to read a text file, and then parse it to JLabel to display the text. It is a long text file that contain not only a single sentence, but complex text with paragraf formatted. If I easily parse the text into the JLabel, its width will be as long as the text, can you imagine? So, I need to know how to wrap text in my JLabel. After browsing on the internet, I only found some basic method, and I rearrange it to be more suited for my program. And I think you can use this idea too.
Before you start to learn this post, make sure you have read the previous article that tell about reading a file. Using that method, I can get Array of String of my text file. After that, I need to wrap that Array of String into JLabel. So, I create this static method. I put it into a class named LabelUtil. One more thing, you have to define the container of the JLabel. If not, this method will return error.
It's easy to do that. You can just create a JPanel and add the JLabel into that panel, so that panel will be JLabel's container. You have to call setSize(int, int);
of the container firstly.
Here is the method:
import java.awt.Container;
import java.awt.FontMetrics;
import java.text.BreakIterator;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class LabelUtil {
/**
* Make the text automatically wrap into JLabel
* @param label JLabel
* @param text Array of String
*/
private void wrapLabelText(JLabel label,
String[] text) {
// measure the length of font in swing component
FontMetrics fm = label.getFontMetrics(
label.getFont());
// size of parent container
Container container = label.getParent();
int containerWidth = container.getWidth();
// to find the word separation
BreakIterator boundary = BreakIterator
.getWordInstance();
// main string to be added
StringBuffer m = new StringBuffer("<html>");
// loop each index of array
for(String str : text) {
boundary.setText(str);
// save each line
StringBuffer line = new StringBuffer();
// save each paragraph
StringBuffer par = new StringBuffer();
int start = boundary.first();
// wrap loop
for(int end = boundary.next();
end != BreakIterator.DONE;
start = end, end = boundary.next()) {
String word = str.substring(start,end);
line.append(word);
// compare width
int trialWidth = SwingUtilities
.computeStringWidth(
fm, line.toString());
// if bigger, add new line
if(trialWidth > containerWidth) {
line = new StringBuffer(word);
par.append("<br>");
}
par.append(word);
}
// add new line each paragraph
par.append("<br>");
// add paragraph into main string
m.append(par);
}
// closed tag
m.append("</html>");
label.setText(m.toString());
}
}
Suppose that my text file is like this:
VT Alpha - Program Pemilihan
http://fauzilhaqqi.blogspot.com - 2009
Programmer : Muhammad Fauzil Haqqi
Program ini adalah program untuk pemilihan dengan metode voting. Cara pembuatan program ini telah ditulis dalam bentuk artikel pada majalah PC Media. Source code program ini bebas untuk dipakai, diubah, maupun disebarkan secara gratis.
Programmer tidak memberikan garansi jika nantinya ada kesalahan yang terjadi selama penggunaan program ini. Programmer juga tidak bertanggung jawab terhadap penyalahgunaan program ini dalam aplikasi nyatanya.
Jika Anda memiliki saran maupun pertanyaan tentang program ini, silahkan menghubungi programmer melalui alamat blog di atas.
So, after I get the Array of String of my text file by using static method FileUtil.fileRead();
, I just parse the Array to method wrapLabelText();
. So easy, isn't it???
I use this code to display a dialog into my frame:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory
.createEtchedBorder());
pane.setSize(270, 0);
// filepath
String[] text = FileUtil.fileRead(
FileUtil.setFile("data/about.vta"));
JLabel label = new JLabel();
pane.add(label);
LabelUtil.wrapLabelText(label, text);
JOptionPane.showMessageDialog(this, pane,
"Tentang Kami",
JOptionPane.PLAIN_MESSAGE);
After do everything I can do, this is the displayed dialog:
read more...
Posted by Haqqi at 6:03 PM 4 comments
Labels: English, My Source Code
Tutorial Java : File Read and Write
Jul 17, 2009Useful Java file I/O classStudying Java is an exciting thing. I really love coding and I am really happy to share that. After writing the Devilish Children, I was confused when writing the next game. One thing that is so important is File Input and Output. I mean, I need to know the easiest way to read and write text file using Java. After searching for the sollution, I found some easy way to do that. I just have to create a FileUtil class that has static method to read and write file. Actually, I get this code from a Game Engine called GTGE. Because GTGE is an open source project, I modified it to fulfill my requirement, added some comments, and write it to this blog.
Here is the source code of FileUtil.java class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* This class has been written by Haqqi. You can
* freely use, modify, and distribute it.
* @author Haqqi
*/
public class FileUtil {
/**
* Private constructor to prevent the object creation
*/
private FileUtil() {}
/**
* Set the file based on relative path
* @param filePath Path of the file
* @return Generated file
*/
public static File setFile(String filePath) {
// create new file object
File file = null;
// getting the path from working directory
// you can check the directory by printing it
String path = System.getProperty("user.dir")
+ File.separatorChar + filePath;
try {
// construct the file based on the path
file = new File(path);
}
catch(Exception e) {
e.printStackTrace();
}
// if file is not found, then throw exception
if (file == null) {
throw new RuntimeException();
}
return file;
}
/**
* Write an Array of String into a file. The written
* file will be just like a text file.
* @param text Array of String that want to be written
* @param file File
* @return true if success and false if not
*/
public static boolean fileWrite(String[] text,
File file) {
try {
// create buffer
BufferedWriter out = new BufferedWriter(
new FileWriter(file));
PrintWriter writeOut = new PrintWriter(out);
// writing text to file
for (int i = 0; i < text.length; i++) {
writeOut.println(text[i]);
}
// close the writer
writeOut.close();
return true;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Read file from a file
* @param file
* @return
*/
public static String[] fileRead(File file) {
try {
// buffered reader
BufferedReader readIn = new BufferedReader(
new FileReader(file));
// ArrayList to store the string each line
ArrayList list = new ArrayList();
// Temporarily object
String data;
// Read each line until end of line
while ((data = readIn.readLine()) != null) {
list.add(data);
}
// closing reader
readIn.close();
// return as Array of String
return (String[])list.toArray(new String[0]);
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
The constructor is modified to be private to prevent the object creation, since all the methods is static method. Before you use fileWrite and fileRead method, you can easily set the file by using setFile method. You just need to set the relative path of the file from working directory. For example, if your woring directory is "D:\\My Java Project\TheProject", and your file is inside folder "data" and titled "My Files.my", so you just call setFile("data/My Files.my"); to get the file. Use the set file in method fileRead and FileWrite. Remember that fileRead returns an Array of String. Each index for 1 line in the file.
Ok, I hope this post will be very helpful for you. Please be free to leave a comment.
read more...
Posted by Haqqi at 8:34 PM 1 comments
Labels: English, My Source Code
Devilish Children
Dec 28, 2008I just upload it, my java project
Ehm ehm... I just finished it in 2 days. As I said before in previous post, I have a task in my study, to create an application, any application that use Java Programming Language. I decided to create a game. Since I still don't know too much about Java yet, I decided to create a strategy game based on classic game in Sega console, Magic Monster, because it won't give any animation, just data structure concept and another little things about java. The deadline is at Tuesday, December 23rd 2008, several days ago. So, actually this game have been finished at that time. But I create this post just now, since I have so many things to do.
First, thanks to Amri, since he helps me to create the images of my game. Because of that the interface is better. I can get 90 point for this project, as Final Exam task. The game titled Devilish Children. Since I still don't know how to create AI, this game only works for player versus player. Based on the title, in this game there are 2 children, as a hero, that can summon monsters from another world to the arena. And then, they will try to defeat each other. The player who defeat the enemy's hero firstly will be the winner.
The system of the game is still creepy. I don't calculate the attribute of each character, since I don't have too much time to think that. So maybe there are some monster that cannot attack any monster because lack of attack status. Haha... Another bad thing is it is still possible to attack an ally. Again, a rule that I forgot to set is the heroes can only summon their monster in a castle. Since I forgot it, so the heroes can summon the monster where ever they are. No more time to write, here is the jar file of the game, in zip file:
Download Link
Password: fauzilhaqqi.blogspot.com
Ok, I don't want to write more, here is the user manual (also included in download section), but I'm sorry I don't have enough time to translate it in English, so it is still in Bahasa Indonesia:
Devilish Children v0.08
Game engine : Haqqi
Graphics : Amri & Haqqi
Bahasa Indonesia
A. Gambaran Umum
Devilish Children (DC) adalah game berjenis Turn Based Strategy. Artinya, permainan dilakukan bergantian antara pemain satu dengan lainnya. DC terinspirasi dari game lama dari SEGA berjudul Magic Monster. DC dimainkan oleh 2 orang pemain yang saling mengalahkan. Masing-masing pemain memulai permainan dengan sebuah Hero yang memiliki kemampuan untuk memanggil monster ke arena. Pemain pertama menggunakan Hero bernama Frost (biru), sedangkan pemain kedua menggunakan Hero bernama Flare (merah).
Arena permainan berupa tile map yang berbentuk hexagonal (segi-6). Pada awal permainan, Frost terletak pada pojok kiri atas map, sedangkan Flare terletak pada pojok kanan bawah map. Monster yang dapat dipanggil berbeda antara Frost dan Flare.
B. Spesifikasi minimum dan menjalankan game
Spesifikasi komputer yang direkomendasikan adalah:
- CPU 1GHz atau lebih
- RAM 512MB atau lebih
- Layar resolusi 1024x768 atau lebih
- VGA 128MB atau lebih
Untuk menjalankan program, pastikan JRE 6 SE (Java Runtime Environment) telah diinstall dalam komputer. Setelah itu, jalankan executable jar yang ada.
C. Control
Game ini menggunakan control yang berasal dari keyboard, yaitu:
- Panah Atas : Atas
- Panah Bawah : Bawah
- Panah Kanan : Kanan
- Panah Kiri : Kiri
Control di atas digunakan untuk memindahkan kursor yang sedang aktif. Setelah kursor diletakkan pada tempat yang diinginkan, ada tombol lain yang berfungsi berbeda tergantung di mana kursor berada:
- Tombol Z : A
- Tombol X : B
Control A berfungsi untuk mengaktifkan fungsi kursor yang sedang aktif sesuai tempatnya. Sedangkan control B berfungsi untuk membatalkan fungsi kursor yang sedang aktif.
D. Aturan Main
- Winner : Pemain yang dapat mengalahkan Hero lawan terlebih dahulu menjadi pemenangnya
- Summon : Pemanggilan monster dapat dilakukan dengan menekan control A disekitar Hero masing-masing. Pemanggilan monster dapat dilakukan berdasarkan sisa Mana yang tersedia dari masing-masing Hero dan jumlah maksimal monster yang dipanggil berdasarkan jumlah castle yang dimiliki.
- Castle : Banyaknya castle menentukan jumlah maksimal monster yang dipanggil oleh masing-masing pemain. Castle akan berubah kepemilikan jika disinggahi monster lawan.
- Move : Setiap monster dapat berjalan pada arena sesuai dengan atribut movement range yang dimiliki.
- Attack : Setiap monster dapat menyerang monster lainnya. Jarak serangan ditentukan oleh atribut attack range. Besar serangan ditentukan oleh besarnya attack penyerang dan defense yang diserang.
- Death : Monster yang kehabisan HP akan dianggap mati dan secara otomatis dihilangkan dari arena.
read more...
Posted by Haqqi at 8:36 AM 3 comments
Labels: Bahasa Indonesia, English, My Source Code
N-Queen Problem (Source Code)
Dec 18, 2008Here is my source code of N-Queen Problem
This post refers to my previous post about N-Queen problem. As I said before, I promise to give my source code to you, who wants. I don't need to tell you more, since all have been told before. Although I don't need to, I still want to write more. About what? Of course, something not important. I couldn't be too proud again. Because before post this article, I found my friend who can program better than me, although the topic is different. I did about N-Queen, he did about ******, although he is in another class.
Now I have to study more and more, to be better than him. Nothing will be told anymore, I want to stay in front of my laptop again, to finish my next project. Ok ok, here is my source code:
Download Link
Password:
fauzilhaqqi.blogspot.com
I wrote my source code in NetBeans 6.1. So for you who usually use NetBeans of course know how to open it. Last words, see ya at my next post!!!
read more...
Posted by Haqqi at 12:10 PM 2 comments
Labels: English, My Source Code
Hanoi Tower
Dec 14, 2008Ok, another one of my task is finished in just no more than 1 day
Hanoi tower, where we have 3 tower to place n number of pin. Start with tower 1 with all pins, we have to move all the pins to another tower. So easy, isn't it?! Not really!!! We have the rules!!! Bigger pin cannot be placed beyond the smaller pin. So, we can only move a pin to tower which the most top pin is bigger. For 3 number of pins, it easy enough. If we want to move all to 3rd tower, firstly we move 1st pin to 3rd tower. Second, move 2nd pin to 2nd tower. Move again 1st pin to the 2nd tower, beyond the 2nd pin. Move last pin to 3rd tower. Move 1st pin to 1st tower. Move 2nd pin to 3rd tower. Lastly, move 1st pin to 3rd tower. Finish!!!
But for 4 number or more pins, we have to think more. I don't give any algorithm to solve that, since I am too lazy to think that now, maybe next time. But I will give you a simulation game to try to solve the algorithm. Actually, this game is one of my task in my study. I finish it just to give my best to this task, since it will be a big quiz. I use NetBeans IDE 6.1 to develop it, just in 1 day. I know my program is not too perfect, but I think it will be one of the best (so arrogant heh?!). No no... I just want to share this to world.
I will give both of the program and the source code. You can download the program here:
Download link
Or if you want to see my source code and maybe want to give comment, you can download here:
Download link
As usual, use the password to open the zip file:
fauzilhaqqi.blogspot.com
In the program (an executable jar file, just double click it), once you run it, an input dialog box will be displayed. You have to enter number of pin you want, no more than 10. If you enter more than 10, it will be converted to 10 automatically. If you enter negative number, a program will be terminated. You can use right arrow and left arrow on your keyboard to move the cursor. And then press space bar to activate cursor, in order to move the top pin.
Please enjoy using it and give comment if you want.
read more...
Posted by Haqqi at 1:38 PM 0 comments
Labels: English, My Source Code
N-Queen Problem by Backtracking
Dec 12, 2008One of my pressures is already solved
Ok, one of my big pressure, or maybe just my obligation as a student, is already solved. Yeah, as you can see in the title of this post, it's about the task of subject "Algorithm and Programming 2" in my study. Yes, I have to create an algorithm to solve N-Queen problem, and then make a presentation to get highest score in my big quiz.
What is N-Queen problem? As you can see in another search result in search engine, in general, N-Queen problem is how can you get a sollution to set n number of Queen on n x n size of chessboard, where no one can attack each other. In my task, I have to use backtracking algorithm, in order to get the closest sollution, rather than all sollution. It means the output is, there is any sollution or not.
I won't give any source code yet, because when I post this posting, another student maybe still not present it yet. But I will give the algorithm, here it is:
We need 2 arrays to use this algorithm. First is the location of the Queens. We can use 1 dimension array with Integer type to save their coordinates. Why just 1 dimension array? Because we know that just one Queen for one row, so we can save the coordinate like this: queen[y]=x; It means that queen at row y is settled at column x. It will save with less capacity rather than 2 dimension array. The second array has to be 2 dimension array with Boolean type. We use it to save the location where Queens cannot take place based on the coordinate. After one Queen is settled, we change the value of second array, where is the row, column, and all diagonals of the position of the Queen, to be "cannot take place". So in the program's loop, it will be checked and no queens will try that place. So easy, isn't it?
I will give explanation about the variables and methods before the pseudocode. Variable queens means the position of the Queens, variable place means the status of free place (it is initialized with 'true' value), variable y means row, variable x means column, and variable size means board size and the number of Queens. Method isAllSolved() will return whether the problem is already solved or not (true if already solved, false is not solved yet), method createCopyOf(array) will create new array with the same value as the parameter, method setCannotTakePlace(x, y) means set the row, column, and diagonals of [x, y] to be 'false', so no queens can take that place. And method isRowSolved(place, y) return whether the row y is already solved or not (return true if there is any queen, and false if no queen at that row). Here is the pseudocode:
Download here
As I tell before, I won't give any source code yet. But I will give the demo of my program as executable jar file. I use GUI to display the sollution. Once you run the program, an input dialog box will be displayed. You have to type the board size at any size but negative (because the program won't run anything). After that, a window is opened and you will see the first sollution. You can see another sollution by press right/left arrow on your keyboard. I tell you again, it is 'another sollution', not the next sollution. You will see how can it happen after you get the source code soon.
Ok, here is the jar file download link:
Download Here
As usual, I set the password at my file:
fauzilhaqqi.blogspot.com
Ok, I hope you will enjoy waiting the source code. If you can't wait any longer, please be free to contact me at my email, fauzil.haqqi@gmail.com. I will send to you privately as you give your contact too. One more thing, I use Java SE to create the program.
read more...
Posted by Haqqi at 6:03 PM 5 comments
Labels: English, My Source Code