当前位置: 首页 > 知识库问答 >
问题:

如何在pygame中从if语句中blit文本?

许淳
2023-03-14

我一直在为我的第一个项目做这个骰子游戏,我把一切都准备好了,我只是不知道如何在窗口上显示结果。一切都应该正确格式化,但我得到一个错误,说参数1必须pyplay.表面,不是pyplay。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()

共有3个答案

陈欣荣
2023-03-14

这是我的观点,尽管其他答案都很好。

当我改变

# 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文件。通常我使用一个重绘窗口函数,绘制背景,然后是文本,然后是图像,因为一旦对象被点击到屏幕上,它就不能被取消,你需要重绘整个屏幕。

钱弘壮
2023-03-14

您可以使用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])
赫连越
2023-03-14

你实际要做的是在事件循环中烧毁一次结果文本。Surface.blit返回一个pyplay。rect对象,带有受影响的区域。这个矩形被分配给结果。该问题是由于您尝试blit结果而引起的。

您必须将渲染文本(pygame.Surface)指定给变量result
此外,如果文本的位置是(宽度、中间高度),则文本将被弹出窗口。您可能希望使用位置(四分之一宽度,中间高度)

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!") 
 类似资料:
  • 我有两个问题。 ①当useState初始值真假时,if语句如何适应下面? 比如说。。 ②当if语句为true和false时,如何使setGoodBotton从React钩子和if语句适应下面? 例如…(这不是工作)

  • 问题内容: 我正在寻找某种if语句来控制不同元素的状态。 我已经尝试了以下内容,但无法编译 问题答案: LESS具有用于mixin的保护表达式,而不是单个属性。 因此,您将创建一个像这样的mixin: 并通过调用或(或完全不调用)将其打开或关闭。

  • 问题内容: 如何在JSON中使用if语句这是代码:............................................... .................................................................. 这是必需的结果,如下所示: 实际上,这种方式是错误的,并且会导致JavaScript语法错误。 问题答案: 那是普通的J

  • 这让我头疼。我需要将if语句放在一个echo中(这个echo在一个函数中,实际上是用于表单提交) 下面是我的部分代码的示例。在这种情况下,我怎样才能把这些if语句放在我的echo中??

  • 问题内容: 在C语言中非常常见:像这样入侵“空if语句”: 它在Python中工作吗?我的意思是,我们可以通过使用它来提高应用程序的性能吗?我也想知道为什么。 问题答案: 如果“ if”中没有其他情况,则性能会得到改善,因为字节码不会将执行传递给“ if”情况。 这是一些功能和输出 以下示例应用程序: 分解为: 以下 分解为:

  • 我对此感到头疼。我需要将if语句放入回显中(这个回显在一个函数中,实际上是用于表单提交) 这是我的部分代码的一个示例。在这种情况下,我如何将这些if语句放入我的回显中??