python - 如何限制子弹射击
问题描述
这是我的代码。这是一个发射子弹直到没有子弹的程序。
from tkinter import *
from time import sleep
import random
class Ball:
def __init__(self, canvas, color, size, x, y, xspeed, yspeed):
self.canvas = canvas
self.color = color
self.size = size
self.x = x
self.y = y
self.xspeed = xspeed
self.yspeed = yspeed
self.id=canvas.create_oval(x,y,x+size,y+size,fill=color)
def move(self):
self.canvas.move(self.id, self.xspeed, self.yspeed)
(x1, y1, x2, y2)=self.canvas.coords(self.id)
(self.x, self.y)=(x1, y1)
if x1<=0 or x2>=WIDTH:
self.xspeed=-self.xspeed
if y1<=0 or y2>=HEIGHT:
self.yspeed=-self.yspeed
WIDTH=800
HEIGHT=400
bullets=[]
def fire(event):
bullets.append(Ball(canvas, 10, "red", 100, 200, 10, 0))
window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT)
canvas.pack()
canvas.bind("<Button-1>", fire)
spaceship = Ball(canvas, "green", 100, 100, 200, 0, 0)
enemy = Ball(canvas, "red", 100, 500, 200, 0, 5)
while True:
for bullet in bullets:
bullet.move()
if (bullet.x+bullet.size) >= WIDTH:
canvas.delete(bullet.id)
bullets.remove(bullet)
if (bullet_count<9):
bullet_count+=1
else:
id=canvas.create_text(100,50, fill="red",font="Times 30 italic
bold",text="Hello World")
break
enemy.move()
window.update()
sleep(0.03)
我只想发射 10 颗子弹,如果没有剩余子弹,我想创建一个消息框,如id = canvas.create_text(100, 50, fill="red",font="Times 30 italic bold",text="Out of bullets")
.
我怎样才能实现这个目标?我在 Python 方面不是特别有经验。
解决方案
请提供更多上下文。但这里有一个提示
for bullet in bullets[:10]:
# we try to fire 10 bullets
# if we have less bullets we fire them
# but we have more, here we only fire 10 of them
bullet.move()
if (bullet.x+bullet.size) >= WIDTH:
canvas.delete(bullet.id)
bullets.remove(bullet)
# If we had less bullets and we fired less than 10 bullets
if len(bullets) <= 0:
id = canvas.create_text(100, 50, fill="red", font="Times 30 italicbold",text="you have less than 10 bullets")
推荐阅读
- php - 将月份拆分为 4 并检索每天的平均值
- javascript - 动态更改html表中的值
- neo4j - neo4j 可以返回节点的某些属性并在图中表示吗?
- java - 编译错误:com.google.gson.Gson 类型没有可用的源代码
- sql-server - SQL Server Data Tools 2017 for Visual Studio 2017 - 无法启动调试器错误
- intellij-idea - 如何在 IntelliJ IDEA 中保留搜索结果
- c# - Service Fabric 参与者:使用最新版本的 Service Fabric nuget 包部署参与者时出现的问题
- java - 突出显示特定行 JTable
- listview - 如何在列表视图中呈现多个自定义行 - Reactnative
- android - firebase 回收器适配器显示空指针异常