package worm; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /*蛇,包含节点*/ //<T>范型:用来约束集合中元素的类型,java 5 以后提供 public class Worm { private List<Node> body = new ArrayList<Node>(); public static final int UP = -10; public static final int DOWN = 10; public static final int LEFT = -1; public static final int RIGHT = 1; /**当前方向*/ private int dir = -1; public Worm() { // TODO Auto-generated constructor stub } //Arrays:数组工具类 public Worm(Node[] nodes,int dir){ List<Node> list = Arrays.asList(nodes);//把数组转换成list this.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<body.size();idx++){ Node n = body.get(idx); if(n.getI()==i && n.getJ()==j){ return true; } } return false; } }
---------------------------------------------------------------
package worm; public class WormPane { private Worm worm; public WormPane() {} public WormPane(Worm worm) { this.worm = worm; } public void print(){ for(int i=0;i<20;i++){ for(int j=0;j<20;j++){ if(i==0 || i==19){//上下边 System.out.print("-"); }else if(j==0 || j==19){//左右边 System.out.print("|"); }else if(worm.contains(i,j)){ System.out.print("#"); }else{ System.out.print(" "); } } System.out.println(); } } }
---------------------------------------------------------------
package worm; import java.util.Scanner; public class WormDemo { public static void main(String[] args){ Node[] nodes = { new Node(4,2), new Node(4,3), new Node(4,4), new Node(5,4), new Node(6,4), new Node(7,4), }; Worm worm = new Worm(nodes,Worm.LEFT); WormPane pane = new WormPane(worm); // pane.print(); // worm.step(); // pane.print(); // worm.step(Worm.UP); // pane.print(); Scanner s = new Scanner(System.in); while(true){ pane.print(); String str = s.nextLine(); if(str.trim().equals("")){ worm.step(); }else if(str.equalsIgnoreCase("W")){ worm.step(Worm.UP); }else if(str.equalsIgnoreCase("s")){ worm.step(Worm.DOWN); }else if(str.equalsIgnoreCase("a")){ worm.step(Worm.LEFT); }else if(str.equalsIgnoreCase("d")){ worm.step(Worm.RIGHT); } } } }