python - 如何在我可以按空格键重新射击子弹之前添加延迟,这样我就不会偶尔出现故障,如果子弹不走的话
问题描述
我正在尝试学习如何在 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"
解决方案
您可以使用模块为任何函数添加延迟time
,time.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"
推荐阅读
- css - 我如何在引导卡标题中对齐
- python - 在另一个 XML 中包含一个 XML 并用 python 解析它
- excel - 将 Outlook Folder.items 分配给 Excel 中的对象时出现运行计时器错误“5”
- c# - 使用资源管理器序列化数据的另一种方法
- jmeter - 如何从使用未显示在响应数据中的随机数变量创建的会话代码中获取值
- reactjs - 材料表标题React中的Col span和Row span
- vaadin - 显示不同 UI 的选项卡 - Vaadin 14
- office365 - 如何获取“通用频道”中的信息?
- ios - 在 iOS13 Xamarin 中打开应用程序中的 URL/文件崩溃
- loopbackjs - 在 Loopback-4 e2e 测试中模拟任何服务