在pygame中按下一个键后如何更改屏幕上的精灵 [英] how to change a sprite on the screen after pressing a key in pygame

查看:82
本文介绍了在pygame中按下一个键后如何更改屏幕上的精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Pygame, and still learning Python. I'm using Python 3.4. I followed this amazing game creation tutorial: http://pythonprogramming.net/pygame-python-3-part-1-intro/. After completing the lessons I decided to change the game slightly, and have succeeded in adding some more movement and fixed some bugs. However now I'm trying to figure out how to change the sprite when I press an arrow key, as to make it appear like it is tilting.

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

I have a file called racecar.png (which is the plane) and move_right.png (which looks like it is tilted). My end goal is to have it when I press the right arrow, move_right.png is displayed until I release the key, in which case it returns to racecar.png. I have looked up how to use sprite sheets, which failed, how to animate, watched YouTube, Googled my problem but I can't find anyone else who has this problem. Most of what I found talked about moving the sprite around the screen.

代码如下:

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 的全局变量中显示图像:

At each frame, you display the image in the global variable called carImp in this function:

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

SO,你要做的是改变这个变量的内容,使其指向显示前所需的图像.您应该首先阅读您汽车的所有图像–您可以将它们全部读入字典,以避免使用每个精灵的变量名称污染您的命名空间(甚至超过污染):

SO, what you have to do is to change the contents of this variable to point to the desired image before the display. You should first read all the images for your car – you can read them all into a dictionary to avoid polluting your namespace (even more than it is polluted) with a variable name for each sprite:

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

So, in the beginning, some code like:

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".)

(Here I've used a shortcut called "generator expression" to avoid having to write a "pygame.image.load" for each car image.)

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

And then, in your main loop, after you've read the keyboard, and detected whether the car is moving right or left (which you reflect in x_change) – just change carImp accordingly:

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

这篇关于在pygame中按下一个键后如何更改屏幕上的精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆