python - 使用pygame添加图像

标签 python image pygame surface

我正在用 python 和 pygame 库编写一个小游戏。 游戏的想法是让一个小角色在地板上跑来跑去,避免撞到掉落的矩形。 这一切都是从游戏逻辑方面解决的。 但是当游戏开始时我仍然遇到问题:

当我水平翻转播放器时,根据它前进的方向,我必须根据按下的键分配 2 张图像。现在,每次我开始游戏并且没有按下任何键时,只有一个“隐藏/透明”的 pygame.Surface()-object,因为我需要它作为占位符来有条件地分配 2 个图像一次键(左或右)被按下。因此,游戏开始,当没有按下键时,没有玩家出现......

我的问题:如何在实际按下任何键并且不隐藏透明 Surface 对象之前添加默认(第 3 个)图像。我用 Surface.blit() 或 gameDisplay.blit() 尝试了很多东西,因此加载了另一张图片,但到目前为止它从未出现过:(...

我想这是一件愚蠢的事情,但我无法自己解决(+谷歌)..

提前致谢

我的代码:

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)
blue = (0,0, 255)
bright_red = (255, 0,0 )
bright_green = (0, 255, 0)

player_width = 100
player_height = 238
pause = False

gameDisplay = pygame.display.set_mode((display_width, display_height))          
pygame.display.set_caption('Gesi Run of her Life <3')
clock = pygame.time.Clock()

gesImg_left = pygame.image.load('yourimage.png')        
gesImg_right = pygame.transform.flip(gesImg_left, True, False)
background = pygame.image.load('yourbackground.jpg')


def things(thingx, thingy, thingw, thingh, color):

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

def ges(player_img, x,y):

    gameDisplay.blit(player_img, (x,y))

def text_objects(text, font, col):

    textSurface = font.render(text, True, col)
    return textSurface, textSurface.get_rect()

def message_display(text, col):

    largeText = pygame.font.Font('freesansbold.ttf', 50)
    TextSurf, TextRect = text_objects(text, largeText, col)
    TextRect.center = ((display_width/2), (display_height/2))

    gameDisplay.blit(TextSurf, TextRect)
    pygame.display.update()

    time.sleep(2)
    game_loop()

def crash():

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

        #gameDisplay.fill(white)
        largeText = pygame.font.Font('freesansbold.ttf', 60)
        TextSurf, TextRect = text_objects("A star was born!", largeText, black)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        button("Nochmal", 150, 450, 100, 50, green, bright_green, "play")
        button("quit", 550, 450, 100, 50, red, bright_red, "quit")

        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:
                if action == "play":
                    game_loop()
                elif action == "quit":
                    pygame.quit()
                    quit()
                elif action == "unpause":
                    global pause
                    pygame.mixer.music.unpause()
                    pause = False

        else:
            pygame.draw.rect(gameDisplay, ic, (x, y, w, h))

        smallText = pygame.font.Font('freesansbold.ttf', 20)
        TextSurf, TextRect = text_objects(msg, smallText, black)
        TextRect.center = ((x+(w/2)),(y +(h/2)))
        gameDisplay.blit(TextSurf, TextRect)

def paused():

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

        #gameDisplay.fill(white)
        largeText = pygame.font.Font('freesansbold.ttf', 60)
        TextSurf, TextRect = text_objects("Paused", largeText, black)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

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

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

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', 60)
        TextSurf, TextRect = text_objects("Gesi Super F/Run Game", largeText, black)
        TextRect.center = ((display_width/2), (display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        button("let's go", 150, 450, 100, 50, green, bright_green, "play")
        button("quit", 550, 450, 100, 50, red, bright_red, "quit")

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


def game_loop():

    global pause

    x = (display_width * 0.45)
    y = (display_height * 0.6)
    x_change = 0

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

    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    color = (r, g, b)

    #player = pygame.Surface((x*0,y*0))
    player = pygame.Surface((x,y), pygame.SRCALPHA, 32)
    #player = pygame.Surface([x,y], pygame.SRCALPHA, 32)
    player = player.convert_alpha()
    #pygame.display.update()
    gameExit = False

    # game loop: the logic that happens if you not quit OR crash
    while not gameExit:

        for event in pygame.event.get():    # list of events per frame per secend (clicking etc.)
            # ask if user asks to quit
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    if bonus > 0:
                        x_change = -5*bonus
                    else:
                        x_change = -5
                    player = gesImg_left

                if event.key == pygame.K_RIGHT:
                    if bonus > 0:
                        x_change = 5*bonus
                    else:
                        x_change = 5
                    player = gesImg_right
                if event.key == pygame.K_p:
                    pause = True
                    paused()

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

                elif event.key == pygame.K_RIGHT:
                    x_change = 0
                    player = gesImg_right

            #print(event) # see all the interaction on the screen printed out on the terminal console

        x = x + x_change
        player_img  = player    

        gameDisplay.blit(background,(0,0))

        if dodged == 10 or dodged == 20 or dodged == 30:
            r = random.randint(0,255)
            g = random.randint(0,255)
            b = random.randint(0,255)
            color = (r, g, b)

        things(thing_startx, thing_starty, thing_width, thing_height, color)
        thing_starty = thing_starty + thing_speed + random.randrange(-1,1)

        ges(player_img, x,y)
        things_dodged(dodged)

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

        if thing_starty > display_height:
            thing_starty =  0 - thing_height
            thing_startx = random.randrange(0, display_width)
            r = random.randint(0,255)
            g = random.randint(0,255)
            b = random.randint(0,255)
            color = (r, g, b)
            dodged = dodged + 1

    # managing the speed
            if dodged >= 17:
                thing_speed += random.uniform(-0.8,0.2)
            if dodged >= 27:
                thing_speed += random.uniform(0.8,1)
            if dodged >= 40:
                thing_speed += random.uniform(0.4,1.5)
            else:
                thing_speed += random.uniform(-0.4,0.9)

    # managing the width
            if dodged >= 19:
                thing_width += (dodged * random.uniform(-0.7,0))
            if dodged >= 35:
                thing_width += (dodged * random.uniform(0,1.1))
            if dodged >= 45:
                thing_width += (dodged * random.uniform(0,1.6))
            else:
                thing_width += (dodged * random.uniform(0.8,2))

    #managing the level ups 
        if dodged == 10:
            pygame.mixer.Sound.play(level_up)
            bonus = 1.5
        if dodged == 20:
            pygame.mixer.Sound.play(level_up)
            bonus = 2
        if dodged == 30:
            pygame.mixer.Sound.play(level_up)
            bonus = 2.4
        if dodged == 35:
            pygame.mixer.Sound.play(level_up)
            bonus = 2.8

    # crash condition and calling the crash() function once the crash happened
        if y + 38 < thing_starty + thing_height and (y + player_height)-15 > thing_starty + thing_height:
            if x>thing_startx and x<thing_startx+thing_width or x+player_width>thing_startx and x+player_width<thing_startx+thing_width:
                crash()

        pygame.display.update()
        #fps, running through the loop at a certain pace
        clock.tick(60)  

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

最佳答案

程序启动时,只需将 ges 表面之一分配给 player,而不是创建透明占位符表面。

player = pygame.Surface((x,y), pygame.SRCALPHA, 32)
player = player.convert_alpha()

# Replace the lines above with this one.
player = gesImg_left

关于python - 使用pygame添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52166042/

相关文章:

python - 如何在 Heroku 虚拟实例 (dyno) 中使用参数触发 Python 函数?

python - 迭代并设置类属性 - Python Django

python - 这些命中框正在交叉,即使它们实际上不与 if 语句一起使用

python - 为什么在运行时python show file not found 错误?

python - 如何使用 pandas/sqlalchemy 在 .db 文件中创建多个表

python - 如何使用 python flask 从谷歌云存储服务图像

c# - 将 System.Web.UI.WebControls.Image 转换为 System.Drawing.Image?

html - 具有最大宽度和最大高度过渡的图像在正确调整大小之前变大

python - 为什么我的pygame声音文件无法播放?

python - Pygame,声音不播放