Kamis, 19 Mei 2011

Coding Game Dorong Kotak

Codingan yang terdapat pada midlet dorong kotak. Codingan ini sudah saya berikan penjelasan pada bagian setiap codingannya. Sehingga dapat di mengerti oleh banyak orang. Berikut ini adalah codingannya. Anda cukup mengklik spoiler yang berada dibawah ini maka coding dapat dilihat. Coding diberikan sesuai dengan class atau file yang dibuat. Karena pada game ini di buat lima class atau file maka setiap lima class tersebut terdapat coding yang harus dibuat.

Spoiler Lihat Coding Script:
//mengimport java api
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* @author rivan_ipai
*/
//deklarasi midlet dorong kotak
public class Midlet_dorong_kotak extends MIDlet implements CommandListener {

//deklarasi objek dan variabel
Display tampil;
private kanpas KANPAS;
private nilainya SKOR;
private Screen LAYAR_SKOR;
private Screen LAYAR_LEVEL;
private Alert ALERT;

//membuat tampilan menu
private Command undoCommand = new Command("Ulang", Command.BACK, 1);
private Command restartCommand =
new Command("Restart", Command.CANCEL, 21);
private Command exitCommand = new Command("Exit", Command.EXIT, 60);
private Command scoresCommand =
new Command("Lihat Skor", Command.SCREEN, 25);
private Command okCommand = new Command("OK", Command.OK, 30);
private Command levelCommand =
new Command("Ganti Level", Command.OK, 24);
private Command nextCommand =
new Command("Level Selanjutnya", Command.SCREEN, 22);
private Command prevCommand =
new Command("Ulang Level", Command.SCREEN, 23);

//konstruktor midlet dorong kotak
public Midlet_dorong_kotak() {
tampil = Display.getDisplay(this);
SKOR = new nilainya();
KANPAS = new kanpas(this, SKOR);
ALERT = new Alert("Warning");
}

//menjalankan program
public void startApp() {
if (!SKOR.open()) {
System.out.println("Score open failed");
}

KANPAS.init();
KANPAS.addCommand(undoCommand);
KANPAS.addCommand(scoresCommand);
KANPAS.addCommand(restartCommand);
KANPAS.addCommand(levelCommand);
KANPAS.addCommand(exitCommand);
KANPAS.addCommand(nextCommand);
KANPAS.addCommand(prevCommand);
KANPAS.setCommandListener(this);

KANPAS.setCommandListener(this);

tampil.setCurrent(KANPAS);
}

//untuk menghentikan program
public void pauseApp() {
}

//untuk menghentikan proses
public void destroyApp(boolean unconditional) {
tampil.setCurrent(null);
KANPAS.destroy();
if (SKOR != null)
SKOR.close();
}

//untuk memberikan efek pada tombol menu yang di buat
public void commandAction(Command c, Displayable s) {
if (c == undoCommand) {
KANPAS.undoMove();
} else if (c == restartCommand) {
KANPAS.restartLevel();
} else if (c == levelCommand) {
LAYAR_LEVEL = KANPAS.getLevelScreen();
LAYAR_LEVEL.addCommand(okCommand);
LAYAR_LEVEL.setCommandListener(this);
tampil.setCurrent(LAYAR_LEVEL);
} else if (c == okCommand && s == LAYAR_LEVEL) {

if (!KANPAS.gotoLevel()) {
ALERT.setString("ERROR");
tampil.setCurrent(ALERT, KANPAS);
} else {
tampil.setCurrent(KANPAS);
}
} else if (c == scoresCommand) {
LAYAR_SKOR = KANPAS.getScoreScreen();
LAYAR_SKOR.addCommand(okCommand);
LAYAR_SKOR.setCommandListener(this);
tampil.setCurrent(LAYAR_SKOR);
} else if (c == okCommand && s == LAYAR_SKOR) {
tampil.setCurrent(KANPAS);
} else if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
} else if (c == List.SELECT_COMMAND && s == KANPAS) {
LAYAR_SKOR = KANPAS.getScoreScreen();
LAYAR_SKOR.addCommand(okCommand);
LAYAR_SKOR.setCommandListener(this);
tampil.setCurrent(LAYAR_SKOR);
KANPAS.nextLevel(1);
} else if (c == nextCommand) {
if (!KANPAS.nextLevel(1)) {
ALERT.setString("ERROR " +
(KANPAS.getLevel() + 1));
tampil.setCurrent(ALERT, KANPAS);
} else {
tampil.setCurrent(KANPAS);
}
if (s == KANPAS) {
KANPAS.repaint();
}
} else if (c == prevCommand) {
if (!KANPAS.nextLevel(-1)) {
ALERT.setString("ERROR " +
(KANPAS.getLevel() - 1));
tampil.setCurrent(ALERT, KANPAS);
} else {
tampil.setCurrent(KANPAS);
}
if (s == KANPAS) {
KANPAS.repaint();
}

} else {
System.out.println("ERROR " + c);
}
}
}
Coddingan yang terdapat pada kanpas
//mengimport java api
import java.io.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;

/**
* @author rivan_ipai
*/

//deklarasi class kanpas
class kanpas extends Canvas {

//deklarasi variabel
private int level = 1;
private boolean solved;

private int cell = 1;
private int w, h;
private int bwidth, bheight;

private nilai board;
private nilainya score;
private Midlet_dorong_kotak pushkotak;
private Display display;
private Timer timer;
private TimerTask timertask;
private CommandListener listener;


private TextBox levelText;

//untuk deklarasi warna pada tampilan permainan
private static int wallColor = 0x7f7f7f;
private static int groundColor = 0xffffff;
private static int packetColor = 0x000000;
private static int storeColor = 0x000000;
private static int pusherColor = 0x000000;
private static boolean useDottedLine = false;

//deklarasi midlet dorong kotak
public kanpas(Midlet_dorong_kotak pushkotak, nilainya s) {
this.pushkotak = pushkotak;
display = Display.getDisplay(pushkotak);
score = s;
board = new nilai();
initColors();
}

//membuat variable tinggi dan lebar
public void init() {
h = getHeight();
w = getWidth();


level = score.getLevel();
if (!readScreen(level)) {
level = 0;
readScreen(level);
}
repaint();
}

//untuk berhenti proses
public void destroy() {
cancelTo();
if (timer != null) {
timer.cancel();
timer = null;
}
}
//mengatur tampilan warna
private void initColors() {
boolean isColor = display.isColor();
int numColors = display.numColors();

if (isColor) {
setColors(0x006D55, 0xffffff, 0xff6d00, 0xb60055, 0x6d6dff);
} else {
if (numColors > 2) {
setColors(0x999999, 0xffffff, 0x666666, 0xbbbbbb, 0x000000);
} else {
setColors(0x6a6a6a, 0xffffff, 0x6a6a6a, 0x000000, 0x000000);
useDottedLine = true;
}
}
}

// memberikan nilai pada tampilan untuk menentukan warna
private void setColors(int w, int g, int pa, int s, int pu) {
if (w != -1)
wallColor = w;
if (g != -1)
groundColor = g;
if (pa != -1)
packetColor = pa;
if (s != -1)
storeColor = s;
if (pu != -1)
pusherColor = pu;
}
//untuk membuat mundur satu langkah
public void undoMove() {
int dir = board.undoMove();
if (dir >= 0) {
repaintNear(board.getPusherLocation(), dir);
}
solved = board.solved();
}

//melakukan restart atau ulang level
public void restartLevel() {
readScreen(level);
repaint();
solved = false;
}

//untuk melakukan level selanjutnya
public boolean nextLevel(int offset) {
updateScores();
if (level + offset >= 0 && readScreen(level+offset)) {
level += offset;
score.setLevel(level);
solved = false;
return true;
}
return false;
}
//untuk memilih level yang diinginkan
public Screen getLevelScreen() {
if (levelText == null) {
levelText = new TextBox("Pilih Level",
Integer.toString(level),
4, TextField.NUMERIC);
} else {
levelText.setString(Integer.toString(level));
}
return levelText;
}

//untuk membaca data inputan dalam menentukan level
public boolean gotoLevel() {
if (levelText != null) {
String s = levelText.getString();
int l = Integer.parseInt(s);

updateScores();
if (l >= 0 && readScreen(l)) {
level = l;
score.setLevel(level);
solved = false;
repaint();
return true;
}
}
return false;
}
//untuk melakukan perhitungan score
public Screen getScoreScreen() {
Form wokeh = null;
int currPushes = board.getPushes();
int bestPushes = score.getPushes();
int currMoves = board.getMoves();
int bestMoves = score.getMoves();
boolean newbest = solved &&
(bestPushes == 0 || currPushes < bestPushes); wokeh = new Form(null); wokeh.append(new StringItem( newbest ? "New Best:\n" : "Current:\n", currPushes + " pushes\n" + currMoves + " moves")); wokeh.append(new StringItem( newbest ? "Old Best:\n" : "Best:\n", bestPushes + " pushes\n" + bestMoves + " moves")); String title = "Scores"; if (newbest) { title = "Congratulations"; } wokeh.setTitle(title); return wokeh; } //untuk proses melakukan langkah ke atas, bawah, kiri dan kanan protected void keyRepeated(int keyCode) { int action = getGameAction(keyCode); switch (action) { case Canvas.LEFT: case Canvas.RIGHT: case Canvas.UP: case Canvas.DOWN: keyPressed(keyCode); break; default: break; } } //mencatat score dari pergerakan yang telah di lakukan protected void keyPressed(int keyCode) { boolean newlySolved = false; synchronized (board) { cancelTo(); int action = getGameAction(keyCode); int move = 0; switch (action) { case Canvas.LEFT: move = nilai.LEFT; break; case Canvas.RIGHT: move = nilai.RIGHT; break; case Canvas.DOWN: move = nilai.DOWN; break; case Canvas.UP: move = nilai.UP; break; default: return; } int pos = board.getPusherLocation(); int dir = board.move(move); repaintNear(pos, dir); if (!solved && board.solved()) { newlySolved = solved = true; } } if (newlySolved && listener != null) { listener.commandAction(List.SELECT_COMMAND, this); } } //untuk membuat score baru apabila score terbaik terpecahkan private void updateScores() { if (!solved) return; int sp = score.getPushes(); int bp = board.getPushes(); int bm = board.getMoves(); if (sp == 0 || bp < sp) { score.setLevelScore(bp, bm); } } //menentukan waktu private void animateTo(int x, int y) { if (timer == null) timer = new Timer(); if (timertask != null) { timertask.cancel(); timertask = null; } timertask = new waktu(this, board, x, y); timer.schedule(timertask, (long)100, (long)100); } //untuk waktu berhenti ketika keluar private void cancelTo() { if (timertask != null) timertask.cancel(); } protected void pointerPressed(int x, int y) { animateTo(x/cell, y/cell); } public void setCommandListener(CommandListener l) { super.setCommandListener(l); listener = l; } //eksekusi nilai scroe void repaintNear(int loc, int dir) { int x = loc & 0x7fff; int y = (loc >> 16) & 0x7fff;

int size = 1;
if (dir >= 0) {
size += 1;
if ((dir & nilai.MOVEPACKET) != 0) {
size += 1;
}
}
int dx = 1;
int dy = 1;
switch (dir & 3) {
case nilai.UP:
y -= size-1;
dy = size;
break;
case nilai.DOWN:
dy = size;
break;
case nilai.RIGHT:
dx = size;
break;
case nilai.LEFT:
x -= size-1;
dx = size;
break;
}
repaint(x * cell, y * cell, dx * cell, dy * cell);
}

//tampilan graphics pada permainan
protected void paint(Graphics g) {

synchronized (board) {

int x = 0, y = 0, x2 = bwidth, y2 = bheight;


int clipx = g.getClipX();
int clipy = g.getClipY();
int clipw = g.getClipWidth();
int cliph = g.getClipHeight();
x = clipx / cell;
y = clipy / cell;
x2 = (clipx + clipw + cell-1) / cell;
y2 = (clipy + cliph + cell-1) / cell;
if (x2 > bwidth)
x2 = bwidth;
if (y2 > bheight)
y2 = bheight;


g.setColor(groundColor);
g.fillRect(0, 0, w, h);

for (y = 0; y < y2; y++) { for (x = 0; x < x2; x++) { byte v = board.get(x, y); switch (v & ~nilai.PUSHER) { case nilai.WALL: g.setColor(wallColor); g.fillRect(x*cell, y*cell, cell, cell); break; case nilai.PACKET: case nilai.PACKET | nilai.STORE: g.setColor(packetColor); g.fillRect(x*cell+1, y*cell+1, cell-2, cell-2); break; case nilai.STORE: g.setColor(storeColor); if (useDottedLine) { g.setStrokeStyle(Graphics.DOTTED); } g.drawRect(x*cell+1, y*cell+1, cell-2, cell-2); break; case nilai.GROUND: default: break; } if ((v & nilai.PUSHER) != 0) { g.setColor(pusherColor); g.fillArc(x*cell, y*cell, cell, cell, 0, 360); } } } g.drawString("Dorong Kotak Level " + level, 0, h-14, Graphics.TOP|Graphics.LEFT); } } } Coddingan pada file nilai //mengimport api import javax.microedition.lcdui.*; /** * * @author rivan_ipai */ //deklarasi class nilai public class nilai { //deklarasi variable dan objek private int level; private byte[] array; private byte[] pathmap; private int width, height; private int pusher; private int packets = 0; private int stored = 0; private byte[] moves; private int nmoves; private int npushes; public static final int LEFT = 0; public static final int RIGHT = 3; public static final int UP = 1; public static final int DOWN = 2; public static final int MOVEPACKET = 4; public static final byte GROUND = 0; public static final byte STORE = 1; public static final byte PACKET = 2; public static final byte WALL = 4; public static final byte PUSHER = 8; //deklarasi nilai public nilai() { moves = new byte[200]; screen0(); } //untuk mengatur tampilan public void screen0() { width = 9; height = 7; array = new byte[width * height]; level = 0; nmoves = 0; npushes = 0; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { byte t = (x == 0 || y == 0 || x == width - 1 || y == height - 1) ? WALL : GROUND; set(x, y, t); } } packets = 2; stored = 0; set(2, 2, PACKET); set(4, 4, PACKET); set(4, 2, STORE); set(6, 4, STORE); pusher = index(1, 1); } //menyimpan langkah private void saveMove(int move) { if (nmoves >= moves.length) {
byte[] n = new byte[moves.length + 50];
System.arraycopy(moves, 0, n, 0, moves.length);
moves = n;
}
moves[nmoves++] = (byte)move;
}

//meakukan ulang satu langkah
public int undoMove() {
if (nmoves <= 0) return -1; int move = moves[--nmoves]; int rev = (move & 3) ^ 3; int back = pusher + indexOffset(rev); if ((move & MOVEPACKET) != 0) { npushes--; movePacket(pusher + indexOffset(move), rev); } pusher = back; return move; } //proses untuk permainan public int runTo(int x, int y, int max) { int target = index(x, y); if (target < 0 || target >= array.length)
return -1;
if (target == pusher)
return -1;


if (pathmap == null || pathmap.length != array.length) {
pathmap = new byte[array.length];
}

for (int i = 0; i < pathmap.length; i++) pathmap[i] = 127; findTarget(target, (byte)0); if (pathmap[pusher] == 127) { return -1; } else { int pathlen = pathmap[pusher]; int pathmin = pathlen - max; int dir = -1; for (pathlen--; pathlen >= pathmin; pathlen--) {
if (pathmap[pusher - 1] == pathlen) {
dir = LEFT;
saveMove(dir);
pusher--;
} else if (pathmap[pusher + 1] == pathlen) {
dir = RIGHT;
saveMove(dir);
pusher++;
} else if (pathmap[pusher - width] == pathlen) {
dir = UP;
saveMove(dir);
pusher -= width;
} else if (pathmap[pusher + width] == pathlen) {
dir = DOWN;
saveMove(dir);
pusher += width;
} else {

throw new RuntimeException("runTo abort");
}
}
return dir;
}
}
Coddingan file nilainya
//mengimport api
import javax.microedition.rms.*;
/**
*
* @author rivan_ipai
*/

//deklarasi class nilainya
class nilainya {

//deklarasi variable
private int t;
private byte[] h;
private static final int LEVEL_LEN = 5;
private static final byte LEVEL_TAG = 1;
private int gh;
private byte[] jh;
private static final int SCORE_LEN = 13;
private static final byte SCORE_TAG = 2;
private RecordStore ghk;
//menjalankan perintah nilainya
nilainya() {
ghk = null;
t = 0;
h = new byte[LEVEL_LEN];
h[0] = LEVEL_TAG;
putInt(h, 1, 0);
gh = 0;
jh = new byte[SCORE_LEN];
jh[0] = SCORE_TAG;
putInt(jh, 1, 0);
}
boolean open() {
try {
ghk = RecordStore.openRecordStore("PushKotakScores", true);
} catch (RecordStoreException ex) {
}

if (ghk == null)
return false;

try {
t = 0;
RecordEnumeration en = ghk.enumerateRecords(null, null, false);
while (en.hasNextElement()) {
int ndx = en.nextRecordId();
if (ghk.getRecordSize(ndx) == LEVEL_LEN) {
int l = ghk.getRecord(ndx, h, 0);
if (l == LEVEL_LEN &&
h[0] == LEVEL_TAG) {
t = ndx;
break;
}
}
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
}

return true;
}
int getLevel() {
return getInt(h, 1);
}
boolean setLevel(int level) {
putInt(h, 1, level);
putInt(jh, 1, level);
if (ghk == null)
return false;
try {
if (t == 0) {
t = ghk.addRecord(h, 0, h.length);
} else {
ghk.setRecord(t, h, 0, h.length);
}
} catch (RecordStoreException ex) {
System.out.println("RecordStoreException");
ex.printStackTrace();
return false;
}
readScore(level);
return true;
}
int getPushes() {
return getInt(jh, 5);
}
int getMoves() {
return getInt(jh, 9);
}
boolean readScore(int level) {
try {
gh = 0;
RecordEnumeration en = ghk.enumerateRecords(null, null, false);
while (en.hasNextElement()) {
int ndx = en.nextRecordId();
if (ghk.getRecordSize(ndx) == SCORE_LEN) {
int l = ghk.getRecord(ndx, jh, 0);
if (l == SCORE_LEN &&
jh[0] == SCORE_TAG &&
getInt(jh, 1) == level) {
gh = ndx;
return true;
}
}
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
}


jh[0] = SCORE_TAG;
putInt(jh, 1, level);
putInt(jh, 5, 0);
putInt(jh, 9, 0);
return true;
}
boolean setLevelScore(int pushes, int moves) {

putInt(jh, 5, pushes);
putInt(jh, 9, moves);

try {

if (gh == 0) {
gh = ghk.addRecord(jh, 0, jh.length);
} else {
ghk.setRecord(gh, jh, 0, jh.length);
}

} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
}
return true;
}
//untuk menghentikan
void close() {
try {
if (ghk != null) {
ghk.closeRecordStore();
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
Coddingan file waktu
//mengimport api
import java.util.TimerTask;
/**
*
* @author rivan_ipai
*/

//membuat class waktu
class waktu extends TimerTask {

//deklarasi variable
int x, y;
nilai papan;
kanpas canvas;
waktu(kanpas c, nilai b, int x, int y) {
canvas = c;
papan = b;
this.x = x;
this.y = y;
}

//menjalankan program
public void run() {
try {
int pos = papan.getPusherLocation();
int dir = papan.runTo(x, y, 1);
if (dir < 0) { cancel(); } else { canvas.repaintNear(pos, dir); } } catch (Exception ex) { } } }



Pada bagian lain juga akan dijelaskan mengenai Manual Book dan Algoritma pada game ini. Untuk itu anda dapat melihat bagian-bagiannya yang telah saya berikan berikut ini;
Untuk melihat MANUAL BOOK GAME DORONG KOTAK
Untuk melihat ALGORITMA GAME DORONG KOTAK DENGAN Flowchart

Salam para blogger dan para programmer..selamat mencoba..

0 komentar:

Posting Komentar

Glitter Word GeneratorGlitter Word GeneratorGlitter Word GeneratorGlitter Word GeneratorGlitter Word GeneratorGlitter Word GeneratorGlitter Word GeneratorGlitter Word Generator