如何在我的乌龟程序中添加倒数计时器?

时间:2018-06-07 13:22:31

标签: python python-3.x

我尝试使用乌龟制作游戏,玩家必须在一定时间内点击随机分布的圈数,但我很难知道如何在游戏中创建计时器。每当我尝试设置计时器时,它会在游戏开始前倒计时或在1个圆圈产生后倒计时。我希望在游戏开始时让它倒计时,并在计时器结束后让游戏结束。

我也试图创建一个分数计数器,但是我使用circle.onclick错了吗?

这就是我一直在尝试做的事情:

1,2,3,4,5,6,7

我最不感兴趣的是,是否可以在游戏中打印计时器和得分,而不是在Python Shell上。

1 个答案:

答案 0 :(得分:0)

我做了一些改动,这似乎有效。我已将得分和时间留在游戏的标题栏中。谢谢

import turtle
from random import random, randint
import time

CURSOR_SIZE = 20

num=0
def increase_score():
    global num 
    num += 1

def my_circle(color):

    radius = randint(10, 50)

    circle = turtle.Turtle('circle', visible=False)
    circle.shapesize(radius / CURSOR_SIZE)
    circle.color(color)
    circle.penup()

    while True:
        nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
        ny = randint(2 * radius - height // 2, height // 2 - radius * 2)

        circle.goto(nx, ny)

        for other_radius, other_circle in circles:
            if circle.distance(other_circle) < 2 * max(radius, other_radius):
                break
        else:
            break

    circle.showturtle()
    circle.onclick(lambda x,y,t=circle: (circle.hideturtle(), increase_score()))

    return radius, circle


screen = turtle.Screen()
screen.bgcolor("lightgreen")
screen.title("Speed Clicker")

width, height = screen.window_width(), screen.window_height()

circles = []

gameLength = 5
# Higher number means faster blocks
# 1-10
difficulty = 10
startTime = time.time()
while True:
    time.sleep(1/difficulty)

    rgb = (random(), random(), random())

    timeTaken = time.time() - startTime

    circles.append(my_circle(rgb))
    screen.title('SCORE: {}, TIME LEFT: {}'.format(num,int(round(gameLength - timeTaken,0))))

    if time.time() - startTime > gameLength: 
        break

screen.title('FINISHED! FINAL SCORE: {}'.format(num))

screen.mainloop()