スポンサーリンク
スポンサーリンク
解答例
func turnAround() {
turnLeft()
turnLeft()
}
func checkSquare() {
if isOnGem {
collectGem()
} else if isOnClosedSwitch {
toggleSwitch()
}
}
func collectOrToggle() {
moveForward()
checkSquare()
turnAround()
}
func collectOrToggleThenTurnRight() {
collectOrToggle()
moveForward()
turnRight()
}
func collectOrToggleThenTurnLeft() {
collectOrToggle()
moveForward()
turnLeft()
}
turnLeft()
moveForward()
moveForward()
greenPortal.isActive = false
for i in 1 ... 3 {
collectOrToggleThenTurnRight()
}
collectOrToggle()
greenPortal.isActive = true
moveForward()
greenPortal.isActive = false
collectOrToggleThenTurnLeft()
collectOrToggleThenTurnLeft()
moveForward()
moveForward()
orangePortal.isActive = false
moveForward()
for i in 1 ... 3 {
collectOrToggleThenTurnRight()
}
collectOrToggle()
orangePortal.isActive = true
moveForward()
orangePortal.isActive = false
turnLeft()
collectOrToggleThenTurnRight()
collectOrToggle()
解説
この課題も、ゴールの仕方が色々あります。
左右似たような配置ですが、宝石とスイッチが逆だったりしますね。
とてもややこしいのですが、小さなかたまりの動作を関数でひとまとめにすると、少しわかりやすくなります。
使い回しできる法則を見つけ出し、forループなども駆使してゴールを目指しましょう。
上手なコードを書けば、プログラムの実行が速くなります。
アプリケーションがさくさく動いて、バッテリーも長持ちするので、使う人に喜んでもらうことができますよ。
以下のようなやり方もありますので、どうぞご参考にしてみてくださいね。
【その2】
func turnAround() {
turnLeft()
turnLeft()
}
func checkSquare() {
if isOnGem {
collectGem()
} else if isOnClosedSwitch {
toggleSwitch()
}
}
func collectOrToggle() {
checkSquare()
turnAround()
moveForward()
turnLeft()
moveForward()
}
orangePortal.isActive = false
turnRight()
moveForward()
moveForward()
moveForward()
collectOrToggle()
toggleSwitch()
orangePortal.isActive = true
turnAround()
moveForward()
orangePortal.isActive = false
moveForward()
for i in 1 ... 3 {
collectOrToggle()
}
collectGem()
turnAround()
moveForward()
turnRight()
greenPortal.isActive = false
for i in 1 ... 4 {
moveForward()
}
collectOrToggle()
collectGem()
greenPortal.isActive = true
turnAround()
moveForward()
moveForward()
greenPortal.isActive = false
for i in 1 ... 3 {
collectOrToggle()
}
toggleSwitch()
【その3】
func turnAround() {
turnRight()
turnRight()
}
func collectOrToggle() {
if isOnGem {
collectGem()
} else if isOnClosedSwitch {
toggleSwitch()
}
turnAround()
moveForward()
turnRight()
moveForward()
}
func move3() {
moveForward()
moveForward()
moveForward()
}
turnRight()
move3()
orangePortal.isActive = false
for i in 1 ... 3 {
collectOrToggle()
}
collectGem()
move3()
greenPortal.isActive = false
for i in 1 ... 3 {
collectOrToggle()
}
toggleSwitch()
greenPortal.isActive = true
turnAround()
moveForward()
greenPortal.isActive = false
turnAround()
moveForward()
collectOrToggle()
collectGem()
turnAround()
moveForward()
turnRight()
move3()
moveForward()
turnRight()
moveForward()
collectOrToggle()
toggleSwitch()
要点まとめ
・ゴールの仕方は1つではないので、色々試してみよう
スポンサーリンク