📄 ufocanvas.java
字号:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.util.*;
import java.io.*;
public class UFOCanvas extends GameCanvas implements Runnable {
private Display display;
private boolean sleeping;
private long frameDelay;
private Random rand;
private Sprite ufoSprite;
private int ufoXSpeed, ufoYSpeed;
public UFOCanvas(Display d) {
super(true);
display = d;
// Set the frame rate (30 fps)
frameDelay = 33;
}
public void start() {
// Set the canvas as the current screen
display.setCurrent(this);
// Initialize the random number generator
rand = new Random();
// Initialize the UFO sprite
ufoXSpeed = ufoYSpeed = 3;
try {
ufoSprite = new Sprite(Image.createImage("/Saucer.png"));
ufoSprite.setPosition(0, 0);
}
catch (IOException e) {
System.err.println("Failed loading image!");
}
// Start the animation thread
sleeping = false;
Thread t = new Thread(this);
t.start();
}
public void stop() {
// Stop the animation
sleeping = true;
}
public void run() {
Graphics g = getGraphics();
// The main game loop
while (!sleeping) {
update();
draw(g);
try {
Thread.sleep(frameDelay);
}
catch (InterruptedException ie) {}
}
}
private void update() {
// Randomly alter the UFO's speed
if (rand.nextInt() % 5 == 0) {
ufoXSpeed = Math.min(Math.max(ufoXSpeed + rand.nextInt() % 2, -8), 8);
ufoYSpeed = Math.min(Math.max(ufoYSpeed + rand.nextInt() % 2, -8), 8);
}
// Move the sprite
ufoSprite.move(ufoXSpeed, ufoYSpeed);
// Wrap the UFO around the screen if necessary
if (ufoSprite.getX() < -ufoSprite.getWidth())
ufoSprite.setPosition(getWidth(), ufoSprite.getY());
else if (ufoSprite.getX() > getWidth())
ufoSprite.setPosition(-ufoSprite.getWidth(), ufoSprite.getY());
if (ufoSprite.getY() < -ufoSprite.getHeight())
ufoSprite.setPosition(ufoSprite.getX(), getHeight());
else if (ufoSprite.getY() > getHeight())
ufoSprite.setPosition(ufoSprite.getX(), -ufoSprite.getHeight());
}
private void draw(Graphics g) {
// Clear the display
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
// Draw the UFO sprite
ufoSprite.paint(g);
// Flush the offscreen graphics buffer
flushGraphics();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -