简体   繁体   English

我想在程序中添加倒数计时器

[英]I want to add a countdown timer to my program

So I am making a game in Python, and I am almost done, though I am stumped. 所以我正在用Python做游戏,尽管我很沮丧,但我差不多完成了。 There are a few things I want: 我想要一些东西:

  • I want to make a 30 second timer. 我想做一个30秒的计时器。 The player has 30 seconds to collect as many pellets as he/she can. 玩家有30秒的时间来收集自己尽可能多的小球。
  • Second, after the timer is complete, the turtle is not controllable anymore. 第二,计时器结束后,乌龟不再可控。

What do I need to do to fix these? 我需要怎么做才能解决这些问题?

Screen setup 屏幕设置

import turtle
import math
import random
#screen
wn=turtle.Screen()
wn.bgcolor("lightblue")
speed=1
wn.tracer(2)


#Score Variable
score=0
#Turtle Player
spaceship= turtle.Turtle()
spaceship.pensize(1)
spaceship.color("red")
spaceship.penup()
turtle.delay(3)
spaceship.shapesize(1,1)
add=1

#Create Goals
maxpoints = 6
points = []

for count in range(maxpoints):
    points.append(turtle.Turtle())
    points[count].color("green")
    points[count].shape("circle")
    points[count].penup()
    points[count].goto(random.randint(-300,300), random.randint(-200,200))

#Border
border = turtle.Turtle()
border.penup()
border.goto(-300,-200)
border.pendown()
border.pensize(5)
border.color("darkblue")
for side in range(2):
    border.forward(600)
    border.left(90)
    border.forward(400)
    border.left(90)



#Functions
def left():
    spaceship.left(30)
def right():
    spaceship.right(30)

def increasespeed():
    global speed
    speed += 1

def decreasespeed():
    global speed
    speed -= 1

def iscollision(turtle1,turtle2):
    collect = math.sqrt(math.pow(turtle1.xcor()-turtle2.xcor(),2)+ math.pow(turtle1.ycor()-turtle2.ycor(),2))
    if collect <20:
        return True
    else:
        return False

Keyboard binding to move turtle around 键盘绑定可移动乌龟

#Keyboard Bindings
turtle.listen()
turtle.onkey(left,"Left")
turtle.onkey(right,"Right")
turtle.onkey(increasespeed ,"Up")
turtle.onkey(decreasespeed ,"Down")
turtle.onkey(quit, "q")

pen=100
while True:
    spaceship.forward(speed)


#Boundary
if spaceship.xcor()>300 or spaceship.xcor()<-300:
    spaceship.left(180)

if spaceship.ycor()>200 or spaceship.ycor()<-200:
    spaceship.left(180)

#Point collection
for count in range(maxpoints):
    if iscollision(spaceship, points[count]):
        points[count].goto(random.randint(-300,300), random.randint(-200,200))
        score=score+1
        add+=1
        spaceship.shapesize(add)
        #Screen Score
        border.undo()
        border.penup()
        border.hideturtle()
        border.goto(-290,210)
        scorestring = "Score:%s" %score
        border.write(scorestring,False,align="left",font=("Arial",16,"normal"))

At the end of my program after the timer finishes, I want the turtle to stop moving; 计时器结束后,在程序结束时,我希望乌龟停止移动。 the user is unable to move the turtle. 用户无法移动乌龟。

I was going to give you some turtle ontimer() event code to handle your countdown but realized your code is not organized correctly to handle it. 我本来打算给您一些turtle ontimer()事件代码来处理您的倒数,但意识到您的代码没有正确组织以处理它。 Eg your infinite while True: loop potentially blocks some events from firing and it definately prevents your boundary and collision code from running. 例如, while True:循环中无限执行可能会阻止某些事件的触发,并最终阻止边界和碰撞代码运行。 Even if it didn't, your boundary and collision code are only setup to run once when they need to run on every spaceship movement. 即使没有,您的边界代码和碰撞代码也只需要在每次飞船运动中运行时设置一次即可运行。

I've reorganized your code around an ontimer() event to run the spaceship and another to run the countdown timer. 我已经围绕ontimer()事件重新组织了您的代码,以运行太空飞船,并另一个运行了倒数计时器。 I've fixed the boundary and collision code to basically work. 我已经修复了边界和碰撞代码,基本上可以正常工作了。 I've left out some features (eg spaceship.shapesize(add) ) to simplify this example: 我省略了一些功能(例如spaceship.shapesize(add) )以简化此示例:

from turtle import Turtle, Screen
import random

MAXIMUM_POINTS = 6
FONT = ('Arial', 16, 'normal')
WIDTH, HEIGHT = 600, 400

wn = Screen()
wn.bgcolor('lightblue')
# Score Variable
score = 0

# Turtle Player
spaceship = Turtle()
spaceship.color('red')
spaceship.penup()

speed = 1

# Border
border = Turtle(visible=False)
border.pensize(5)
border.color('darkblue')

border.penup()
border.goto(-WIDTH/2, -HEIGHT/2)
border.pendown()

for _ in range(2):
    border.forward(WIDTH)
    border.left(90)
    border.forward(HEIGHT)
    border.left(90)

border.penup()
border.goto(-WIDTH/2 + 10, HEIGHT/2 + 10)
border.write('Score: {}'.format(score), align='left', font=FONT)

# Create Goals
points = []

for _ in range(MAXIMUM_POINTS):
    goal = Turtle('circle')
    goal.color('green')
    goal.penup()
    goal.goto(random.randint(20 - WIDTH/2, WIDTH/2 - 20), \
        random.randint(20 - HEIGHT/2, HEIGHT/2 - 20))
    points.append(goal)

# Functions
def left():
    spaceship.left(30)

def right():
    spaceship.right(30)

def increasespeed():
    global speed
    speed += 1

def decreasespeed():
    global speed
    speed -= 1

def iscollision(turtle1, turtle2):
    return turtle1.distance(turtle2) < 20

# Keyboard Bindings
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')
wn.onkey(increasespeed, 'Up')
wn.onkey(decreasespeed, 'Down')
wn.onkey(wn.bye, 'q')

wn.listen()

timer = 30

def countdown():
    global timer

    timer -= 1

    if timer <= 0:  # time is up, disable user control
        wn.onkey(None, 'Left')
        wn.onkey(None, 'Right')
        wn.onkey(None, 'Up')
        wn.onkey(None, 'Down')
    else:
        wn.ontimer(countdown, 1000)  # one second from now

wn.ontimer(countdown, 1000)

def travel():
    global score

    spaceship.forward(speed)

    # Boundary
    if not -WIDTH/2 < spaceship.xcor() < WIDTH/2:
        spaceship.left(180)

    if not -HEIGHT/2 < spaceship.ycor() < HEIGHT/2:
        spaceship.left(180)

    # Point collection
    for count in range(MAXIMUM_POINTS):
        if iscollision(spaceship, points[count]):
            points[count].goto(random.randint(20 - WIDTH/2, WIDTH/2 - 20), \
                random.randint(20 - HEIGHT/2, HEIGHT/2 - 20))
            score += 1
            # Screen Score
            border.undo()
            border.write('Score: {}'.format(score), align='left', font=FONT)

    if timer:
        wn.ontimer(travel, 10)

travel()

wn.mainloop()

Another simple way that to implement this is to do the following: 实现此目的的另一种简单方法是执行以下操作:

  1. Add a variable that holds the timestamp for when the game was begun 添加一个变量,该变量保存游戏开始的时间戳
  2. Wrap the code that you want to respect the timeout inside of a while loop that runs while the difference between the current time and the the starting time is less than your time limit. 在当前时间和开始时间之间的时间差小于您的时间限制时,在运行的while循环内包装要考虑超时的代码。

For example: 例如:

import time
starting_time = time.time()
time_limit = 30

while (time.time() - starting_time) < time_limit:
     # YOUR GAME LOGIC HERE

Something that is helpful for me is using time.time() . 对我来说有用的是使用time.time() If you set a variable(say startTime ) to time.time() in the beginning of your code, you can then add an if in your main game loop. 如果在代码的开头将变量(例如startTime )设置为time.time() ,则可以在主游戏循环中添加if。 The if will check if enough time has passed. if将检查是否经过了足够的时间。 For example: 例如:

if time.time() > startTime + 30: #whatever you do to end the game

time.time() gives the current time in seconds, so if you set a variable to time.time() at the beginning of the code, that variable will give you the time that the game started. time.time()以秒为单位给出当前时间,因此,如果在代码开头将变量设置为time.time() ,则该变量将为您提供游戏开始的时间。 In the if , you check if the current time has reached the time your game started plus 30 seconds. if ,检查当前时间是否已达到游戏开始的时间加上30秒。

I hope this helped; 我希望这会有所帮助; if it did be sure to upvote! 如果确实可以投票! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM