贪吃蛇代码
package day14worm;
public class Node {
private int i;
private int j;
public Node(){
}
public Node(int i, int j) {
super();
this.i = i;
this.j = j;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj==null)
return false;
if(this==obj)
return true;
if(obj instanceof Node){
Node other=(Node) obj;
return i==other.i&&j==other.j;
}
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return i*10000+j;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "#";
}
package day14worm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Worm {
private List body=new ArrayList();//表示线性表中全是Node类型;
// i
//j
public static final int UP=-10; //0 -1
public static final int DOWN=10; //0 1
public static final int LEFT=-1;
public static final int RIGHT=1;
private int dir;
public Worm(){
}
public Worm(Node[] nodes,int dir){
List list=Arrays.asList(nodes);
body.addAll(list);
this.dir=dir;
}
//走一步
public void step(){
Node head=body.get(0);
int i=head.getI()+dir/10;
int j=head.getJ()+dir%10;
Node newHead=new Node(i,j);
body.add(0,newHead);
if(eatSomething()){
return;
}
body.remove(body.size()-1); }
private boolean eatSomething(){
return false;
}
public void step(int dir){
if(this.dir+dir==0){
throw new IllegalArgumentException("方向错误");
}
this.dir=dir;
step();
}
public boolean contains(int i,int j){
for(int idx=0;idx