📄 greedsnake.java
字号:
package greedSnake;
import com.nttdocomo.ui.Display;
import com.nttdocomo.ui.IApplication;
public class GreedSnake extends IApplication implements Runnable {
public static final int GRID_WIDTH = 20;
public static final int GRID_HEIGHT = 24;
public static final int NODE_SIZE = 10;
private Grid grid = null;
private Food food = null;
private Snake snake = new Snake();;
private boolean running;
private int score;
private int level;
private int count;
private int countMove;
private int timeInterval;
// ----------------------------------------
/** Set up game. */
public void start() {
reset();
grid = new Grid(GRID_WIDTH, GRID_HEIGHT, this);
Display.setCurrent(grid);
Thread runner = new Thread(this);
runner.start();
}
private void reset() {
running = false;
score = 0;
level = 0;
count = 0;
countMove = 6;
timeInterval = 200;
}
/** Runnable interface. */
public void run() {
food = grid.addFood();
grid.addSnake(snake);
grid.repaint();
for (;;) {
if (food == null) {
food = grid.addFood();
continue;
}
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!running) {
snake.move();
Node head = snake.getHead();
if (grid.overlapsWith(head) || (snake.ptInSnake(head))) {
running = true;
continue;
}
if ((head.x == food.getX()) && (head.y == food.getY())) {
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0 ? scoreGet : 0;
countMove = 0;
snake.eatFood(food);
grid.reduceFood(food);
food = null;
if (++count % 5 == 0) {
level++;
}
} else {
countMove++;
}
grid.repaint();
} else {
grid.setGameOver();
break;
}
}
grid.repaint();
}
public int getScore() {
return score;
}
/** Get the current level of the game. */
public int getLevel() {
return level;
}
/** Key event handler. */
public void keyPressed(int key) {
if (key == Display.KEY_SELECT) {
grid.setGameOver();
}
if (key == Display.KEY_LEFT) {
snake.setDirection(Snake.LEFT);
}
if (key == Display.KEY_RIGHT) {
snake.setDirection(Snake.RIGHT);
}
if (key == Display.KEY_DOWN) {
snake.setDirection(Snake.DOWN);
}
if (key == Display.KEY_UP) {
snake.setDirection(Snake.UP);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -