Thứ Bảy, 17 tháng 11, 2012

chia các phần trong một trò chơi

hãy tưởng tượng, khi mở một trò chơi ra bạn sẽ có thể gặp một phần giới thiệu trước, sau đó là menu, mỗi một lựa chọn trong menu lại đưa ra một màn hình khác nhau, như màn chơi, phần hướng dẫn, phần tóm tắt...
bài này sẽ tạo ra một class hiển thị các phần như vậy, và menu của chúng ta chỉ có 3 mục: play game, help, about, với một nút exit ở dưới trái màn hình.
file Midlet của chúng ta sẽ chỉ có thêm một dòng so với ban đầu:
//Midlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


public class Midlet extends MIDlet {
public void startApp() {
Display.getDisplay(this).setCurrent(new game(this));
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}
}
tạo một class mới đặt tên là game, có nội dung như sau:
//game.java

import javax.microedition.lcdui.*;
public class game extends Canvas {

String[] smenu={"play game","help","about"};
int w,h,fh,mindex=0,mode=0;
Midlet m;
Font f=Font.getDefaultFont();

public game(Midlet m){
this.m=m;
setFullScreenMode(true);
w=getWidth();
h=getHeight();
fh=f.getHeight();}

public void paint(Graphics g){
g.setColor(0);
g.fillRect(0, 0, w, h);
g.setColor(0xf0f0f0);
switch(mode){
case 0: //vẽ menu
//vẽ thanh index
g.fillRect(0, (h-fh*3)/2+mindex*fh, w, fh);
//vẽ các menu
for(int i=0;i<smenu.length;i++){
if(i==mindex){g.setColor(0);}else{g.setColor(0xf0f0f0);}
g.drawString(smenu[i],w/2 ,( h-fh*3)/2+i*fh, Graphics.HCENTER|Graphics.TOP);
}
break;
case 1: //vẽ game play
g.drawString(smenu[0], w/2, h/2, Graphics.BASELINE|Graphics.HCENTER);
break;
case 2: //vẽ help
g.drawString(smenu[1], w/2, h/2, Graphics.BASELINE|Graphics.HCENTER);
break;
case 3: //vẽ about
g.drawString(smenu[2], w/2, h/2, Graphics.BASELINE|Graphics.HCENTER);
break;}
//vẽ nút lệnh
g.setColor(0xf0f0f0);
g.drawString("exit", 0, h, Graphics.LEFT|Graphics.BOTTOM);
g.drawString("back", w, h, Graphics.RIGHT|Graphics.BOTTOM);
repaint();}

public void keyPressed(int k){

//cho di chuyển vị trí thanh menu
if(k==-1)mindex--;
if(k==-2)mindex++;
if(mindex<0) mindex=smenu.length-1;
if(mindex==smenu.length) mindex=0;

//thay đổi mode khi lựa chọn menu
if(k==-5)mode=mindex+1;

//các lệnh cho menu góc màn hình
if(k==-7)mode=0;
if(k==-6)m.notifyDestroyed();}
}


Không có nhận xét nào: