【发布时间】:2021-09-30 12:32:36
【问题描述】:
我正在通过 Apple 官方“Learn to Code”学习 swift,目前正在学习 Learn to Code 2。如下所示:
我的重点不是解决难题,而是努力完善其中的一部分。我正在努力让角色在无法向左或向右移动时直线前进。我知道我可以使用这个逻辑运算符:
if (isBlockedLeft == true && isBlockedRight == true) {
moveForward()
}
但这不是我想要做的。我想先声明一个像这样的常量
let Straight = (isBlockedLeft == true && isBlockedRight == true)
并通过将代码包含在 if 条件中来简化代码:
if Straight {
moveForward()
}
但是,当我这样做时,有问题......
应该发生什么:从箭头开始,角色应该移动四次并停在边缘,因为 isBlockedRight 由于旁边的门户而变为 false。
实际发生的情况:从箭头开始,角色向前移动并继续向前移动,即使在边缘也是如此。
下面是完整的代码(为了清楚起见,非必要部分已被删除)。请记住,我的目标不是解决难题,而是尝试靠近传送门并停下来:
// Define what "Straight" is
let Straight = (isBlockedLeft == true && isBlockedRight == true)
let straight = Straight
// Define the function that determines what to do when going "Straight"
func GoStraight() {
if straight {
moveForward()
}
}
//Part that powers the character's movement. Even though it's an infinite loop, the character should still stop as isBlockedRight no longer qualifies as true while at the edge.
while true {
GoStraight()
}
【问题讨论】:
-
在每次“移动”操作之后,您肯定需要重新评估
isBlockedLeft和isBlockedRight条件并更新您的straight变量