stanford編程方法學(xué)karel作業(yè)一problem2

/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the   quad"
 * problem from Assignment 1.  In addition to editing the   program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */

import stanford.karel.*;

public class StoneMasonKarel extends SuperKarel {
  public void run(){
      while(frontIsClear()){
          turnEast();               //將起始位置朝東
          SetColumnStone();     //將一列全部填滿
          turnBack();               //填滿一列后回到該列下方
          move4times();         //移動四列
        }
    
        //為了讓最后一列也可以判斷,需要加上最后一次循環(huán)
        SetColumnStone();       //將一列全部填滿
        turnBack();             //填滿一列后回到該列    下方
        }
    private void move4times() {
      turnLeft();
      for(int i=0;i<4;i++){
          move();
      }
    }

  //轉(zhuǎn)向東
  private void turnEast() {
      while(notFacingEast()){       //如果不是朝東,向左轉(zhuǎn),直到朝東
          turnLeft();
      }
  }

  //返回下方
  private void turnBack() {
      turnAround();
      while(frontIsClear()){
          move();
      }
  }

  //填滿一列
  private void SetColumnStone() {
      turnLeft();                   //出發(fā)時向左拐
      while(frontIsClear()){
          if(noBeepersPresent()){       //判斷當(dāng)前位置是否有beeper
              putBeeper();
          }
          move();
      }
      if(noBeepersPresent()){       //判斷當(dāng)前位置是否有beeper,防止最后一個判斷錯誤
          putBeeper();
      }
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容