Reputation: 11
import pygame
screen = 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.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()
Error:
Traceback (most recent call last):
File "c:\Users\gopal\Desktop\Misc Projects\main.py", line 136, in
bullet_group.draw(SCREEN)
File "C:\Users\gopal\AppData\Local\Programs\Python\Python39\lib\site-packages\pygame\sprite.py", line 546, in draw
surface.blits((spr.image, spr.rect) for spr in sprites)
TypeError: Source objects must be a surface
Upvotes: 1
Views: 1212
Reputation: 211220
You have used the name bullet
several times, but for different things. At the beginning it is a pygame.Surface
object, but after adding the 1st bullet,
bullet = Bullet(player.rect.centerx, player.rect.centery, player.direction, bullerRect)
it reference a Bullet
object. Rename the variables.
Use the name bullet_surf
for the image that represents the bullet:
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
To fire a bullet with the space bar see:
Upvotes: 0