📄 maincanvas.java
字号:
package com.j2medev.chapter5.game;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class MainCanvas extends GameCanvas implements Runnable,CommandListener {
private ScrollScreen midlet = null;
private boolean isPlay;
private long delay; //线程休眠的时间间隔
private int width; // 屏幕宽度
private int height; //屏幕高度
private int scnX, scnY; //可视窗口的左上角坐标
Image backgroundImage;
private Sprite backgroundSprite;
private LayerManager layerManager;
public static final Command exitCommand = new Command("退出",Command.EXIT, 1);
public MainCanvas(ScrollScreen midlet) throws Exception {
super(true);
this.midlet = midlet;
width = getWidth();
height = getHeight();
scnX = 55;
scnY = 20;
delay = 20;
backgroundImage = Image.createImage("/background.png");
backgroundSprite = new Sprite(backgroundImage);
layerManager = new LayerManager();
layerManager.append(backgroundSprite);
this.addCommand(exitCommand);
this.setCommandListener(this);
}
public void start() {
isPlay = true;
//启动游戏线程
Thread t = new Thread(this);
t.start();
}
public void stop() {
isPlay = false;
}
//游戏主循环
public void run() {
Graphics g = getGraphics();
while (isPlay == true) {
input();
drawScreen(g);
try {
//线程休眠
Thread.sleep(delay);
} catch (InterruptedException ie) {
}
}
}
//处理用户输入 支持四个方向的屏幕滚动
private void input() {
int keyStates = getKeyStates();
//根据用户输入调整scnX和scnY的值
if ((keyStates & LEFT_PRESSED) != 0) {
if (scnX - 1 > 0)
scnX--;
}else if ((keyStates & RIGHT_PRESSED) != 0) {
if (scnX + 1 + 140 < backgroundImage.getWidth())
scnX++;
}else if((keyStates & UP_PRESSED)!=0){
if(scnY -1 > 0){
scnY--;
}
}else if((keyStates & DOWN_PRESSED)!=0){
if(scnY+1+140<backgroundImage.getHeight()){
scnY++;
}
}
}
private void drawScreen(Graphics g) {
//清屏
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x0000ff);
//设置视窗
layerManager.setViewWindow(scnX, scnY, 140, 140);
layerManager.paint(g, 20, 20);
//绘制到主屏幕
flushGraphics();
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == exitCommand){
//停止线程,销毁MIDlet
stop();
midlet.exit();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -