这段代码大部分都能用,但当我按下空格键时,子弹应该会发射并跟随外星人一起移动。相反,子弹会移动,外星人只是停在它的轨迹上,就像在shoot()函数启动时enemy_move()函数已经停止一样。如果你知道如何让它们同时工作,那就太好了。
bulletState = TRUE
bulletHealth = 0
enemyHealth = 100
def SpaceInvaders():
window.destroy()
SpaInv=Tk()
s = Canvas(SpaInv, height=HEIGHT, width=WIDTH, bg='black')
s.pack()
ship = s.create_polygon(590, 485, 630, 485, 610, 430, fill='red')
bullet = s.create_oval(600, 425, 620, 400, fill='yellow', state=HIDDEN)
enemy = s.create_rectangle(4, 4, 34, 34, fill = 'green')
def enemy_move():
global enemyHealth
while enemyHealth > 0:
pos = s.coords(enemy)
s.move(enemy, 3, 0)
time.sleep(0.01)
SpaInv.update()
def shoot(event):
global bulletHealth
global WIDTH
global bulletState
s.itemconfig(bullet, state=NORMAL)
bulletState = FALSE
while bulletHealth == 0:
s.move(bullet, 0, -3)
time.sleep(0.01)
SpaInv.update()
s.bind_all('<Key>', move_ship)
s.bind_all('<space>', shoot)
enemy_move()发布于 2019-04-05 05:05:43
下面是你的示例代码的高度简化的修改,允许外星人和子弹同时移动。解决方案不是编写一个循环来完成整个移动,而是编写一个函数来完成一小部分移动,然后通过after()调用自身
from tkinter import *
WIDTH, HEIGHT = 900, 600
def enemy_move():
s.move(enemy, 3, 0)
SpaInv.after(10, enemy_move)
def shoot(event=None):
s.itemconfig(bullet, state=NORMAL)
s.move(bullet, 0, -3)
SpaInv.after(10, shoot)
SpaInv = Tk()
s = Canvas(SpaInv, height=HEIGHT, width=WIDTH, bg='black')
s.pack()
ship = s.create_polygon(590, 485, 630, 485, 610, 430, fill='red')
bullet = s.create_oval(600, 425, 620, 400, fill='yellow', state=HIDDEN)
enemy = s.create_rectangle(4, 4, 34, 34, fill='green')
s.bind_all('<space>', shoot)
enemy_move()
SpaInv.mainloop()https://stackoverflow.com/questions/55518167
复制相似问题