我正在尝试将骰子掷骰的结果包含在屏幕上的文本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
statement放在错误的位置。 global
语句意味着列出的标识符将被解释为当前范围内的全局变量。
在全局名称空间中声明并初始化roll
,但在函数global
中使用dice
语句在全局名称空间中设置variabel roll
:
roll = 1
def dice():
global roll
roll = randint(1, 6)
print("You rolled a ", roll)
您必须先通过
roll
将数值str()
转换为字符串,然后才能在render()
中使用它并呈现文本Surface
:text2 = font.render(("You rolled a " + str(roll)), True, (30, 128, 190))
关于python - 如何在font.render行中包含此变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60140839/