Python龟模块

64jmpszr  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(131)

我现在是python编程的新手。现在我正在用turtle模块构建一个snake游戏。我想在snake对象的每一部分移动后刷新屏幕。所以我关闭了tracer,并在for循环后使用update函数。
但要做到这一点,我必须导入time模块并使用time.sleep()函数。如果我不使用它,python turtle模块开始没有响应。我想知道为什么我必须使用time函数,为什么我不能直接使用sc.update而不使用time函数。
这是我代码

from turtle import *
from snake import *
import time

sc = Screen()
sc.bgcolor('black')
sc.setup(width=600, height=600)
sc.tracer(0)

# diyego is our snake name
diyego = Snake(10)

run = 1
while run:
#here is the problem 
    sc.update()
    time.sleep(1) #used time.sleep
    for i in range(len(diyego.snake_object_list)-1, 0, -1):
        infront_item_position = diyego.snake_object_list[i - 1].pos()
        diyego.snake_object_list[i].goto(infront_item_position)

    diyego.snake_head.forward(10)

sc.exitonclick()



#Snake module

from turtle import *

class Snake():
    def __init__(self, number_of_parts):
        """Should pass the lenght of snake"""
        self.snake_object_list = []
        self.create_snake_parts(number_of_parts)
        self.snake_head = self.snake_object_list[0]

    def create_snake_parts(self, number_of_parts):
        """ Get number of parts which snake shuld have and create snake it"""
        x_cor = 0
        for i in range(number_of_parts):
            snake = Turtle()
            snake.speed(0)
            snake.shape("circle")
            snake.color('white')
            snake.penup()
            snake.setx(x=x_cor)
            self.snake_object_list.append(snake)
            x_cor += -20

我只是想知道为什么乌龟没有React,当我删除的时间。sleep()

3pvhb19x

3pvhb19x1#

你所描述的是可能的,但问题不在于缺少sleep()函数的使用,而是你(有效地)使用了while True:,它在turtle这样的事件驱动世界中是没有位置的。让我们使用ontimer()事件重新编写代码,使snake的基本运动成为snake本身的一种方法:

from turtle import Screen, Turtle

CURSOR_SIZE = 20

class Snake():
    def __init__(self, number_of_parts):
        """ Should pass the length of snake """
        self.snake_parts = []
        self.create_snake_parts(number_of_parts)
        self.snake_head = self.snake_parts[0]

    def create_snake_parts(self, number_of_parts):
        """ Get number of parts which snake should have and create snake """
        x_coordinate = 0

        for _ in range(number_of_parts):
            part = Turtle()
            part.shape('circle')
            part.color('white')
            part.penup()
            part.setx(x_coordinate)

            self.snake_parts.append(part)
            x_coordinate -= CURSOR_SIZE

    def move(self):
        for i in range(len(self.snake_parts) - 1, 0, -1):
            infront_item_position = self.snake_parts[i - 1].position()
            self.snake_parts[i].setposition(infront_item_position)

        self.snake_head.forward(CURSOR_SIZE)

def slither():
    diyego.move()
    screen.update()
    screen.ontimer(slither, 100)  # milliseconds

screen = Screen()
screen.bgcolor('black')
screen.setup(width=600, height=600)
screen.tracer(0)

diyego = Snake(10)

slither()

screen.exitonclick()

相关问题