添加计时器,确保按键间隔足够大才移动方向 #9
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
当蛇向右移动到右侧边界时,你快速按下向下或向上和向左的方向键。由于蛇在移动过程中,方向的改变可能没有按照预期的顺序进行,或者在一个短时间内方向改变过于频繁,导致蛇头在下次移动时直接移动到了身体所在的位置,游戏结束。同理,当蛇向其他方向(向左、向上、向下)时,同时按下相反方向和相邻方向都会导致蛇误判为撞到自己,游戏结束。
为了避免这种情况,可以在 setMoveDirection 函数中添加更多的逻辑,确保蛇在一个较短的时间内不能进行过于频繁的方向改变。例如,可以添加一个计数器,记录蛇最近一次改变方向的时间,只有当时间间隔超过一定值时,才允许蛇改变方向。
msecsTo() 是 QTime 类的另一个成员函数,用于计算从当前 QTime 对象(lastDirectionChangeTime)到指定 QTime 对象(currentTime)之间的毫秒数差值。
lastDirectionChangeTime 是一个 QTime 类型的对象,用于记录蛇上一次改变方向的时间。
isValid() 是 QTime 类的一个成员函数,用于检查该 QTime 对象是否包含一个有效的时间值。