Почему говорится, что мой основной цикл недоступен? - PullRequest
0 голосов
/ 26 октября 2019
import turtle 
import time

delay = 0.1

ms = turtle.Screen() 
ms.title("hungry snake Game by @Rafa") 
ms.bgcolor("green") 
ms.setup(width=600, height=600)
ms.tracer(0)

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

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)


# main game loop

while True:
    ms.update()
    move()

    time.sleep(delay)

//Here is where am having trouble with the code?

ms.mainloop()

1 Ответ

0 голосов
/ 26 октября 2019

Настоящей ошибкой здесь является использование while True: и sleep() в управляемой событиями среде, такой как черепаха. Мы можем заменить бесконечный цикл и time.sleep() методом черепахи ontimer():

from turtle import Screen, Turtle

DELAY = 100  # milliseconds

def move():
    if direction == 'up':
        y = turtle.ycor()
        turtle.sety(y + 20)
    elif direction == 'down':
        y = turtle.ycor()
        turtle.sety(y - 20)
    elif direction == 'left':
        x = turtle.xcor()
        turtle.setx(x - 20)
    elif direction == 'right':
        x = turtle.xcor()
        turtle.setx(x + 20)

    screen.update()
    screen.ontimer(move, DELAY)

def up():
    global direction
    direction = 'up'

def down():
    global direction
    direction = 'down'

def left():
    global direction
    direction = 'left'

def right():
    global direction
    direction = 'right'

screen = Screen()
screen.title("Hungry Snake Game")
screen.bgcolor('green')
screen.setup(width=600, height=600)
screen.tracer(0)

turtle = Turtle()
turtle.shape('square')
turtle.speed('fastest')
turtle.penup()

direction = 'stop'

screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()

# main game loop

move()

screen.mainloop()
...