python - 如何在pygame中按下按键后更改屏幕上的 Sprite

标签 python pygame sprite

我是 Pygame 新手,仍在学习 Python。我正在使用Python 3.4。 我遵循了这个令人惊叹的游戏创建教程:http://pythonprogramming.net/pygame-python-3-part-1-intro/ 。完成类(class)后,我决定稍微改变一下游戏,并成功地添加了更多 Action 并修复了一些错误。然而现在我试图弄清楚当我按下箭头键时如何改变 Sprite ,使它看起来像倾斜的。

我有一个名为 racecar.png (这是飞机)和 move_right.png (看起来像是倾斜的)的文件。我的最终目标是当我按下右箭头时,会显示 move_right.png ,直到我松开按键,在这种情况下它会返回 racecar.png。我查过如何使用 Sprite 表,但失败了,如何制作动画,观看了 YouTube,谷歌搜索了我的问题,但我找不到其他有此问题的人。我发现的大部分内容都涉及在屏幕上移动 Sprite 。

这是代码:

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

最佳答案

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

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

所以,您要做的就是在显示之前更改此变量的内容以指向所需的图像。 您应该首先读取汽车的所有图像 - 您可以将它们全部读入字典中,以避免每个 Sprite 的变量名称污染您的命名空间(甚至比被污染的还要严重):

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

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"]

(这里我使用了一个名为“生成器表达式”的快捷方式,以避免为每个汽车图像编写“pygame.image.load”。)

然后,在主循环中,在读取键盘并检测到 无论汽车是向右还是向左移动(您在 x_change 中反射(reflect)) - 只需相应地更改 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"]

关于python - 如何在pygame中按下按键后更改屏幕上的 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666653/

相关文章:

html - CSS Sprite 翻转显示垂直而不是水平

css - 列表项的 Sprite

CSS Sprite 缩放到 div 尺寸

带有参数 : @repeat(n) 的 Python3 'repeat' 装饰器

Python将字符串转换为字节

python - 为什么 Pygame 上不允许拖放事件?

python - 如何从分组的 Sprite 中调用函数?

python - 如何使用 python 中的 telegram bot 和 telepot 制作调查问卷

Python将二进制图像(PNG)数据写入文件

python - Python-[Errno 10054]现有连接被远程主机强行关闭-发送腌制数据问题