スポンサーリンク
スポンサーリンク
解答例
let totalGems = randomNumberOfGems
var gemCounter = 0
world.place(Block(), atColumn: 0, row: 2)
world.place(Block(), atColumn: 3, row: 3)
let expert = Expert()
world.place(expert, facing: east, atColumn: 2, row: 3)
while gemCounter < totalGems {
if expert.isOnGem {
expert.collectGem()
gemCounter += 1
}
if expert.isBlocked {
expert.turnRight()
if expert.isBlocked {
expert.turnRight()
if expert.isBlocked {
expert.turnRight()
}
}
}
expert.moveForward()
}
解説
ランダムに宝石が現れるので、
while gemCounter < totalGems {}
として、宝石カウンターで数えていかないといけませんね。
一つ宝石を取るたびに、
gemCounter = gemCounter + 1
として、『gemCounterに1を加えたものを、gemCounterに戻す』作業を繰り返しますが、
これは
gemCounter += 1
と書いてもOKでしたね。
慣れると簡単なので、こちらを使うようにしましょう。
今回はブロックを追加して、4つの陸地をワープで周る形になっていますね。
要点まとめ
・効率よく周るルートを考えて、比較演算子を使ってゴールしよう
スポンサーリンク