// Studscanvas.java import java.util.*; import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.*; public class Studscanvas extends GameCanvas { int ball_radius; double ball_x, ball_y, ball_dx, ball_dy; Timer the_timer; Graphics g; public Studscanvas() { super(false); int screen_width = getWidth(); int screen_height = getHeight(); ball_radius = 5; ball_x = screen_width / 2; ball_y = screen_height / 2; ball_dx = 1; ball_dy = -1; } public void showNotify() { the_timer = new Timer(); g = getGraphics(); TimerTask task = new TimerTask() { public void run() { update_game_state(); render(); flushGraphics(); } }; the_timer.schedule(task, 0, 20); } public void hideNotify() { if (the_timer != null) { the_timer.cancel(); the_timer = null; } } private void update_game_state() { int screen_width = getWidth(); int screen_height = getHeight(); ball_x += ball_dx; ball_y += ball_dy; if (ball_x + ball_radius >= screen_width) { ball_dx *= -1; } else if (ball_x - ball_radius <= 0) { ball_dx *= -1; } if (ball_y - ball_radius <= 0) { ball_dy *= -1; } else if (ball_y + ball_radius >= screen_height) { ball_dy *= -1; } // System.out.println("ball_x = " + ball_x + ", ball_y = " + ball_y + // ", ball_dx = " + ball_dx + " + ball_dy = " + ball_dy); } public void render() { g.setColor(0xffffff); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(0x000000); g.drawString("dx = " + ball_dx + ", dy = " + ball_dy, 0, 0, Graphics.TOP | Graphics.LEFT); g.fillArc((int)(ball_x - ball_radius), (int)(ball_y - ball_radius), ball_radius * 2, ball_radius * 2, 0, 360); } protected void keyPressed(int keyCode) { System.out.println("keyPressed, keyCode = " + keyCode); int game_action = getGameAction(keyCode); System.out.println("keyPressed, game_action = " + game_action); switch (game_action) { case UP: ball_dy -= 1; break; case DOWN: ball_dy += 1; break; case LEFT: ball_dx -= 1; break; case RIGHT: ball_dx += 1; break; case FIRE: ball_dx = 0; ball_dy = 0; break; } } protected void keyRepeated(int keyCode) { System.out.println("keyRepeated, keyCode = " + keyCode); keyPressed(keyCode); } protected void keyReleased(int keyCode) { System.out.println("keyReleased, keyCode = " + keyCode); } } // class Studscanvas