如何在 font.render 行中包含此变量?



我试图将掷骰子的结果包含在blit到屏幕上的文本字符串中,"You rolled a" + roll

我相信问题与"运行时:"的while循环或我编写代码的顺序有关,但我不知道如何解决它。任何帮助将不胜感激。我是StackOverflow的新手,所以如果标题/解释不够清楚,我提前道歉。

from random import *
import pygame
import sys
from pygame import rect
"""SETTINGS"""
global roll
clock = pygame.time.Clock()
fps = 60
WHITE = (255, 255, 255)
GREY = (200, 200, 200)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
WIDTH = 520
HEIGHT = 500
bg = (255, 255, 255)
"""functions"""

def dice():
roll = randint(1, 6)
print("You rolled a ", roll)

"""init"""
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Dice")
"""dice image"""
image = pygame.image.load("diceImage.gif").convert()
image2 = image.get_rect()
imageUsed = pygame.transform.scale(image, (WIDTH, HEIGHT))
"""text object"""
surf = pygame.Surface((WIDTH, 60))
font = pygame.font.SysFont("comicsansms", 37)
text = font.render("Click the dice to roll a number", True, (30, 128, 190))
surf2 = pygame.Surface((400, 60))
text2 = font.render(("You rolled a", roll), True, (30, 128, 190))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
dice()
mouse_pos = event.pos
if image2.collidepoint(mouse_pos):
print('button was pressed at {0}'.format(mouse_pos))
screen.fill(bg)
screen.blit(imageUsed, (0, 0))
screen.blit(surf, (0, 0))
screen.blit(surf2, (50, 450))
screen.blit(text, (0, 0))
screen.blit(text2, (50, 450))
pygame.display.update()
clock.tick(fps)

错误信息:

Traceback (most recent call last):
File "C:/Users/lee/Documents/PYTHON/Dice/Dice.py", line 50, in <module>
text2 = font.render(("You rolled a", roll), True, (30, 128, 190))
NameError: name 'roll' is not defined

你把global语句放在了错误的地方。global语句意味着列出的标识符将被解释为当前范围内的全局变量。
在全局命名空间中声明和初始化roll,但使用函数dice中的global语句在全局命名空间中设置变量roll

roll = 1
def dice():
global roll
roll = randint(1, 6)
print("You rolled a ", roll)

您必须通过str()roll的数值转换为字符串,然后才能在render()中使用它并将文本呈现Surface

text2 = font.render(("You rolled a " + str(roll)), True, (30, 128, 190))

dice()函数中,roll =实际上不会引用或修改顶级roll变量,这是您需要全局语句的地方。我不确定您使用的是哪个IDE,但是在粘贴相关代码时,我的代码会立即通知我roll = randint(1, 6)Shadows名称"roll"来自外部范围

我认为dice()函数应该重命名为更具描述性的名称,并失去打印。我对 PyGame 的了解还不够多,无法判断您是否可以完全摆脱全局变量。

此外,import *通常是不好的做法。

最新更新