62,614
社区成员
发帖
与我相关
我的任务
分享
public class SampleKarel extends SuperKarel {
int count = 0;
boolean flag = true;
LinkedList<Node> list = new LinkedList<Node>();
String beeperStr = JOptionPane.showInputDialog("请输入所要pick的beeper个数:");
int beeperInt = Integer.parseInt(beeperStr);
public void run() {
while(count < beeperInt && flag){
judgeAndPick();
Node n = new Node(getLocation(),getDirection());
if (list.contains(n)) {
switch ((list.get(list.indexOf(n))).getCount()) {
case 1:
turnLeft();
break;
case 2:
turnLeft();
turnLeft();
break;
case 3:
turnRight();
break;
case 4:
JOptionPane.showMessageDialog(null, "你已经完成任务了!");
flag = false;
break;
}
} else {
list.add(n);
}
if (frontIsBlocked() || rightIsClear()) {
changeDirection();
}
move();
}
}
public void changeDirection() {
if (rightIsClear()) {
turnRight();
} else {
if (leftIsBlocked()) {
turnLeft();
}
turnLeft();
}
}
public void judgeAndPick() {
if (beepersPresent()) {
pickBeeper();
count++;
}
}
class Node {
private java.awt.Point pt;
private int dir;
private int count = 1;
public Node() {
}
public Node(java.awt.Point pt, int dir) {
this.pt = pt;
this.dir = dir;
}
public int getCount() {
return count;
}
public void addCount() {
count++;
}
public boolean equals(Object obj) {
Node n = (Node)obj;
if (n == null) {
return false;
} else if (this.pt == n.pt && this.dir == n.dir){
return true;
}
return false;
}
}