加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Snake.java 2.44 KB
一键复制 编辑 原始数据 按行查看 历史
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Snake {
Node head=null;
Node tail=null;
int size=0;
private Node node=new Node(20,30,Dir.L);
private Yard y;
public Snake(Yard y) {
head=node;
tail=node;
size=1;
this.y=y;
}
private void move() {
addToHead();
deletFromTail();
}
public void addToHead() {
Node n=null;
switch(head.dir) {
case L:
n=new Node(head.row,head.col-1,head.dir);
break;
case R:
n=new Node(head.row,head.col+1,head.dir);
break;
case U:
n=new Node(head.row-1,head.col,head.dir);
break;
case D:
n=new Node(head.row+1,head.col,head.dir);
break;
}
head.prior=n;
n.next=head;
head=n;
size++;
}
private void deletFromTail() {
if(tail==null) return;
else{
tail=tail.prior;
tail.next=null;
}
}
private Rectangle getRect() {
return new Rectangle(Yard.BLOCK_SIZE*head.col, Yard.BLOCK_SIZE*head.row,head.w,head.h);
}
public void eat(Egg e) {
if(this.getRect().intersects(e.getRect())) {
e.reAppear();
this.addToHead();
y.score+=5;
}
}
public void checkDead() {
if(head.row<3||head.row>Yard.ROWS-1||head.col<0||head.col>Yard.COLS) {
y.stop();
}
for(Node n=head.next;n!=null;n=n.next) {
if(head.row==n.row&&head.col==n.col){
y.stop();
}
}
}
public void draw(Graphics g) {
if(size<=0) {
return;
}
else {
for(Node n=head;n!=null;n=n.next) {
n.draw(g);
}
}
move();
}
private class Node {
int w=Yard.BLOCK_SIZE;
int h=Yard.BLOCK_SIZE;
int row,col;
Node next=null;
Node prior=null;
Dir dir=Dir.L;
public Node(int row,int col,Dir dir) {
this.row=row;
this.col=col;
this.dir=dir;
}
public 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) {
int key=e.getKeyCode();
switch(key) {
case KeyEvent.VK_UP:
if(head.dir!=Dir.D) {
head.dir=Dir.U;
}
break;
case KeyEvent.VK_DOWN:
if(head.dir!=Dir.U) {
head.dir=Dir.D;
}
break;
case KeyEvent.VK_RIGHT:
if(head.dir!=Dir.L) {
head.dir=Dir.R;
}
break;
case KeyEvent.VK_LEFT:
if(head.dir!=Dir.R) {
head.dir=Dir.L;
}
break;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化