导入pyplay
屏幕=pygame.display.set_mode(((800,600))
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, rect):
pygame.sprite.Sprite.__init__(self)
self.speed = 10
self.image = bullet
self.rect = rect
self.rect.center = (x, y)
self.direction = direction
bullet_group=pygame。(传说中的)精灵组()
游戏运行时:
clock.tick(FPS)
draw_bg()
enemy.draw()
enemy.update_animation()
player.update_animation()
player.draw()
player.move(move_left, move_right)
bullet_group.update()
bullet_group.draw(screen)
if player.alive:
if shoot:
bullet = Bullet(player.rect.centerx, player.rect.centery, player.direction, bullerRect)
bullet_group.add(bullet)
if player.in_air:
player.update_action(2)
elif move_right or move_left:
player.update_action(1)# 1 is run
else:
player.update_action(0)# 0 is idle
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameRun = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
move_left = True
if event.key == pygame.K_d:
move_right = True
if event.key == pygame.K_SPACE:
shoot = True
if event.key == pygame.K_w and player.alive:
player.jump = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
move_left = False
if event.key == pygame.K_d:
move_right = False
if event.key == pygame.K_SPACE:
shoot = False
pygame.display.update()
错误:
Traceback(最近的调用最后):
文件“c:\Users\gopal\Desktop\Misc Projects\main.py”,第136行,在
bullet_group.draw(SCREEN)
文件“C:\Users\gopal\AppData\Local\Programs\Python\39\lib\site packages\pygame\sprite.py”,第546行,在绘图中
surface.blits((spr.image, spr.rect) for spr in sprites)
TypeError:源对象必须是曲面
您已多次使用名称bullet
,但用于不同的用途。一开始它是一个pygame。曲面
对象,但在添加第一个项目符号后,
bullet = Bullet(player.rect.centerx, player.rect.centery, player.direction, bullerRect)
它引用了一个项目符号
对象。重命名变量。
对表示项目符号的图像使用名称bullet_surf
:
bullet_surf = pygame.image.load(...)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction, rect):
pygame.sprite.Sprite.__init__(self)
self.speed = 10
self.image = bullet_surf
使用空格键发射子弹参见: