1
votes

I'm trying to use a list to randomly pick an image but I got this error:

mob = random(list[pygame.image.load("image1.png"),pygame.image.load("image2.png"),pygame.image.load("image3.png"),]) TypeError: 'type' object is not subscriptable

If I load the image manually in the pygame.image.load("Image") it works, but then I got this error. angryball_image_rect should be defined tho

screen.blit(angryball, angryball_image_rect.move(angryball_image_rect.width, 0)) NameError: name 'angryball_image_rect' is not defined

import pygame
import os
import random

size = width, height = 750, 422
screen = pygame.display.set_mode(size)

img_path = os.path.join(os.getcwd())
background_image = pygame.image.load('background.jpg').convert()
bg_image_rect = background_image.get_rect()
pygame.mixer.pre_init(44100, 16, 2, 4096)

pygame.display.set_caption("BallGame")

class Ball(object):
    def __init__(self):
        self.image = pygame.image.load("ball.png")
        self.image_rect = self.image.get_rect()
        self.image_rect.x
        self.image_rect.y
        self.facing = 'LEFT'

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 5
        if key[pygame.K_DOWN] and self.image_rect.y < 321:
            self.facing = 'DOWN'
            self.image_rect.y += dist
        elif key[pygame.K_UP] and self.image_rect.y > 0:
                self.facing = 'UP'
        self.image_rect.y -= dist
        if key[pygame.K_RIGHT] and self.image_rect.x < 649:
           self.facing = 'RIGHT'
            self.image_rect.x += dist
       elif key[pygame.K_LEFT] and self.image_rect.x > 0:
            self.facing = 'LEFT'
            self.image_rect.x -= dist

    def draw(self, surface):
        if self.facing == "RIGHT":
            surface.blit(pygame.transform.flip(self.image, True, False),(self.image_rect.x,self.image_rect.y))
        elif self.facing == "DOWN":
            surface.blit(pygame.image.load("ball_down.png"),(self.image_rect.x,self.image_rect.y))
        if self.facing == "UP":
            surface.blit(pygame.image.load("ball_up.png"),(self.image_rect.x,self.image_rect.y))
        elif self.facing == "LEFT":
            surface.blit(self.image,(self.image_rect.x,self.image_rect.y))


#List of objects to randomly select the image of the Angryball
mob = random(list[pygame.image.load("image1.png"),pygame.image.load("image2.png"),pygame.image.load("image3.png"),])

class Angryball(object):
    def __init__(self):
        self.image = mob
        self.image_rect = self.image.get_rect()
        self.image_rect.x
        self.image_rect.y
        self.facing = 'LEFT'


pygame.init()
screen = pygame.display.set_mode((750, 422))

ball = Ball()
angryball = Angryball()

clock = pygame.time.Clock()

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.play(-1, 0.0)

running = True
while running:
    esc_key = pygame.key.get_pressed()
    for event in pygame.event.get():
        if esc_key[pygame.K_ESCAPE]:
            pygame.display.quit()
            pygame.quit()
            running = False

    ball.handle_keys()

#Move the Angryball from right to left at speed 5 spawning randomly on the right border when it reaches the left border
    screen.blit(angryball, angryball_image_rect.move(angryball_image_rect.width, 0))
    angryball_image_rect = angryball.get_rect()
    angryball_image_rect.move_ip(-5, 0)
    if angryball_image_rect.x <= 0:
        angryball_image_rect.x = random.randint(101, 649) #101 is the size of the image so it wont be split at the border's edge

    screen.blit(background_image, bg_image_rect)
    screen.blit(background_image, bg_image_rect.move(bg_image_rect.width, 0))
    bg_image_rect.move_ip(-2, 0)
    if bg_image_rect.right <= 0:
        bg_image_rect.x = 0


    ball.draw(screen)
    pygame.display.update()

    clock.tick(60)
1
@skrx I'm seeking guidance because i'm still learning and the only things i have "clear" are the steps i have to make. I am stuck because i don't know where to start so some quick hints will be great to make my mind clear. But thank you anyway. - Shuratt
@skrx For example, i've found this stackoverflow.com/questions/43732487/… as a possible solution for the first point but i thought it could be possibile to use the random function directly in a pygame.image.load() by loading a list of objects - Shuratt
Okay, to spawn the sprites, first load the images before the game loop starts and put them into a list, then in your main loop generate some random coordinates at the side of the screen with the random module and finally create instances of your sprite, pass a random image and the coordinates and add the sprites to a pygame sprite group or list. - skrx
@skrx Thank you - Shuratt
For the movement it would be a good idea to give your sprite class an update method in which you update the position of the sprite each frame. In the main loop iterate over your sprite container with a for loop and call the update method of the sprites to move them. With a pygame.sprite.Group you can just call my_sprite_group.update(). -- Try to implement these things and edit your question if you got a more specific problem. I could also create a chat room. - skrx

1 Answers

1
votes

Define your images list in the global scope and fill it with your images. Then you can call random.choice to get one of the images in the list and pass it together with your random coordinates to the __init__ method of your sprite class where you can assign them to the specific attributes of the sprite.

# Load the images once and put them into a global list. Then you don't have
# to load them from the hard disk again (which is inefficient) and you can
# use `random.choice` to pick one of the images. Also, call convert or
# convert_alpha to improve the blit performance.
mob_images = [
    pygame.image.load("image1.png").convert_alpha(),
    pygame.image.load("image2.png").convert_alpha(),
    pygame.image.load("image3.png").convert_alpha(),
    ]

mob_image = random.choice(mob_images)  # Pick a random image.


class Angryball(object):
    # The __init__ method now takes an image (pygame.Surface) and
    # the x- and y-position.
    def __init__(self, image, pos_x, pos_y):
        self.image = image
        self.image_rect = self.image.get_rect()
        self.image_rect.x = pos_x
        self.image_rect.y = pos_y
        self.facing = 'LEFT'

# Pass the random image and the coordinates to the `__init__` method.
angryball = Angryball(mob_image, 700, random.randrange(400))

The TypeError was raised because you tried to call list with square brackets (which are used for indexing):

list[1, 2, 3]  # Won't work, because square brackets are used for indexing.

list([1, 2, 3])  # This works but is unnecessary, because it's already a list.