Exibindo imagens aleatoriamente em um jogo Python com Pygame

Aug 31 2020

Estou trabalhando em um jogo de labirinto, o ator principal tem que encontrar um caminho movendo-se entre as paredes para acessar a saída.

Fiz uma parte do projeto, mas só que não consigo exibir objetos (seringa, agulha e tubo de plástico) de forma aleatória (eles têm que mudar de posição a cada início) no labirinto, depois pegar e exibir um contador que irá listar os itens coletados.

Eu tenho que modificar minha função GERAR, no loop que passa por meu arquivo de texto eu tenho que recuperar os espaços vazios (sprite == 0), colocá-los em uma lista, então usar um aleatório imagino para recuperar 3 posições aleatórias para cada objeto. Por exemplo, para as três posições aleatórias do objeto seringa armazenado em uma lista, tenho que substituir o (sprite == 0) por (sprite == s), s = seringa. Então, no final, eu teria três posições s que usaria em minha função show para fazer a exibição.

    def generer(self):
    """Method for generating the start based on the file.
    we create a general list, containing one list per line to display"""
    # We open the file
    with open(self.file, "r") as file:
        structure_level = []
        # We browse the lines of the file
        for line in file:
            line_level = []
            # We browse the sprites (letters) contained in the file
            for sprite in line:
                # We ignore the end of line "\ n"
                if sprite != '\n':
                    # We add the sprite to the list of the line
                    line_level.append(sprite)
            # Add the line to the level list
            structure_level.append(line_level)
        # We save this structure
        self.structure = structure_level

    def show(self, window):
    """Méthode permettant d'afficher le niveau en fonction
    de la liste de structure renvoyée par generer()"""
    # Chargement des images (seule celle d'arrivée contient de la transparence)
    wall = pygame.image.load(wall_image).convert()
    departure = pygame.image.load(departure_image).convert_alpha()
    arrived = pygame.image.load(Gardien_image).convert_alpha()
    syringe = pygame.image.load(syringe_image).convert_alpha()

    # We go through the list of the level
    number_line = 0
    for line in self.structure:
        # On parcourt les listes de lignes
        num_case = 0
        for sprite in line:
            # We calculate the real position in pixels
            x = num_case * sprite_size
            y = number_line * sprite_size
            if sprite == 'w':  # w = Wall
                window.blit(wall, (x, y))
            elif sprite == 'd':  # d = Départure
                window.blit(departure, (x, y))
            elif sprite == 'a':  # a = Arrived
                window.blit(arrived, (x, y))
            elif sprite == 's':  # s = syringe
                window.blit(syringe, (x, y))

            num_case += 1
        number_line += 1

Depois disso, tenho que encontrar uma maneira de comparar a posição (xey) de um objeto (seringa por exemplo) com a posição atual do personagem principal, e se os dois forem iguais, então eu poderia dizer que o personagem está exatamente ligado o ponto. 'objeto.

Aqui está o meu problema, espero ter explicado bem.

Obrigado

Respostas

Mike67 Aug 31 2020 at 21:49

Para colocar (3) seringas aleatoriamente, tente esta lógica:

  • Conte todos os espaços no labirinto
  • Divida a contagem de espaço por 3
  • Em cada terço, coloque uma seringa em uma posição aleatória

Isso deve manter as posições da seringa aleatórias, mas uniformemente distribuídas.

Aqui está o código atualizado. Não foi testado, portanto, pode ser necessário ajustá-lo um pouco.

def generer(self):
"""Method for generating the start based on the file.
we create a general list, containing one list per line to display"""
import random
zerocnt = 0 # counter for empty spaces
# We open the file
with open(self.file, "r") as file:
    structure_level = []
    # We browse the lines of the file
    for line in file:
        line_level = []
        # We browse the sprites (letters) contained in the file
        for sprite in line:
            # We ignore the end of line "\ n"
            if sprite != '\n':
                # We add the sprite to the list of the line
                line_level.append(sprite)
                if sprite == 0: zerocnt += 1 # another space
        # Add the line to the level list
        structure_level.append(line_level)

    # 3 syringes, distribute evenly
    div3 = zerocnt//3  # divide empty spaces by 3
    # generate 3 positions, 1 syringe per third of maze
    poslst = [random.randint(i*div3, (i+1)*div3-1) for i in [0,1,2]]
    ctr=0
    # scan empty spaces, update 3 spots
    for lvl in structure_level:
       for i in range(len(lvl)):
           if ctr in poslst:
               lvl[i]='s' # put syringe here
               ctr += 1
    
    # We save this structure
    self.structure = structure_level

Para a outra parte da postagem, verificando se o jogador encontrou uma seringa, não sei como você está movendo o jogador, então só posso adivinhar. Supondo que o jogador tenha uma coordenada (x, y), você pode verificar se essa posição tem um 's' na matriz.

Experimente algo assim:

Player.X = 5
Player.Y = 5
if self.structure[Player.X][Player.Y] == 's':
    print("Found syringe")
    Player.Syringes += 1
    self.structure[Player.X][Player.Y] = 0  # remove syringe from maze (or set to player)