我们现在来学习一下如何应用前两关的知识。
在这里,我们要让专家按照需求进行操作。
面临的环境是比较复杂的。四个上下的砖块,高度不同。
代码如下:
let expert = Expert()
let character = Character()
func lockControl(up: Bool,numTimes: Int) {
for i in 1 ... numTimes {
if up == true {
expert.turnLockUp()
}else {
expert.turnLockDown()
}
expert.turnLeft()
}
}
func move(distance: Int) {
for i in 1 ... distance {
character.moveForward()
}
character.collectGem()
}
func turnAround() {
character.turnLeft()
character.turnLeft()
}
lockControl(up: true, numTimes:16)
move(distance: 2)
character.turnRight()
move(distance: 2)
character.turnRight()
move(distance: 4)
turnAround()
move(distance: 1)
lockControl(up: false, numTimes:12)
character.turnRight()
move(distance: 1)
turnAround()
move(distance: 2)
character.turnLeft()
move(distance: 2)
turnAround()
move(distance: 6)
turnAround()
move(distance: 2)
character.turnLeft()
move(distance: 2)
在这里我们可以感受到参数的方便作用了。执行后:
同样,注释还是大家自己加上去,没有注释的代码,时间久了就会忘记。