2014-02-24 46 views
1

我有一个相当标准的ascii迷宫,在机器人周围移动,在找到出口和离开(获胜!)之前拾取所需数量的黄金。然而,我不能阻止机器人自行回归,因此赢得的时间需要很长的时间。无法阻止我自己的机器人自动回复

E.g.如果机器人刚刚向南移动,那么在那之后我不希望它能够立即向北移动。

我知道这可能会更有效率,但不要告诉我如何改进机器人,只是如何阻止自己回归本身。

response.equals("FAIL")指的是移动是否将机器人插入墙壁(用#表示)。

public static void randomMove(){ 
    String reponse = "FAIL"; 
    int lastrand = -1; 
    int rand = -1; 
    while(reponse.equals("FAIL")){  
     lastrand = rand; 
     rand = new Random().nextInt(4); 
     if(rand==0 && lastrand != 1){ 
      reponse = robot.Move("N",'B'); 
     }else if(rand==1 && lastrand != 0){ 
      reponse = robot.Move("S",'B'); 
     }else if(rand==2 && lastrand != 3){ 
      reponse = robot.Move("E",'B'); 
     }else if(rand==3 && lastrand != 2){ 
      reponse = robot.Move("W",'B'); 
     }else{ 
      continue; 
     } 
     lastrand = rand; 
    } 

    if(robot.getNewSquare()=='G'){ 
     robot.print(robot.Pickup()); 
    } 
    if(reponse == "Winner!"){ 
     robot.print(reponse); 
     robot.Quit(); 
    } 
} 
+0

给'Robot'一个实例变量'lastMove'。每次你调用'Move'时,检查传入的方向是否与'lastMove'相同;如果它们相等则返回“失败”,以便循环继续;如果不能返回你成功返回的任何东西。 – iamnotmaynard

+4

需要注意的事项;如果机器人遇到死路一条怎么办?它会被撤退,是的? –

+0

我也很困惑你的比较。你为什么要检查rand是0还是lastrand不是1?为什么不先检查是否(rand!= lastrand)? – jgitter

回答

3

它看起来像你的想法加入else continue“不更新lastrand如果我们没动”。但是在循环开始时你仍然有一个lastrand = rand;,无论如何它都会更新它。所以如果你连续两次随机得到北,它就会这样。

+0

甚至删除'lastrand = rand;'不会使它工作。我已经尝试了几乎所有代码的变体,我似乎无法得到它的工作。 –