筆者剛剛開(kāi)始學(xué)習(xí)寫(xiě)游戲,并沒(méi)有什么經(jīng)驗(yàn),因此選擇了門(mén)檻比較低的猜數(shù)字游戲。花了一天的時(shí)間,基本能夠在Nokia6108上運(yùn)行了,界面比較簡(jiǎn)單,為學(xué)習(xí)之用。
下面介紹一下如何實(shí)現(xiàn)猜數(shù)字游戲,其實(shí)這是一個(gè)比較經(jīng)典的游戲。游戲的原理是:游戲開(kāi)始的時(shí)候會(huì)自動(dòng)產(chǎn)生四個(gè)不重復(fù)的隨機(jī)數(shù)字比如1234,用戶輸入四個(gè)數(shù)字,系統(tǒng)通過(guò)判定返回給用戶xAyB的結(jié)果,其中A代表數(shù)字正確位置也正確,B代表數(shù)字正確但是位置不正確。假如用戶猜對(duì)游戲就結(jié)束了,10次內(nèi)沒(méi)有猜對(duì),游戲也結(jié)束。在這里我們重點(diǎn)介紹為游戲而實(shí)現(xiàn)的組件,簡(jiǎn)單的流程控制和游戲邏輯。
首先介紹組件,這里我們提供了兩個(gè)組件,一個(gè)就是Button,他可以接收用戶輸入的數(shù)字,并且可以響應(yīng)用戶的按鍵事件。
首先我們構(gòu)造一個(gè)基本的組件,這個(gè)組件需要包括左上角頂點(diǎn)的坐標(biāo)(x,y),寬度w,高度h以及前景色、背景色。最重要的一點(diǎn)是我們需要給他提供一個(gè)容器來(lái)治理他,因此提供一個(gè)Manager類(lèi)。
package com.j2medev.numbergame;
import javax.microedition.lcdui.*;
import com.nokia.mid.ui.*;
//A root class for Canvas-based components.
//Because Area extends Canvas, you can actually
//use a component directly as a Canvas, although
//it's recommended you place it on Manager.
public abstract class Area extends FullCanvas
{
PRotected int x;
protected int y;
protected int w;
protected int h;
protected Font font;
protected Manager parent;
protected int backcolor = -1;
protected int forecolor = -1;
protected Area(int x, int y, int w, int h)
{
this(x, y, w, h, null);
}
protected Area(int x, int y, int w, int h, Font f)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.font = f;
}
// Erase the background using backcolor
protected void eraseBackground(Graphics g)
{
g.setColor(getBackColor());
if (parent == null)
{
g.fillRect(0, 0, getCanvasWidth(), getCanvasHeight());
} else
{
g.fillRect(0, 0, w, h);
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注