Python 在游戏中射击子弹
我正在制作自己的太空入侵者游戏,到目前为止,我已经能够用鼠标移动我的飞船。不过,我还是不会开枪。这是我的游戏循环Python 在游戏中射击子弹,python,python-3.x,pygame,Python,Python 3.x,Pygame,我正在制作自己的太空入侵者游戏,到目前为止,我已经能够用鼠标移动我的飞船。不过,我还是不会开枪。这是我的游戏循环 def game_loop(): x=0 y=0 xlist=[] ylist=[] while True: mouseclk=pygame.mouse.get_pressed() game_display.fill(white) for event in pygame.event.ge
def game_loop():
x=0
y=0
xlist=[]
ylist=[]
while True:
mouseclk=pygame.mouse.get_pressed()
game_display.fill(white)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
quit()
x, y = pygame.mouse.get_pos()
xlist.append(x)
ylist.append(y)
if x>=display_width-40:
x=display_width-40
if y>=display_height-48:
y=display_height-48
if pygame.mouse.get_focused()==0:
game_display.blit(spaceship, (x, y))
elif pygame.mouse.get_focused()==1:
game_display.blit(spaceshipflames, (x, y))
pygame.display.update()
if pygame.mouse.get_focused()==0:
pause()
clock.tick(500)
我尝试在游戏循环中使用以下代码:
if mouseclk[0]==1:
shoot.play()
while True:
pygame.draw.circle(game_display, white, (x+20, y-2), 5)
pygame.draw.circle(game_display, red, (x+20, y-7), 5)
y-=5
if y<=0:
break
pygame.display.update()
clock.tick(400)
for bullet in bullets:
bullet.move()
如果mouseclk[0]==1:
射击,玩耍
尽管如此:
pygame.draw.circle(游戏显示,白色,(x+20,y-2),5)
pygame.draw.circle(游戏显示,红色,(x+20,y-7),5)
y-=5
如果y我建议使用类(特别是游戏类),并将代码拆分成更小的函数
在制作游戏时,每个类都应该代表游戏中的某种类型的对象,例如一艘船或一颗子弹。使用类应该有助于解决多个项目符号导致故障的问题
分解成更小的函数将使代码更易于阅读和更新。尽可能多地坚持正确的方向
考虑到以下几点,您可以如何实施拍摄:
bullets = []
class Bullet:
def __init__(self, position, speed):
self.position = position
self.speed = speed
def move(self):
self.position[1] += self.speed
class Ship:
def __init__(self, position, bullet_speed):
self.position = position
self.bullet_speed = bullet_speed
def shoot(self):
new_bullet = Bullet(self.position, self.bullet_speed)
bullets.append(new_bullet)
其中位置
变量的形式为[x,y]
。然后,要向前移动子弹,请在游戏主循环中的某个位置放置这条线:
if mouseclk[0]==1:
shoot.play()
while True:
pygame.draw.circle(game_display, white, (x+20, y-2), 5)
pygame.draw.circle(game_display, red, (x+20, y-7), 5)
y-=5
if y<=0:
break
pygame.display.update()
clock.tick(400)
for bullet in bullets:
bullet.move()
循环所有项目符号并将每个项目符号绘制到屏幕以渲染它们
这不是最详细的示例,但希望它足以让您朝着正确的方向前进。您在哪里定义了shot
?您需要发布一个完全可复制的示例。现在,任何人都可以猜测你的代码实际上是如何构造的,但是他们无法指出问题所在。在这段代码中,可能存在重复的代码,你在哪里将子弹画到屏幕上?我没有为此编写方法,但我的建议是,每个类都有一个draw
方法,然后在主循环的每次迭代中,对每个对象调用draw,就像我在每个项目符号上调用move
一样。