我在pygame中做了一个非常非常基本的游戏,其中唯一可能的动作是向左移动,向右移动并向上射击子弹。我的问题是,当我射击时,我的球员精灵在子弹向上移动时保持不动。我该如何补救?我对pygame很陌生,所以我会很感激任何和所有的帮助。我需要精灵在射击子弹后继续移动
#importing needed libraries
import pygame,sys
from pygame.locals import *
#Class for the Player
class Player():
def __init__(self,surf,xpos,ypos):
self.image=pygame.image.load("cat1.png").convert_alpha()
self.x=xpos
self.y=ypos
self.surface=surf
def keys(self):
dist=10
key=pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
if self.x<500:
self.x+=dist
elif key[pygame.K_LEFT]:
if self.x!=0:
self.x-=dist
def draw(self,surface):
self.surface.blit(self.image,(self.x,self.y))
#Class for the bullet which inherits the Player Class
class Weapon(Player):
def __init__(self,surf,xpos,ypos,bg,wxpos,wypos):
Player.__init__(self,surf,xpos,ypos)
self.wimage=pygame.image.load("bullet.png").convert_alpha()
self.wx=wxpos
self.wy=wypos
self.background=bg
def Shoot(self):
dist=10
while self.wy>0:
self.surface.blit(self.background,(0,0))
self.surface.blit(self.image,(self.x,self.y))
self.surface.blit(self.wimage,(self.wx,self.wy))
self.wy-=dist
pygame.display.update()
#initialising pygame
pygame.init()
FPS=30
fpsClock=pygame.time.Clock()
#creating display window
DISPLAYSURF=pygame.display.set_mode((577,472),0,32)
pygame.display.set_caption('Animation')
WHITE = (255, 255, 255)
background=pygame.image.load("background.png")
DISPLAYSURF.fill(WHITE)
#creating player
player=Player(DISPLAYSURF,50,360)
#main game loop
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==MOUSEBUTTONDOWN:
weapon=Weapon(DISPLAYSURF,player.x,player.y,background,player.x+25,player.y)
player.draw(DISPLAYSURF)
weapon.Shoot()
player.keys()
DISPLAYSURF.blit(background,(0,0))
player.draw(DISPLAYSURF)
pygame.display.update()
fpsClock.tick(FPS)
没有详细说明在这里做这样的方式,但你需要使用一个线程或子程序。基本上,你想要的是有许多对象同时运行,所以你需要并行化他们的行为。 –
你不能在'Shoot'中使用'while'循环。你必须在'while True'(主循环)内移动它。 – furas
'射击'必须是类 - 类似于玩家 - 使用'draw()'来显示和'更新()'在主循环的每个循环中只移动几个像素。 Mainloop会做所有的工作。 – furas