【问题标题】:How do I blit text from an if statement in pygame?如何从pygame中的if语句中传输文本?
【发布时间】:2020-07-12 07:02:22
【问题描述】:

我一直在为我的第一个项目开发这款骰子游戏,我已经启动并运行了所有东西,我只是不知道如何在窗口上显示(blit)结果。一切都应该正确格式化,但我收到一个错误,说参数 1 必须是 pygame.Surface,而不是 pygame.Rect。如何正确显示谁赢了?

这是我的参考代码...

import pygame
import random
import os
import os.path

WIDTH = 750
HEIGHT = 750
FPS = 60
QUARTER_WIDTH = WIDTH // 4
MIDDLE_HEIGHT = HEIGHT // 2
white = (255, 255, 255)

pygame.init()
pygame.font.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Dice Game")

# Fonts and Text
title_font = pygame.font.SysFont("comicsans", 70)
title_label = title_font.render("Would You like to roll? Y/N", 1, (255, 255, 255))
result_font = pygame.font.Font("freesansbold.ttf", 32)

# Load images
dice1 = pygame.image.load(os.path.join("assets", "dice_1.png"))
dice2 = pygame.image.load(os.path.join("assets", "dice_2.png"))
dice3 = pygame.image.load(os.path.join("assets", "dice_3.png"))
dice4 = pygame.image.load(os.path.join("assets", "dice_4.png"))
dice5 = pygame.image.load(os.path.join("assets", "dice_5.png"))
dice6 = pygame.image.load(os.path.join("assets", "dice_6.png"))

# Indexed list to reference all the faces
all_dice = [None, dice1, dice2, dice3, dice4, dice5, dice6]
pygame.display.set_icon(dice6)

# Game Background
background = pygame.transform.scale(pygame.image.load(os.path.join("assets", "dice_board.png")), (WIDTH, HEIGHT))


### Function to perform the random parts of the game
def rollDice():
    """ Generate the two random numbers, one for the Player and Opponent """
    player_roll = random.randint(1, 6)
    opponent_roll = random.randint(1, 6)

    return player_roll, opponent_roll


### Main Loop
clock = pygame.time.Clock()
running = True
player_face = None  # No dice before first roll
player_roll = 0
opponent_face = None  # No dice before first roll
player_roll = 0
result = None
textRect1 = None

while running:

    # handle user input
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_y:
                player_roll, opponent_roll = rollDice()
                player_face = all_dice[player_roll]
                opponent_face = all_dice[opponent_roll]

                # Debug prints

                text1 = result_font.render(f'opponent won. They rolled a {opponent_roll}', 1, white)
                text2 = result_font.render(f'You win! They rolled a {opponent_roll}', 1, white)
                text3 = result_font.render('Tied!', 1, white)
                textRect1 = text1.get_rect()

                if opponent_roll > player_roll:
                    result = window.blit(text1, (WIDTH, MIDDLE_HEIGHT))
                    print(f"opponent won. They rolled a {opponent_roll}")
                elif opponent_roll < player_roll:
                    result = window.blit(text2, (WIDTH, MIDDLE_HEIGHT))
                    print(f"You win! They rolled a {opponent_roll}")
                elif opponent_roll == player_roll:
                    result = window.blit(text3, (WIDTH, MIDDLE_HEIGHT))
                    print("tied!")

    # Repaint the screen

    window.blit(background, (0, 0))
    window.blit(title_label, (WIDTH // 2 - title_label.get_width() // 2, 250))
    # Where I'm trying to blit the result text
    if (result != None) and (textRect1 != None):
        window.blit(result, textRect1)
    # Paint the dice faces
    if (player_face != None):
        window.blit(player_face, (QUARTER_WIDTH, MIDDLE_HEIGHT))
    if (opponent_face != None):
        window.blit(opponent_face, (3 * QUARTER_WIDTH, MIDDLE_HEIGHT))

    # flush display changes
    pygame.display.flip()

    # Constrain FPS
    clock.tick(FPS)

pygame.quit()

【问题讨论】:

  • 您是否检查了错误所指的代码行?你知道argument 是什么吗?您是否尝试阅读您正在使用的功能的文档?

标签: python pygame


【解决方案1】:

您实际上要做的是在事件循环中blit一次结果文本。 pygame.Surface.blit 返回一个 pygame.Rect 对象,带有受影响的区域。这个矩形被分配给result。问题是由于您尝试 blit result.

您必须将呈现的文本 (pygame.Surface) 分配给变量 result
此外,如果文本的位置是(WIDTH, MIDDLE_HEIGHT),那么文本将被从窗口中删除。可能您想使用职位(QUARTER_WIDTH, MIDDLE_HEIGHT)

while running:
    # [...]

    for event in pygame.event.get():
        # [...]

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_y:
                # [...]

                textRect1 = text1.get_rect(topleft = (QUARTER_WIDTH, MIDDLE_HEIGHT))
                
                if opponent_roll > player_roll:
                    result = text1
                    print(f"opponent won. They rolled a {opponent_roll}")
                
                elif opponent_roll < player_roll:
                    result = text2
                    print(f"You win! They rolled a {opponent_roll}")
                
                elif opponent_roll == player_roll:
                    result = text3
                    print("tied!") 

【讨论】:

    【解决方案2】:

    你可以使用 pygames 的 blit 函数来做到这一点。通过创建可变文本,您还可以选择文本的字体。

    len_of_snake = 5
    font = pygame.font.Font('Roboto-Italic.ttf', 32)
    text = font.render(f'AI: {len_of_snake}', True, (0, 0, 0))
    window.blit(text, [0, 0])
    

    【讨论】:

    • 这没有回答问题。
    【解决方案3】:

    尽管其他答案很好,但这是我的看法。

    当我改变时

    # Where I'm trying to blit the result text
    if (result != None):
        window.blit(result, (QUARTER_WIDTH, MIDDLE_HEIGHT))
    

     if opponent_roll > player_roll:
                    result =  result_font.render(f'opponent won. They rolled a {opponent_roll}', 1, white)
                    print(f"opponent won. They rolled a {opponent_roll}")
                elif opponent_roll < player_roll:
                    result = result_font.render(f'You win! They rolled a {opponent_roll}', 1, white)
                    print(f"You win! They rolled a {opponent_roll}")
                elif opponent_roll == player_roll:
                    result = result_font.render('Tied!', 1, white)
                    print("tied!")
    

                if event.key == pygame.K_y:
                    window.fill((0,0,0))  # Read the text under here for clarification 
                    player_roll, opponent_roll = rollDice()
    

    更改后它对我有用,我不得不注释掉所有外部 .png 文件。 通常我使用重绘窗口函数来绘制背景,然后是文本,然后是图像,因为一旦对象被 blit 到屏幕,它就不能被 unblit,你需要重绘整个屏幕。

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多