/**
* @(#)Snake.java
*
*
* @author
* @version 1.00 2008/12/12
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Snake {
GamePanel panel;
Node food;
int mark=0;
boolean[][] all;
public static boolean run;
int maxX;
int maxY;
public static int left = 1;
public static int up = 2;
public static int right = 3;
public static int down = 4;
int direction = 4;
LinkedList snakeList = new LinkedList();
public Snake(GamePanel p, int maxX, int maxY) {
panel = p;
this.maxX = maxX;
this.maxY = maxY;
all = new boolean[maxX][maxY];
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
all[i][j] = false;
}
}
int arrayLength = maxX > 20 ? 10 : maxX / 2;
for (int i = 0; i < arrayLength; i++) {
int x = maxX / 10 + i;
int y = maxY / 10;
snakeList.addFirst(new Node(x, y));
all[x][y] = true;
}
food = createFood();
all[food.x][food.y] = true;
}
// 蛇移动的方法
public void move() {
Node n = (Node) snakeList.getFirst();
int x = n.x;
int y = n.y;
if (direction == 3) {
x++;
} else if (direction == 4) {
y++;
} else if (direction == 1) {
x--;
} else if (direction == 2) {
y--;
}
// 实现对蛇撞到自身的检测
if ((x>=0 && x <= GamePanel.panelWidth / 15 - 1)
&& (0 <= y && y <= GamePanel.panelHeight / 15 - 1)) {
if (all[x][y]) {
if (x == food.x && y == food.y) {
mark++;
MarkPanel.markLabel.setText("分数为:"+mark);
snakeList.addFirst(food);
food = createFood();
all[food.x][food.y] = true;
} else {
JOptionPane.showMessageDialog(null, "你撞到自己了");
System.exit(0);
}
} else {
snakeList.addFirst(new Node(x, y));
all[x][y] = true;
Node l = (Node) snakeList.getLast();
snakeList.removeLast();
all[l.x][l.y] = false;
}
} else {
JOptionPane.showMessageDialog(null, "越界了,游戏结束");
System.exit(0);
}
panel.repaint();
}
public Node createFood() {
int x = 0;
int y = 0;
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (all[x][y]);
return new Node(x, y);
}
//设置蛇不能回头
public void changeDirection(int newDirection) {
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
public void drawMap(Graphics2D g) {
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
if (all[i][j] == true) {
g.setColor(Color.red);
g.fillRect(i, j, 4, 4);
}
}
}
}
}
评论0