如何在pygame中按键后更改屏幕上的精灵

时间:2015-06-05 12:31:39

标签: python pygame sprite

我是Pygame的新手,还在学习Python。我使用的是Python 3.4。 我按照这个惊人的游戏创建教程:http://pythonprogramming.net/pygame-python-3-part-1-intro/。完成课程后,我决定稍微改变游戏,并成功添加了一些动作并修复了一些错误。但是现在我试图弄清楚当我按箭头键时如何更改精灵,以使它看起来像是倾斜。

我有一个名为racecar.png的文件(即飞机)和move_right.png(看起来像是倾斜的)。我的最终目标是在按下右箭头时显示move_right.png,直到我释放密钥,在这种情况下它会返回到racecar.png。我已经查找了如何使用精灵表,失败,如何制作动画,观看YouTube,搜索我的问题,但我无法找到有此问题的其他人。我发现的大部分内容都是关于在屏幕上移动精灵的。

以下是代码:

import pygame
import random
import time

pygame.init()

car_width = 100
car_height = 100

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A Macross Simumater')

black = (0,0,0)
white = (255, 255, 255)
red = (255, 0,0)
green = (0,255,0)
greent = (0, 150, 0)
blue = (0,0, 200)
dark_blue = (0, 0, 50)

clock = pygame.time.Clock()

carImp = pygame.image.load('racecar.png')

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

#background = pygame.image.load('background.png')

pygame.display.set_icon(gameIcon)

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

def unpause():
    global pause
    pause = False

def paused():

    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,black,unpause)
        button("Quit",550,450,100,50,red,black,quitgame)

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


def things_dodged(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Dodged: " + str(count), True, black)
    gameDisplay.blit(text, (0,0))

def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])

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

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

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf', 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2), (display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

    time.sleep(2)

    game_loop()

def crash():


    largeText = pygame.font.SysFont("comicsansms",115, (0, 0, 0))
    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,black,game_loop)
        button("Quit",550,450,100,50,red,black,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()
    print(click)

    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.Font('freesansbold.ttf', 21)
    textSurf, textRect = text_objects("GO!", smallText)
    textRect.center = ((150+(100/2)), (450+(50/2)))
    gameDisplay.blit(textSurf, textRect)

    textSurf, textRect = text_objects("QUIT!", smallText)
    textRect.center = ((550+(100/2)), (450+(50/2)))
    gameDisplay.blit(textSurf, textRect)

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

        gameDisplay.fill(white)
        largeText = pygame.font.Font('freesansbold.ttf', 115)
        TextSurf, TextRect = text_objects('Macross',largeText)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        mouse = pygame.mouse.get_pos()

        button("GO!", 150, 450, 100, 50, green, black, game_loop)
        button("Quit", 550,450,100,50, red, black, quitgame)

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

def game_loop():
    global pause

    pygame.mixer.music.load('Macross Plus - Voices HQ MV Karaoke Instrumental Japanese.mp3')
    pygame.mixer.music.play(-1)

    x = (display_width * 0.45)
    y = (display_height * 0.8)

    global x_change
    global y_change

    x_change = 0
    y_change = 0


    pause = False

    dodged = 0

    thing_startx = random.randrange(0, display_width)
    thing_starty = -600
    thing_speed = 4
    thing_width = 50
    thing_height = 50

    thingt_startx = random.randrange(0, display_width)
    thingt_starty = -600
    thingt_speed = 7
    thingt_width = 100
    thingt_height = 100


    gameExit = False

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


            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    x_change = 8
                elif event.key == pygame.K_LEFT:
                    x_change = -8
                elif event.key == pygame.K_p:
                    pause = True
                    paused()
                elif event.key == pygame.K_UP:
                    y_change = -8
                elif event.key == pygame.K_DOWN:
                    y_change = 8
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    x_change = 0
                    y_change = 0

        x += x_change
        y += y_change

        gameDisplay.fill(dark_blue)

        things(thing_startx, thing_starty, thing_width, thing_height, greent)
        thing_starty += thing_speed
        things(thingt_startx, thingt_starty, thingt_width, thingt_height, greent)
        thingt_starty += thingt_speed

        car(x, y)


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

        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0, display_width)
            dodged += 1
            thing_speed += 1
            thing_width += (dodged * 1.2)
            thing_height += (dodged * 2)
            thingt_starty = 0 - thing_height
            thingt_startx = random.randrange(0, display_width)
            dodged += 1
            thingt_speed += 1
            thingt_width += (dodged * 1.2)
            thingt_height += (dodged * 2)

        if thing_starty < y:
            if y < thing_starty+thing_height:
                if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
                    crash()
        elif thing_starty > y:
            print('passed')

        if thingt_starty < y:
            if y < thingt_starty+thingt_height:
                if x > thingt_startx and x < thingt_startx + thingt_width or x +     car_width > thingt_startx and x + car_width < thingt_startx + thingt_width:
                    crash()
        elif thingt_starty > y:
            print('PASSED')





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



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

1 个答案:

答案 0 :(得分:1)

在每个帧中,您在此函数中显示名为carImp的全局变量中的图像:

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

所以,您需要做的是更改此变量的内容以指向显示前的所需图像。 您应该首先阅读汽车的所有图像 - 您可以将它们全部读入字典中,以避免污染您的命名空间(甚至超过它被污染),每个精灵都有一个变量名称:

所以,在一开始,一些代码如:

car_image_names = ["racecar", "move_right", "move_left"]
car_sprites = dict(((img_name, pygame.image.load(img_name + ".png"))
                        for img_name in car_image_names)
carImp = car_sprites["racecar"]

(这里我使用了名为&#34的快捷方式;生成器表达式&#34;以避免为每个汽车图像编写&#34; pygame.image.load&#34;。

然后,在您的主循环中,在您阅读键盘并检测到之后 汽车是向右还是向左移动(您在x_change中反映) - 只需相应更改carImp

if x_change == 0:
    carImp = car_sprites["racecar"]
elif x_change > 0:
    carImp = car_sprites["move_right"]
elif x_change < 0:
    carImp = car_sprites["move_left"]