【问题标题】:Snake Head Isn't Moving [closed]蛇头不动[关闭]
【发布时间】:2021-07-12 14:46:33
【问题描述】:

我在 Python 中的海龟模块中编写了一个基本的蛇游戏,当我测试它时,我看到蛇头没有移动。

代码如下:

导入模块:

import turtle
import random
import time
delay=0.1

# Background

win = turtle.Screen()
win.title("snake")
win.bgcolor("black")
win.setup(width=800, height=800)
win.tracer(0)

我测试了它并且它工作,所以我移动到蛇头上:

# snake head

head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 50)
head.direction = "stop"

移动蛇头:

# snake movement

def move():

    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)

    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)

# keyboard setting


def go_up():

    if head.direction != "down":
        head.direction = "up"


def go_down():

    if head.direction != "up":
        head.direction = "down"


def go_right():

    if head.direction != "left":
        head.direction = "right"


def go_left():
    if head.direction != "right":
        head.direction = "left"

主游戏循环:

# main game loop
while True:
    win.update()
    move()
    time.sleep(delay)

和键盘绑定:

# keyboard binding

win.listen()
win.onkey(go_up, "w")
win.onkey(go_down, "s")
win.onkey(go_right, "d")
win.onkey(go_left, "a")

另外,我在win.listen() 行中有一个错误,说“此代码无法访问”,如果有人知道我做错了什么,请告诉我。

【问题讨论】:

    标签: python pycharm python-turtle


    【解决方案1】:

    它说代码无法访问的原因是因为键绑定的东西,包括window.listen,在while True: 循环之后。由于您没有任何方法可以退出循环,因此之后的代码将永远不会运行。如果没有任何键绑定,则蛇永远不会从"stop" 方向改变。

    您应该将主游戏循环移动到代码的最后,以便其他所有内容都有机会运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2018-05-08
      • 2015-06-30
      • 2021-08-11
      • 2013-11-27
      • 1970-01-01
      相关资源
      最近更新 更多