【发布时间】:2016-11-10 02:44:21
【问题描述】:
我在 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(主循环)中。 -
Shoot必须是类 - 类似于 Player - 显示draw()和update()在主循环的每个循环中仅移动几个像素。 Mainloop 将完成所有工作。
标签: python python-2.7 pygame