你看下我写的,对比一下
package snake;import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;public class Snake {
private Node head = null;
private Node tail = null;
private int size = 0;
private Node n = new Node(10, 20, Direction.L);
private Yard y; public Snake(Yard y) {
head = n;
tail = n;
size = 1;
this.y = y;
} public void eat(Egg e) {
if (this.getRectangle().intersects(e.getRectangle())) {
e.reappear();
this.addToHead();
y.setScore(y.getScore() + 5);
}
} private Rectangle getRectangle() {
return new Rectangle(Yard.BLOCK_SIZE * head.col, Yard.BLOCK_SIZE
* head.row, head.w, head.h);
} public void addToTail() {
Node node = null;
switch (tail.dir) {
case L:
node = new Node(tail.row, tail.col + 1, tail.dir);
break;
case R:
node = new Node(tail.row, tail.col - 1, tail.dir);
break;
case U:
node = new Node(tail.row + 1, tail.col, tail.dir);
break;
case D:
node = new Node(tail.row - 1, tail.col, tail.dir);
break;
}
tail.next = node;
node.pre = tail;
tail = node;
// size++;
} public void addToHead() {
Node node = null;
switch (head.dir) {
case L:
node = new Node(head.row, head.col - 1, head.dir);
break;
case R:
node = new Node(head.row, head.col + 1, head.dir);
break;
case U:
node = new Node(head.row - 1, head.col, head.dir);
break;
case D:
node = new Node(head.row + 1, head.col, head.dir);
break;
}
head.pre = node;
node.next = head;
head = node;
// size++;
} public void draw(Graphics g) {
if (size <= 0)
return;
move();
for (Node n = head; n != null; n = n.next) {
n.draw(g);
}
} private void move() {
addToHead();
delFromTail();
checkDead();
} private void checkDead() {
// TODO Auto-generated method stub
if (head.row > Yard.ROWS || head.row < 2 || head.col > Yard.COLS
|| head.col < 0) {
y.stop();
}
for (Node n = head.next; n != null; n = n.next) {
if (head.row == n.row && head.col == n.col) {
y.stop();
}
}
} private void delFromTail() {
// TODO Auto-generated method stub
if (size == 0)
return;
tail = tail.pre;
tail.next = null;
} private class Node {
int w = Yard.BLOCK_SIZE;
int h = Yard.BLOCK_SIZE;
int row, col;
Direction dir = Direction.L;
Node next = null;
Node pre = null; public Node(int row, int col, Direction dir) {
// TODO Auto-generated constructor stub
this.row = row;
this.col = col;
this.dir = dir;
} void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.BLACK);
g.fillRect(Yard.BLOCK_SIZE * col, Yard.BLOCK_SIZE * row, w, h);
g.setColor(c);
}
} public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
if (head.dir != Direction.R)
head.dir = Direction.L;
break;
case KeyEvent.VK_RIGHT:
if (head.dir != Direction.L)
head.dir = Direction.R;
break;
case KeyEvent.VK_UP:
if (head.dir != Direction.D)
head.dir = Direction.U;
break;
case KeyEvent.VK_DOWN:
if (head.dir != Direction.U)
head.dir = Direction.D;
break;
}
}
}