[Java] 纯文本查看 复制代码 import java.awt.Color;
import java.awt.Graphics;
public class Snake {
private Node head = null;
private Node tail = null;
private int size = 0;
private Node n = new Node(20,5,Dir.L);
public Snake() {
head = n;
tail = n;
size = 1;
}
public void addToTail() {
Node node = null;
switch (tail.dir) {
case L:
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 R:
node = new Node(tail.row,tail.col-1,tail.dir);
break;
case D:
node = new Node(tail.row-1,tail.col,tail.dir);
break;
}
tail.next = node;
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 U:
node = new Node(head.row-1,head.col,head.dir);
break;
case R:
node = new Node(head.row,head.col+1,head.dir);
break;
case D:
node = new Node(head.row+1,head.col,head.dir);
break;
}
node.next = head;
head = node;
size++;
}
public void draw(Graphics g) {
if(size <= 0) return ;
for(Node n = head; n != null; n = n.next) {
n.draw(g);
}
}
public class Node {
int w = Yard.BLOCK_SIZE;
int h = Yard.BLOCK_SIZE;
int row,col;
Dir dir = Dir.L;
Node next = null;
Node(int row, int col, Dir dir) {
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);
}
}
}
昨天发了一个贪吃蛇小游戏的Yard的部分代码,有人反映说部分代码太少了,这一点我是知道的,因为我也在学习中,所以说呢。。喜欢的可以跟着我的代码更新,我们可以互相学习,一起努力!
|