首页 > 解决方案 > 如何限制子弹射击

问题描述

这是我的代码。这是一个发射子弹直到没有子弹的程序。

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 方面不是特别有经验。

标签: pythontkinter

解决方案


请提供更多上下文。但这里有一个提示

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")

推荐阅读