Pygame display multiple images randomly

2019-08-11 02:42发布

问题:

I am working with pygame and I was able to draw multiple lines on a screen. I made with this command:

for x in range(60,940,20):
        pygame.draw.line(screen, white, [x, 0], [x, 500], 1)

I now need to draw multiple images on the screen. I was able to draw one image by doing:

player_two = pygame.image.load("player_two.png").convert()
player_two.set_colorkey(white)



while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        screen.blit(player_two, [60, 240])

        pygame.display.flip()

    clock.tick(20)

pygame.quit()

I need to draw multiple of this object EITHER randomly within a range of [60, 0], [220, 475] #OR within the same range but with set coordinates. BOTH instances I need these images to move #randomly within that range in either x and/or y direction with a distance of the size of the #image (jump).

回答1:

To create multi players

import random

multi_players = []
multi_players_pos = []

player = pygame.image.load("player_two.png").convert()
player.set_colorkey(white)

#create 10 players 0...9
for i in range(10):
    multi_players.append(player)
    pos = [random.randint(60,220+1), random.randint( 0, 475+1)]
    multi_players_pos.append(pos)

or load player_0.png ... player_9.png:

multi_players = []
multi_players_pos = []

for i in range(10):
    temp = pygame.image.load("player_"+str(i)+".png").convert()
    temp.set_colorkey(white)
    multi_players.append(temp)
    pos = [random.randint(60,220+1), random.randint( 0, 475+1)]
    multi_players_pos.append(pos)

draw it:

while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        for i in range(len(multi_players)):
            screen.blit(multi_players[i], multi_players_pos)

        pygame.display.flip()

    clock.tick(20)

pygame.quit()

The same way you can change players position.

But better way is to make Player class with all needed function.

(it is not full code - so not tested)

import random

class Player():

    def __init__(self, image, x, y):
        self.image = pygame.image.load(image).convert()
        self.image.set_colorkey(white)
        image_rect = image.get_rect()

        self.rect = Rect(x, y, image_rect.width, image_rect.height)

    def draw(self, screen):
        screen.blit(self.image, self.rect.topleft)

    def update(self):
        # here change randomly positon

#--------------------------------------------

multi_players = []

#create 10 players 0...9
for i in range(10):
    x, y = random.randint(60,220+1), random.randint( 0, 475+1)
    multi_players.append(Player("player_"+str(i)+".png", x, y))

while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # changes position

    for player in multi_players:
        player.update()

    # draws

    for player in multi_players:
        player.draw(screen)

    pygame.display.flip()

    clock.tick(20)

pygame.quit()

EDIT:

Full working example - if you press any key (except ESC) images change position.

I use transparent PNG ball1.png, ball2.png, ball3.png so I don't use .convert() and .set_colorkey().

Images you can find (and download) in answer to questions:

  • Space invaders project
  • Pygame- window and sprite class - python

.

import random
import pygame

WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )

#----------------------------------------------------------------------

class Player():

    def __init__(self, image, x=0, y=0):

        self.image = pygame.image.load(image)#.convert()
        #self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()

        self.rect.centerx = x
        self.rect.centery = y

    #------------

    def draw(self, screen):
        screen.blit(self.image, self.rect)

    #------------

    def update(self):
        # here change randomly positon
        self.rect.topleft = random.randint(60,220+1), random.randint( 0, 475+1)

#----------------------------------------------------------------------

class Game():

    def __init__(self):

        pygame.init()

        self.screen = pygame.display.set_mode((800,600))

        self.background = pygame.image.load("background.jpg").convert()
        self.multi_players = []

        # create 3 balls 1...3

        for i in range(1,4):
            player = Player("ball"+str(i)+".png")
            player.update() # set random position on start
            self.multi_players.append(player)

    #------------

    def run(self):

        clock = pygame.time.Clock()
        RUNNING = True

        while RUNNING:

            # --- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False

                    # changes position when key is pressed

                    for player in self.multi_players:
                        player.update()

            # --- updates ---- 

            # place for updates

            # --- draws ---

            self.screen.fill(BLACK)

            self.screen.blit(self.background, self.background.get_rect())

            for player in self.multi_players:
                player.draw(self.screen)

            pygame.display.flip()

            # --- FPS ---

            clock.tick(20)

        # --- quit ---

        pygame.quit()

#----------------------------------------------------------------------

Game().run()