简体   繁体   English

产生多个敌人 pygame

[英]Spawn multiple enemies pygame

I have a task where i have to spawn in 3 enemies at random positions, but i only am able to spawn in 1 enemy, can someone help me with this?我有一个任务,我必须在随机位置生成 3 个敌人,但我只能生成 1 个敌人,有人可以帮我解决这个问题吗?

import pygame
import random

# Initialize the pygame modules to get everything started.
pygame.init()

# The screen that will be created needs a width and a height.
screen_width = 1300
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))

# This creates the player and gives it the image found in this folder.
player = pygame.image.load("player.jpg")

# Creating multiple enemies
enemy = []
enemy_height = []
enemy_width = []
enemyXPosition = []
enemyYPosition = []
num_enemies = 3

for i in range(num_enemies):
    enemy.append().image.load("monster.jpg")
    enemyheight = enemy.get_height()
    enemywidth = enemy.get_width()
    enemyXPosition = random.randint(1100, screen_width)
    enemyYPosition = random.randint(0, screen_height - enemyheight)

# Get the width and height of the images in order to do boundary detection (i.e. make sure the image stays within screen boundaries or know when the image is off the screen).
image_height = player.get_height()
image_width = player.get_width()

print("This is the height of the player image: " + str(image_height))
print("This is the width of the player image: " + str(image_width))

# Store the positions of the player as variables.
playerXPosition = 100
playerYPosition = 50

# Creating conditions for game to run
keyUp = False
keyDown = False
keyLeft = False
keyRight = False

# The game loop for running game till told to stop and drawing player and enemy
while 1:

    screen.fill(0)
    screen.blit(player, (playerXPosition, playerYPosition))
    screen.blit(enemies[i], (enemiesXPosition[i], enemiesYPosition[i]))

    pygame.display.flip()

    # This loops through events in the game.
    for event in pygame.event.get():

        # This event checks if the user quits the program, then if so it exits the program.
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
        
        # Event for Key presses
        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_UP:
                keyUp = True
            if event.key == pygame.K_DOWN:
                keyDown = True
            if event.key == pygame.K_LEFT:
                keyLeft = True
            if event.key == pygame.K_RIGHT:
                keyRight = True

        # Event to check if key is released
        if event.type == pygame.KEYUP:

            if event.key == pygame.K_UP:
                keyUp = False
            if event.key == pygame.K_DOWN:
                keyDown = False
            if event.key == pygame.K_LEFT:
                keyLeft = False
            if event.key == pygame.K_RIGHT:
                keyRight = False

    # Checks which keys are pressed and moves player accordingly
    if keyUp == True:
        if playerYPosition > 0:
            playerYPosition -= 1

    if keyDown == True:
        if playerYPosition < screen_height - image_height:
            playerYPosition += 1

    if keyLeft == True:
        if playerXPosition > 0:
            playerXPosition -= 1

    if keyRight == True:
        if playerXPosition < screen_width - image_width:
            playerXPosition += 1

    # Bounding box for the player:
    playerBox = pygame.Rect(player.get_rect())
    playerBox.top = playerYPosition
    playerBox.left = playerXPosition

    # Make enemy approach the player.
    for i in range(num_enemies):
        enemiesXPosition[i] -= 0.15

        # Bounding box for the enemy:
        enemyBox = pygame.Rect(enemies[i].get_rect())
        enemyBox.top = enemiesYPosition[i]
        enemyBox.left = enemiesXPosition[i]

    #Test collision of the boxes:
    if playerBox.colliderect(enemyBox):
        print("You lose!")

    # If the enemy is off the screen the user wins the game:
    if enemiesXPosition[i] < 0 - enemy_width[i]:
        print("You win!")

Create list for the enemies and the coordinates of the enemies.为敌人和敌人的坐标创建列表。 Load the enemy image and append enemies at random positions:在随机位置加载敌人图像和 append 个敌人:

enemies = []
enemiesXPosition = []
enemiesYPosition = []
num_enemies = 3

enemy = pygame.image.load("monster.jpg")
enemyheight = enemy.get_height()
enemywidth = enemy.get_width()

for i in range(num_enemies):

    enemyx = random.randint(1100, screen_width - enemywidth)
    enemyy = random.randint(0, screen_height - enemyheight)

    enemies.append(enemy)
    enemiesXPosition.append(enemyx)
    enemiesYPosition.append(enemyy)

Draw the enemies in a loop:循环绘制敌人:

while 1:

    screen.fill(0)
    screen.blit(player, (playerXPosition, playerYPosition))
    for i in range(num_enemies):
        screen.blit(enemies[i], (enemiesXPosition[i], enemiesYPosition[i]))

Move the enemies and test for collisions in a loop, too:移动敌人并循环测试碰撞:

while 1:
    # [...]

    # Make enemy approach the player.
    for i in range(num_enemies):
        enemiesXPosition[i] -= 0.15

        # Bounding box for the enemy:
        enemyBox = pygame.Rect(enemies[i].get_rect())
        enemyBox.top = enemiesYPosition[i]
        enemyBox.left = enemiesXPosition[i]

        #Test collision of the boxes:
        if playerBox.colliderect(enemyBox):
            print("You lose!")

        # If the enemy is off the screen the user wins the game:
        if enemiesXPosition[i] < 0 - enemywidth:
            print("You win!")

Complete example code:完整示例代码:

import pygame
import random

# Initialize the pygame modules to get everything started.
pygame.init()

# The screen that will be created needs a width and a height.
screen_width = 1300
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))

# This creates the player and gives it the image found in this folder.
player = pygame.image.load("player.jpg")

# Creating multiple enemies
enemies = []
enemiesXPosition = []
enemiesYPosition = []
enemy_width = []
enemy_height = []
num_enemies = 3

enemy = image.load("monster.jpg")
enemyheight = enemy.get_height()
enemywidth = enemy.get_width()

for i in range(num_enemies):

    enemyx = random.randint(1100, screen_width - enemywidth)
    enemyy = random.randint(0, screen_height - enemyheight)

    enemies.append(enemy)
    enemiesXPosition.append(enemyx)
    enemiesYPosition.append(enemyy)
    enemy_width.append(enemywidth)
    enemy_height.append(enemyheight)

# Get the width and height of the images in order to do boundary detection (i.e. make sure the image stays within screen boundaries or know when the image is off the screen).
image_height = player.get_height()
image_width = player.get_width()

print("This is the height of the player image: " + str(image_height))
print("This is the width of the player image: " + str(image_width))

# Store the positions of the player as variables.
playerXPosition = 100
playerYPosition = 50

# Creating conditions for game to run
keyUp = False
keyDown = False
keyLeft = False
keyRight = False

# The game loop for running game till told to stop and drawing player and enemy
while 1:

    screen.fill(0)
    screen.blit(player, (playerXPosition, playerYPosition))
    for i in range(num_enemies):
        screen.blit(enemies[i], (enemiesXPosition[i], enemiesYPosition[i]))

    pygame.display.flip()

    # This loops through events in the game.
    for event in pygame.event.get():

        # This event checks if the user quits the program, then if so it exits the program.
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
        
        # Event for Key presses
        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_UP:
                keyUp = True
            if event.key == pygame.K_DOWN:
                keyDown = True
            if event.key == pygame.K_LEFT:
                keyLeft = True
            if event.key == pygame.K_RIGHT:
                keyRight = True

        # Event to check if key is released
        if event.type == pygame.KEYUP:

            if event.key == pygame.K_UP:
                keyUp = False
            if event.key == pygame.K_DOWN:
                keyDown = False
            if event.key == pygame.K_LEFT:
                keyLeft = False
            if event.key == pygame.K_RIGHT:
                keyRight = False

    # Checks which keys are pressed and moves player accordingly
    if keyUp == True:
        if playerYPosition > 0:
            playerYPosition -= 1

    if keyDown == True:
        if playerYPosition < screen_height - image_height:
            playerYPosition += 1

    if keyLeft == True:
        if playerXPosition > 0:
            playerXPosition -= 1

    if keyRight == True:
        if playerXPosition < screen_width - image_width:
            playerXPosition += 1

    # Bounding box for the player:
    playerBox = pygame.Rect(player.get_rect())
    playerBox.top = playerYPosition
    playerBox.left = playerXPosition

    # Make enemy approach the player.
    for i in range(num_enemies):
        enemiesXPosition[i] -= 0.15

        # Bounding box for the enemy:
        enemyBox = pygame.Rect(enemies[i].get_rect())
        enemyBox.top = enemiesYPosition[i]
        enemyBox.left = enemiesXPosition[i]

        #Test collision of the boxes:
        if playerBox.colliderect(enemyBox):
            print("You lose!")

        # If the enemy is off the screen the user wins the game:
        if enemiesXPosition[i] < 0 - enemywidth:
            print("You win!")

Presumably you're expecting for the enemy object's properties to be contained in the following lists:大概您希望敌人对象的属性包含在以下列表中:

enemy = []
enemy_height = []
enemy_width = []
enemyXPosition = []
enemyYPosition = []

However, in your enemy initialization you assign directly to these variables instead of appending to them:然而,在你的敌人初始化中,你直接分配给这些变量而不是附加到它们:

enemyXPosition = random.randint(1100, screen_width)
enemyYPosition = random.randint(0, screen_height - enemyheight)

Additionally, you seem to be missing some underscores in height and width此外,您似乎在高度和宽度上缺少一些下划线

enemyheight = enemy.get_height()
enemywidth = enemy.get_width()

presumably you wanted to append these values to enemy_height and enemy_width大概你想要 append 这些值到enemy_heightenemy_width

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM