我正在制作一个关于鸡的小游戏,但我遇到了一些我无法找到解决方案的问题。问题是我的文本后面有一个小矩形,如下所示:The number of coins and a rectangle behind it. 我还发现错误是来自读取文本文件,代码是:
import pygame
from pygame import *
pygame.init()
surface = pygame.display.set_mode((800,600))
pg = pygame
coins = 0
eggs = 0
time_left = 12
chickens = 0
grain = 0
with open('stats.txt', 'r') as f:
a = f.readlines()
coins = a[0]
eggs = a[1]
time_left = a[2]
chickens = a[3]
grain = a[4]
font = pg.font.Font("freesansbold.ttf", 28)
text = font.render(coins,False,(255,255,255))
run = True
while run:
surface.fill(0)
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
surface.blit(text,(20,-2))
pg.display.update()
文本文件是:
0
0
12.0
0
0
我不认为我可以改变从文件中获取信息的方式,但如果您知道一种方法并且它有效,您可以让我知道。
最佳答案
文本末尾有一个无法显示的字符。文本的最后一个字符是\n
,因为文本文件中的每一行都以换行符结尾。因此,只需从文本中删除尾部换行符即可(请参阅 How do I remove a trailing newline? ):
硬币 = a[0]
coins = a[0].rstrip()
关于python - 为什么在 pygame 中屏幕上的位图文本后面有一个矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73639426/