如何在Python Tkinter射击程序中限制最多发射10发子弹
实现限制最多10发子弹的修改方案
你原有代码存在2个核心问题:
- 没有初始化子弹计数变量,且fire函数没有做发射数量限制
- fire函数中Ball类实例化的参数顺序传反,将size和color参数倒置,会直接导致运行报错
以下是修改后的完整可运行代码:
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=[] # 新增:剩余可发射子弹数,初始为10 bullet_remaining = 10 # 新增:存储缺弹提示文本的id,避免重复生成 out_of_ammo_text = None def fire(event): global bullet_remaining, out_of_ammo_text # 剩余子弹大于0才能发射 if bullet_remaining > 0: # 修正了参数顺序:原来把color和size传反了 bullets.append(Ball(canvas, "red", 10, 100, 200, 10, 0)) bullet_remaining -= 1 # 子弹打光时显示提示 if bullet_remaining == 0: out_of_ammo_text = canvas.create_text(100, 50, fill="red",font="Times 30 italic bold",text="Out of bullets") 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) enemy.move() window.update() sleep(0.03)
核心修改说明
- 新增了
bullet_remaining全局变量记录剩余可发射子弹数量,初始值设置为10 - 新增
out_of_ammo_text变量存储提示文本的id,避免每次点击都重复生成提示 - 修正了
fire函数中Ball类的参数顺序错误,将color和size参数调整为符合类定义的顺序 - 在
fire函数中增加发射限制:只有剩余子弹数大于0时才允许创建子弹实例,每次发射后剩余子弹数减1,减到0时自动生成缺弹提示
内容的提问来源于stack exchange,提问作者이정모
相关产品推荐
相关产品推荐

