Python Turtle实现贪吃蛇游戏穿墙异常 求代码错误排查
问题定位
你遇到的穿墙问题是代码逻辑主动实现的效果,与Python版本、库兼容性无关。
主循环中存在如下边界处理代码,正是穿墙的触发逻辑:
if head.xcor()>290: head.setx(-290) if head.ycor()>290: head.sety(-290) if head.ycor()<-290: head.sety(290) if head.xcor()<-290: head.setx(290)
这段代码的作用是蛇头超出窗口边界时,直接将其移动到对侧边界位置,就会出现穿墙效果。
修复方法
将上述代码块替换为撞边界死亡逻辑即可,参考实现如下:
# 撞边界判定逻辑 if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: time.sleep(1) head.goto(0, 0) head.direction = "stop" # 清理所有蛇身 for body in bodies: body.goto(1000, 1000) bodies.clear() # 重置状态 score = 0 delay = 0.1 sb.clear() sb.write("Score:{} Highest Score: {}".format(score, highestscore))
额外存在的隐藏bug
你当前生成食物的代码中random.randint(290,-290)参数顺序错误,randint要求第一个参数为最小值、第二个为最大值,顺序错误会导致运行报错,需要修改为random.randint(-290, 290)。
内容的提问来源于stack exchange,提问作者HaRrY
相关产品推荐
相关产品推荐

