【问题标题】:Snake game in python Turtle.update() causes problemspython Turtle.update() 中的蛇游戏导致问题
【发布时间】:2021-10-27 13:12:28
【问题描述】:

所以我试图使用 python 创建一个蛇游戏,但我似乎收到了这个错误消息

Traceback (most recent call last):   
File "C:\Users\user\source\repos\PythonApplication1\PythonApplication1\PythonApplication1.py", line 85, in <module>
    wn.update()   
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\turtle.py", line 1304, in update
    t._update_data()   
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\turtle.py", line 2647, in _update_data
    self.screen._incrementudc()   
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\turtle.py", line 1293, in _incrementudc
    raise Terminator turtle.Terminator

我尝试了一些我在网上看到的解决方案,但都没有奏效

import turtle
import time
import random

delay = 0.1
score = 0

wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")

wn.setup(width=600 ,height=600)
wn.tracer(0)

#HEAD
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"
#FOOD
food = turtle.Turtle()
colors = random.choice(['red','green','black'])
shapes = random.choice(['square','triangle','circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0,100)



pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,250)
pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))


def goup():
    if head.direction !="down":
        head.direction = "up"

def godown():
    if head.direction !="up":
        head.direction ="down"

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

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

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 == "left":
        x = head.xcor()
        head.setx(x-20)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x+20)


wn.listen()
wn.onkeypress(goup,"w")
wn.onkeypress(godown,"s")
wn.onkeypress(goleft,"a")
wn.onkeypress(goright,"d")

segments = []

#Main Gameplay
while True:
    wn.update()
    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"
        colors = random.choice(['red','blue','green'])
        shapes = random.choice(['square','circle'])
        for segment in segments:
            segments.goto(1000,1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))
    if head.distance(food)<20:
        x = random.randint(-270,270)
        y = random.randint(-270,270)

        #Adding segments
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("orange")
        new_segment.penup()
        segments.append(new_segment)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))

        for index in range(len(segments)-1,0,-1):
            x = segments[index-1].xcor()
            y = segments[index-1].ycor()
            segments[index].goto(x,y)
        if len(segments) > 0:
            x = head.xcor()
            y = head.ycor()
            segments[0].goto(x,y)
        move()
        for segment in segments:
            if segment.distance(head) < 20:
                time.sleep(1)
                head.goto(0,0)
                head.direction = "Stop"
                colors = random.choice(['red','blue','green'])
                shapes = random.choice(['square','circle'])
                for segment in segments:
                    segment.goto(1000,1000)
                segment.clear()

                score = 0 
                delay = 0.1
                pen.clear()
                pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))
        time.sleep(delay)

wn.mainloop()

【问题讨论】:

  • 只有当我用 Turtle 关闭窗口时才会出现这个问题。这是正常的,因为当我关闭窗口时它仍然运行while-loop 并且update() 尝试访问已经关闭的窗口。您必须添加侦听器来检查窗口是否关闭并停止while 循环。或者你应该使用ontimer 而不是while Truedelay - 当你关闭窗口时它可能会停止运行。

标签: python turtle-graphics


【解决方案1】:

编辑:

原始代码有错误的缩进,某些元素不起作用。


只有当我用 Turtle 关闭窗口时才会出现这个问题。这是正常行为,因为当我关闭窗口时,它仍然运行 while-loop 并且 wm.update() 尝试访问已经关闭的窗口。

需要指定关闭窗口时执行的函数,并且该函数应该停止while 循环。但这需要使用while running:running = True 并访问由tkinter 创建的root 窗口并将函数(将设置running = False)分配给"WM_DELETE_WINDOW"

# ... code ...

running = True

def on_closing():
    global running
    
    running = False
    #root.destroy()
    
canvas = turtle.getcanvas()
root = canvas.winfo_toplevel()
root.protocol("WM_DELETE_WINDOW", on_closing)

while running:
   # ...code...

完整的工作代码。

顺便说一句:如果您使用update() 运行自己的循环,则不需要mainloop

import turtle
import time
import random

delay = 0.1
score = 0

wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")

wn.setup(width=600 ,height=600)
wn.tracer(0)

#HEAD
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"
#FOOD
food = turtle.Turtle()
colors = random.choice(['red','green','black'])
shapes = random.choice(['square','triangle','circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0,100)



pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,250)
pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))


def goup():
    if head.direction !="down":
        head.direction = "up"

def godown():
    if head.direction !="up":
        head.direction ="down"

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

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

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 == "left":
        x = head.xcor()
        head.setx(x-20)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x+20)


wn.listen()
wn.onkeypress(goup,"w")
wn.onkeypress(godown,"s")
wn.onkeypress(goleft,"a")
wn.onkeypress(goright,"d")

segments = []

running = True

def on_closing():
    global running
    
    running = False
    root.destroy()
    
canvas = turtle.getcanvas()
root = canvas.winfo_toplevel()
root.protocol("WM_DELETE_WINDOW", on_closing)

#Main Gameplay
while running:
    wn.update()
    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"
        colors = random.choice(['red','blue','green'])
        shapes = random.choice(['square','circle'])
        for segment in segments:
            segments.goto(1000,1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))
    if head.distance(food)<20:
        x = random.randint(-270,270)
        y = random.randint(-270,270)

        #Adding segments
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("orange")
        new_segment.penup()
        segments.append(new_segment)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))

    # --- after `if` ---

    for index in range(len(segments)-1,0,-1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    move()
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0,0)
            head.direction = "Stop"
            colors = random.choice(['red','blue','green'])
            shapes = random.choice(['square','circle'])
            for segment in segments:
                segment.goto(1000,1000)
            segment.clear()

            score = 0 
            delay = 0.1
            pen.clear()
            pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))
    time.sleep(delay)

#wn.mainloop()

或者您应该使用ontimer(func, time) 而不是while-loop 和time.sleep() - 然后它应该在您关闭窗口时停止它

def gameloop():
    wn.update()
    # ... code without `while` and without `sleep`

    # run again 
    wn.ontimer(gameloop, 1000) # time in millisecons

# --- 

# run first time
wn.ontimer(gameloop, 1000) # time in millisecons

wn.mainloop()

顺便说一句:但它需要在gameloop 中使用global 来为全局变量而不是局部变量赋值。


完整代码

它需要mainloop(),它将运行gameloop() 1000 毫秒。

import turtle
import time
import random

delay = 0.1
score = 0

wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")

wn.setup(width=600 ,height=600)
wn.tracer(0)

#HEAD
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"
#FOOD
food = turtle.Turtle()
colors = random.choice(['red','green','black'])
shapes = random.choice(['square','triangle','circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0,100)



pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,250)
pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))


def goup():
    if head.direction !="down":
        head.direction = "up"

def godown():
    if head.direction !="up":
        head.direction ="down"

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

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

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 == "left":
        x = head.xcor()
        head.setx(x-20)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x+20)


wn.listen()
wn.onkeypress(goup,"w")
wn.onkeypress(godown,"s")
wn.onkeypress(goleft,"a")
wn.onkeypress(goright,"d")

segments = []

high_score = 0

def gameloop():
    global score
    global delay
    global high_score
    # ... etc. ...

    wn.update()

    if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
        head.goto(0,0)
        head.direction = "Stop"
        colors = random.choice(['red','blue','green'])
        shapes = random.choice(['square','circle'])
        for segment in segments:
            segments.goto(1000,1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score : 0 High Score : 0",align="center",font=("candara",24,"bold"))
    if head.distance(food)<20:
        x = random.randint(-270,270)
        y = random.randint(-270,270)

        #Adding segments
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("orange")
        new_segment.penup()
        segments.append(new_segment)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))

    # --- after `if` ---

    for index in range(len(segments)-1,0,-1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    move()
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0,0)
            head.direction = "Stop"
            colors = random.choice(['red','blue','green'])
            shapes = random.choice(['square','circle'])
            for segment in segments:
                segment.goto(1000,1000)
            segment.clear()

            score = 0 
            delay = 0.1
            pen.clear()
            pen.write("Score : {} High Score : {} ".format(score,high_score),align="center", font=("candara",24,"bold"))

    # run again 
    wn.ontimer(gameloop, 1000) # time in millisecons

# --- 

# run first time
wn.ontimer(gameloop, 1000) # time in millisecons

wn.mainloop()  # it needs `mainloop` 

【讨论】:

  • 它确实解决了我的问题,但现在游戏至少对我不起作用,我尝试按下按钮但它不起作用是我做错了什么吗?我感觉好傻xd
  • 即使使用您的原始代码,您的代码也对我不起作用 - 也许首先您应该使用 print() 来查看变量中的内容以及执行了哪部分代码。它被称为"print debuging"
  • 在带有ontimer 的版本中,我在gameloop 中忘记了第二个ontimer
  • 在检查代码后,我发现你在循环内有错误的缩进 - 你在 if 内有 for-loop 和 move() - 所以它只在某些情况下执行 - 但它应该在外面if 在每个循环中运行它。
猜你喜欢
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多