package coreGame; import javax.microedition.lcdui.*; import java.util.Random; import com.ckrocket.gui.*; import menu.*; import javax.microedition.midlet.MIDlet; public class CoreGame extends TouchCanvas implements Runnable{ int width, height, sleep; int score; Snake snake; Bait bait; KeyPad keypad; PauseMenu pause; Display display; MIDlet main; long startTime; Thread game; Image gameImage; public CoreGame( MIDlet main) { setFullScreenMode(true); game = new Thread(this); sleep = 250; score = 0; width = getWidth(); height = getHeight(); snake = new Snake(); keypad = new KeyPad(width, height, this); this.main = main; pause = new PauseMenu("pause", main, this); game.start(); display = Display.getDisplay(main); gameImage = Image.createImage(240, 320); bait = new Bait(random(0, gameImage.getWidth(), 10), random(0, gameImage.getHeight(), 10)); snake.create((width/2) - 5, (height / 2) - 5); snake.direction = Snake.UP; } public void paint(Graphics g) { g.setColor(255, 255, 255); g.fillRect(0, 0, width, height); g.drawImage(resize(gameImage, width, height - 60), 10, 10, 0); keypad.paint(g); //draw score g.setColor(0, 0, 0); g.fillRect(0, 0, width, 10); g.setColor(255, 255, 255); g.drawString("your score : " + score, 0, 2, 17); } public void run(){ while(true){ gameProcess(); keyListner(); if(sleep(sleep))snake.moving(); paintGame(gameImage.getGraphics()); repaint(); } } private void paintGame(Graphics g){ snake.paintSnake(g); bait.paint(g); } private void gameProcess(){ PartSnake localPart = (PartSnake)(snake.snake.elementAt(0)); int x = localPart.x; int y = localPart.y; if(x == bait.x && y == bait.y){ score++; snake.add(); bait = new Bait(random(0, gameImage.getWidth(), 10), random(0, gameImage.getHeight(), 10)); } } public void keyListner(){ if(keypad.keyText.equals("up") ){ snake.direction = Snake.UP; } if(keypad.keyText.equals("down") ){ snake.direction = Snake.DOWN; } if(keypad.keyText.equals("left") ){ snake.direction = Snake.LEFT; } if(keypad.keyText.equals("right") ){ snake.direction = Snake.RIGHT; } if(keypad.keyText.equals("pause") ){ SetPaint.set(main, pause); } } public static int random(int min, int max, int dim) { return min + new Random().nextInt((int)((max-min)/dim)) * dim; } public boolean sleep(long mills){ if(startTime == 0)startTime = System.currentTimeMillis(); long thisTime = System.currentTimeMillis(); long lastTime = thisTime - startTime; if(lastTime >= mills){ startTime = System.currentTimeMillis(); lastTime = 0; return true; }else{ return false; } } }