// 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() { process_keys(); 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 process_keys() { int keys = getKeyStates(); // System.out.println("keys = " + keys); if ((keys & LEFT_PRESSED) != 0) { System.out.println("Pressed left!"); ball_dx -= 1; } if ((keys & RIGHT_PRESSED) != 0) { System.out.println("Pressed right!"); ball_dx += 1; } if ((keys & UP_PRESSED) != 0) { System.out.println("Pressed up!"); ball_dy -= 1; } if ((keys & DOWN_PRESSED) != 0) { System.out.println("Pressed down!"); ball_dy += 1; } if ((keys & FIRE_PRESSED) != 0) { System.out.println("Pressed FIRE!"); ball_dx = 0; ball_dy = 0; } } 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); } } // class Studscanvas