如何从列表中显示随机敌人?

时间:2017-08-23 15:57:56

标签: python python-2.7 random pygame

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

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

我认为问题在于这段代码

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()

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

首先初始化敌人汽车图像列表,然后从中选择一个。

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]

希望这有帮助!