import pygame
screen=pygame.display.set_mode((800600((
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.sprite.group((
while gameRun:
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()
错误:
追踪(最近一次通话(:
文件";c: \Users\gopal\Desktop\Misc Projects\main.py";,第136行,在中
bullet_group.draw(SCREEN)
文件";C: \Users\gopal\AppData\Local\Programs\Python39\lib\site-packages\pygame\sprite.py";,546线,在绘图中
surface.blits((spr.image, spr.rect) for spr in sprites)
TypeError:源对象必须是表面
您已经多次使用名称bullet
,但用途不同。一开始它是一个pygame.Surface
对象,但在添加了第一个项目符号之后
bullet = Bullet(player.rect.centerx, player.rect.centery, player.direction, bullerRect)
它引用CCD_ 3对象。重命名变量。
对表示项目符号的图像使用名称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
要用空格键发射子弹,请参阅:
- 如何用空格键发射子弹
- 如何一次停止多发子弹
- Pygame:太空入侵者的射击问题