📄 snakemodel.java
字号:
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JOptionPane;
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public class SnakeModel implements Runnable {
boolean matrix[][];
LinkedList nodeArray = new LinkedList();
Node food;
int direction = 2;
int timeInterval = 200;
int initArrayLen;
int maxX;
int maxY;
boolean running = false;
int countMove = 0;
int score = 0;
boolean paused = false;
GreedSnake gs;
double speedChangeRate = 0.75;
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel(GreedSnake gs, int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
this.gs = gs;
matrix = new boolean[maxX][maxY];
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
matrix[i][j] = false;
}
}
initArrayLen = maxX > 20 ? 10 : maxX / 2;
for (int i = 0; i < initArrayLen; i++) {
int x = maxX / 2 + i;
int y = maxY / 2;
Node n = new Node(x, y);
nodeArray.addLast(n);
matrix[x][y] = true;
}
food = createFood();
matrix[food.x][food.y] = true;
}
private Node createFood() {
int x = 0;
int y = 0;
Random r = new Random();
do {
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y] == true);
return new Node(x, y);
}
public void changeDirection(int newDirection) {
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) {
if (matrix[x][y]) {
if (x == food.x && y == food.y) {
nodeArray.addFirst(food);
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0 ? scoreGet : 10;
countMove = 0;
food = createFood();
matrix[food.x][food.y] = true;
return true;
} else
return false;
} else {
nodeArray.addFirst(new Node(x, y));
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
} else
return false;
}
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn()) {
gs.repaint();
} else {
JOptionPane.showMessageDialog(null, "GAME OVER",
"Game Over", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
public void speedUp() {
timeInterval *= speedChangeRate;
}
public void speedDown() {
timeInterval /= speedChangeRate;
}
public void changePauseState() {
paused = !paused;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -