首页 > 解决方案 > 如何在我可以按空格键重新射击子弹之前添加延迟,这样我就不会偶尔出现故障,如果子弹不走的话

问题描述

我正在尝试学习如何在 python 中编码,这是我自己创建的太空入侵者。它工作正常,除了当我过早按下空格键时,子弹出现并且不移动。

我试过给子弹一个不起作用的状态(见代码),这是我能做的最好的,我考虑过添加延迟,但我不知道该怎么做。

import turtle
import os

bullet = turtle.Turtle()
bullet.color("blue")
bullet.shape("circle")
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5,0.5)
bullet.hideturtle()

bulletspeed = 25

bulletstate = "ready"

def fire_bullet():
    global bulletstate
    if bulletstate == "ready":
        bulletstate = "fire"
        x = player.xcor()
        y = player.ycor() +15
        bullet.setpos(x, y)
        bullet.showturtle()
turtle.listen():
     turtle.onkeypress(fire_bullet, 'space')

while True:
     if bulletstate == "fire":
        y = bullet.ycor()
        y += bulletspeed
        bullet.sety(y)

    #border bullet check
    if bullet.ycor() > 275:
        bullet.hideturtle()
        bulletstate = "ready"

标签: python

解决方案


您可以使用模块为任何函数添加延迟timetime.sleep(5)其中 5 是延迟的秒数。我不明白您具体希望在哪里延迟,但您可以在time.sleep()任何地方添加延迟特定操作。如果您正在创建一个游戏,其中(距离)存在bulletspeed变化,y您可以使用time.sleep(y/bulletspeed)(假设它们都以相同的值表示)将您的动作延迟到子弹(给定一定的速度)到覆盖那个距离(y的变化)

import turtle
import os
import time

bullet = turtle.Turtle()
bullet.color("blue")
bullet.shape("circle")
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5,0.5)
bullet.hideturtle()

bulletspeed = 25

bulletstate = "ready"

def fire_bullet():
    global bulletstate
    if bulletstate == "ready":
        bulletstate = "fire"
        x = player.xcor()
        y = player.ycor() +15
        bullet.setpos(x, y)
        bullet.showturtle()
turtle.listen():
     turtle.onkeypress(fire_bullet, 'space')

while True:
     if bulletstate == "fire":
        y = bullet.ycor()
        y += bulletspeed
        time.sleep(2) #This means it'll take 2 seconds since y has defined to apply the next function. You can also try a combination of time and speed so you can measure distance for instance: time.sleep(bulletspeed/y). 
        bullet.sety(y)

    #border bullet check
    if bullet.ycor() > 275:
        bullet.hideturtle()
        bulletstate = "ready"

推荐阅读