【问题标题】:How do I get random enemies to appear from list?如何让随机敌人从列表中出现?
【发布时间】:2017-08-23 15:57:56
【问题描述】:

我正在尝试从保存在变量中的汽车列表中随机出现一辆汽车。问题似乎是它从列表中随机选择一辆汽车,并且在玩游戏时不会改变它。每次上一辆车离开屏幕时,我都想换车。

每次游戏开始时,它都会从随机列表中选择一辆汽车,但不会在每次游戏循环运行时更换汽车。

我认为问题在于这段代码

randomCars = [car1, car2, car3, car4, car5, car6, car7, car8]
enemy = random.choice(randomCars)

我在下面粘贴了完整的代码:

import pygame
import time
import random

pygame.init()

#############

#############

display_width = 800
display_height = 600

black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
block_color = (53, 115, 255)

crash_sound = pygame.mixer.Sound("crash.mp3")

car_width = 55

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Super Racer')
clock = pygame.time.Clock()

gameIcon = pygame.image.load('carIcon.png')

backgroundImage = pygame.image.load("background.png")
backgroundImage = pygame.transform.scale(backgroundImage, (800, 600))
gameDisplay.blit(backgroundImage, (0, 0))





pygame.display.set_icon(gameIcon)

pause = False


# crash = True

def score(count):
    font = pygame.font.SysFont("comicsansms", 25)
    text = font.render("SCORE: " + str(count), True, red)
    gameDisplay.blit(text, (0, 0))

def load_image(name_img):
    car = pygame.image.load(name_img)
    car = pygame.transform.scale(car, (60, 100)) # resize graphic
    return car.convert_alpha() # remove whitespace from graphic

carImg = load_image('racecar.png')
enemies_list = ['diablo.png', 'aventador.png', 'nsx.png', 'bike.png', 'Mach6.png', 'speeder.png', 'Stingray.png', 'slr.png' ] # add all other cars
randomCars = [load_image(img) for img in enemies_list]

def things(enemy, thingx, thingy, thingw, thingh, color):
    gameDisplay.blit(enemy, [thingx, thingy, thingw, thingh])

def car(x, y):
    gameDisplay.blit(carImg, (x, y))


def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()


def crash():
    ####################################

    pygame.mixer.Sound.play(crash_sound)
    pygame.mixer.music.stop()
    ####################################
    largeText = pygame.font.SysFont("comicsansms", 115)
    TextSurf, TextRect = text_objects("You Crashed", largeText)
    TextRect.center = ((display_width / 2), (display_height / 2))
    gameDisplay.blit(TextSurf, TextRect)

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

        button("Play Again", 150, 450, 100, 50, green, bright_green, game_loop)
        button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)

        pygame.display.update()
        clock.tick(15)


def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
    smallText = pygame.font.SysFont("comicsansms", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    gameDisplay.blit(textSurf, textRect)


def quitgame():
    pygame.quit()
    quit()


def unpause():
    global pause
    pygame.mixer.music.unpause()
    pause = False


def paused():
    ############
    pygame.mixer.music.pause()
    #############
    largeText = pygame.font.SysFont("comicsansms", 115)
    TextSurf, TextRect = text_objects("Paused", largeText)
    TextRect.center = ((display_width / 2), (display_height / 2))
    gameDisplay.blit(TextSurf, TextRect)

    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Continue", 150, 450, 100, 50, green, bright_green, unpause)
        button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)

        pygame.display.update()
        clock.tick(15)


def game_intro():
    intro = True

    while intro:
        for event in pygame.event.get():
            # print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        gameDisplay.fill(white)
        largeText = pygame.font.SysFont("comicsansms", 115)
        TextSurf, TextRect = text_objects("Super Racer", largeText)
        TextRect.center = ((display_width / 2), (display_height / 2))
        gameDisplay.blit(TextSurf, TextRect)

        button("LEGGO!", 150, 450, 100, 50, green, bright_green, game_loop)
        button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)

        pygame.display.update()
        clock.tick(15)


def game_loop():
    global pause
    enemy = random.choice(randomCars)
    ############

    pygame.mixer.music.load('bgmusic.mp3')
    pygame.mixer.music.play(-1)
    ############
    x = (display_width * 0.45)
    y = (display_height * 0.8)

    x_change = 0

    thing_startx = random.randrange(0, display_width)
    thing_starty = -600
    enemy_speed = 4
    thing_width = 55
    thing_height = 95
    enemy = random.choice(randomCars)
    thingCount = 1

    dodged = 0

    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                if event.key == pygame.K_RIGHT:
                    x_change = 5
                if event.key == pygame.K_p:
                    pause = True
                    paused()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        x += x_change

        gameDisplay.blit(backgroundImage, (0, 0))

        things(enemy, thing_startx, thing_starty, thing_width, thing_height, block_color)

        thing_starty += enemy_speed
        car(x, y)
        score(dodged)

        if x > display_width - car_width or x < 0:
            crash()

        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0, display_width)
            dodged += 1
            #enemy_speed += .25
            if dodged % 5 == 0:
                enemy_speed += (dodged * 1)


        if y < thing_starty + thing_height:
            #print('y crossover')

            if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
                #print('x crossover')
                crash()

        pygame.display.update()
        clock.tick(60)


game_intro()
game_loop()
pygame.quit()
quit()

【问题讨论】:

  • 离题,但您可以使用简单的实用方法/列表理解来整理 car1 = ... 部分。
  • 谢谢,我打算在一切正常后进去整理一下。
  • 为什么不把enemy = random.choice(randomCars)移到game_loop函数的开头呢?这样enemy 会在每次循环重新启动时被声明(enemy 如果在外部调用也可能需要是一个全局变量)
  • 我试过了,这对我来说很有意义。不幸的是,它不起作用,我不知道为什么。
  • 请为有帮助的答案投票,并通过点击复选标记接受您的最爱以表明问题已解决。

标签: python python-2.7 random pygame


【解决方案1】:

这是一个最小的例子。只要当前汽车离开屏幕,只需使用random.choice 即可将一辆新车从列表中删除。

import random
import pygame


pygame.init()

CAR_IMG1 = pygame.Surface((30, 50))
CAR_IMG1.fill((10, 150, 200))
CAR_IMG2 = pygame.Surface((30, 50))
CAR_IMG2.fill((210, 150, 0))
CAR_IMG3 = pygame.Surface((30, 50))
CAR_IMG3.fill((10, 250, 0))

CARS = [CAR_IMG1, CAR_IMG2, CAR_IMG3]


def main():
    screen = pygame.display.set_mode((640, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    car = random.choice(CARS)
    pos_x = random.randrange(screen_rect.width-30)
    pos_y = -50

    done = False

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

        pos_y += 15
        if pos_y > screen_rect.height:
            car = random.choice(CARS)
            pos_x = random.randrange(screen_rect.width-30)
            pos_y = -50

        screen.fill((30, 30, 30))
        screen.blit(car, (pos_x, pos_y))

        pygame.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()

【讨论】:

  • 我还建议查看pygame.Rect 类,该类对于存储汽车的位置和碰撞检测很有用。我在示例中使用了一个矩形对象(screen_rect)来存储屏幕的大小。 Surfaces 有一个.get_rect() 方法,它返回一个矩形对象。
【解决方案2】:

首先初始化你的敌车图像列表,从中选择一个。

randomCars = [carImg1, carImg2, carImg3, carImg4]

在 game_loop() 函数内部但在主循环集之外 enemy = random.choice(randomCars)

在 game_loop() 函数的主循环中检查敌人是否离开了屏幕。如果是这样,请将敌人变量设置为新的随机汽车。

if thing_starty > display_height:
    # Reset enemy image
    enemy = random.choice(randomCars)
    # Reset thing co-ordinates
    thing_starty = -600
    thing_startx = random.randrange(0, display_width)

如果enemy = random.choice(randomCars) 代码行不起作用,您也可以尝试使用随机整数索引randomCars 列表。

randomCarsIndex = random.randint(0, len(randomCars) - 1) enemy = randomCars[randomCarsIndex]

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多