python - 到达边界时如何重置位置
问题描述
我想做的是让蛇(因为我在做蛇游戏)在到达边界时重置它的位置。但是使用我的代码,当蛇到达边界时,它的位置不会重置,它只会越过边界。
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x * gridsize))), (cur[1] + (y * gridsize)))
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
screen_width = 520
screen_height = 520
gridsize = 20
grid_width = screen_width / gridsize
grid_height = screen_height / gridsize
任何帮助将不胜感激!,(如果我回复晚了对不起,很可能是因为我睡着了)
解决方案
您只需要测试蛇是否在网格中并调用reset()
:
grid_x = new[0] // gridsize
grid_y = new[1] // gridsize
if not (0 <= grid_x < grid_width and 0 <= grid_y < grid_height):
self.reset()
推荐阅读
- python - 循环遍历 NumPy 3D 数组的向量化代码
- mysql - 在 INSERT 上搜索和更新
- docker - Docker for Mac `docker images` 命令返回“致命错误:故障”
- r - 从并行循环内部将文本附加到现有文件
- c# - 文本到语音 C#
- django - 警告:Django_mysql.w001
- phpunit - SilverStripe 4:FunctionalTest “get” 方法返回 404 状态,尽管页面在那里。
- javascript - 将我的脚本移动到外部页面,它们不再响应
- javascript - Textarea.value 不操纵 HTML
- ansible - 使用 ansible 将文件从远程主机复制到 vagrant 实例