乌龟图形问题

问题描述

我试图使用海龟图形制作类似于蛇的游戏。 我添加了 wn.update 行,但每次它只是说错误,如果我删除它,它就会崩溃。 有人知道为什么吗?

我在 python 方面很笨,所以我可能犯了一个非常愚蠢的错误

import turtle
import random

score = 0

def go_up():
    if cat.direction != "down":
        cat.direction = "up"

def go_down():
    if cat.direction != "up":
        cat.direction = "down"

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

def go_right():
    if cat.direction != "left":
        cat.direction = "right"

def move():
    if cat.direction == "up":
        y = cat.ycor()
        cat.sety(y + 20)

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

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

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

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

mouse=turtle.Turtle()
mouse.penup()
mouse.goto(0,100)

cat = turtle.Turtle()
cat.penup()

while True:
    wn.update()
    if cat.distance(mouse) < 20:
        x = random.randint(0,500)
        y = random.randint(0,500)
        mouse.goto(x,y)

wn.onkeypress(go_up,"w")
wn.onkeypress(go_down,"s")
wn.onkeypress(go_left,"a")
wn.onkeypress(go_right,"d")
wn.listen()

wn.mainloop()

解决方法

您的程序结构不正确。您不应该在事件驱动的想乌龟中使用 while True:。 (尤其是在您需要执行的附加语句之前!)在您的程序基本正常工作之前,您不应该实现 tracer()update()。这是“可玩”的代码的返工:

from turtle import Screen,Turtle
from random import randint

CURSOR_SIZE = 20

def go_up():
    if cat.direction != 'down':
        cat.direction = 'up'
        cat.setheading(90)
        screen.update()

def go_down():
    if cat.direction != 'up':
        cat.direction = 'down'
        cat.setheading(270)
        screen.update()

def go_left():
    if cat.direction != 'right':
        cat.direction = 'left'
        cat.setheading(180)
        screen.update()

def go_right():
    if cat.direction != 'left':
        cat.direction = 'right'
        cat.setheading(0)
        screen.update()

def move():
    cat.forward(20)

    if cat.distance(mouse) < CURSOR_SIZE:
        x = randint(CURSOR_SIZE - 300,300 - CURSOR_SIZE)
        y = randint(CURSOR_SIZE - 300,300 - CURSOR_SIZE)
        mouse.goto(x,y)

    screen.update()

    screen.ontimer(move,200)  # 1/5 second delay in milliseconds

screen = Screen()
screen.setup(width=600,height=600)
screen.tracer(False)

mouse = Turtle('turtle')
mouse.penup()
mouse.sety(100)

cat = Turtle('arrow')
cat.penup()
cat.direction = 'right'  # user defined property

screen.onkeypress(go_up,'w')
screen.onkeypress(go_down,'s')
screen.onkeypress(go_left,'a')
screen.onkeypress(go_right,'d')
screen.listen()

move()

screen.mainloop()