Pygame文本优化

2024-10-05 10:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pygame进行培训,想看看是否有比我在那里做的更好的方法来显示特定坐标的文本:

font = pygame.font.SysFont("freesansbold.tff", 30, False)
textA = font.render("a", True, black)
displaySurf.blit(textA, ((2 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textB = font.render("b", True, black)
displaySurf.blit(textB, ((3 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textC = font.render("c", True, black)
displaySurf.blit(textC, ((4 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textD = font.render("d", True, black)
displaySurf.blit(textD, ((5 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textE = font.render("e", True, black)
displaySurf.blit(textE, ((6 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textF = font.render("f", True, black)
displaySurf.blit(textF, ((7 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textG = font.render("g", True, black)
displaySurf.blit(textG, ((8 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
textH = font.render("h", True, black)
displaySurf.blit(textH, ((9 * w - w / 2 - 8),(windowHeight - 7/8 *h)))
text8 = font.render("8", True, black)
displaySurf.blit(text8, ((2 * w / 3),(2 * h - h / 2 - 10)))
text7 = font.render("7", True, black)
displaySurf.blit(text7, ((2 * w / 3),(3 * h - h / 2 - 10)))
text6 = font.render("6", True, black)
displaySurf.blit(text6, ((2 * w / 3),(4 * h - h / 2 - 10)))
text5 = font.render("5", True, black)
displaySurf.blit(text5, ((2 * w / 3),(5 * h - h / 2 - 10)))
text4 = font.render("4", True, black)
displaySurf.blit(text4, ((2 * w / 3),(6 * h - h / 2 - 10)))
text3 = font.render("3", True, black)
displaySurf.blit(text3, ((2 * w / 3),(7 * h - h / 2 - 10)))
text2 = font.render("2", True, black)
displaySurf.blit(text2, ((2 * w / 3),(8 * h - h / 2 - 10)))
text1 = font.render("1", True, black)
displaySurf.blit(text1, ((2 * w / 3),(9 * h - h / 2 - 10)))

先谢谢你


Tags: truerenderpygameblackfontblitdisplaysurfwindowheight
1条回答
网友
1楼 · 发布于 2024-10-05 10:47:25

我建议使用for-循环来绘制文本。e、 g.:

font = pygame.font.SysFont("freesansbold.tff", 30, False)
for n in range(8):

    textCol = font.render(chr(ord('a') + n), True, black)
    displaySurf.blit(textCol, ((n+2)*w - w/2 - 8, windowHeight - 7/8 *h))

    textRow = font.render(str(8-n), True, black)
    displaySurf.blit(textRow, (2*w/3, (n+2)*h - h/2 - 10))

注意,^{}返回表示Unicode码位为整数的字符的字符串i^{}返回表示字符Unicode码位的整数。
所以从ah的字符可以通过chr(ord('a') + n)得到,其中n在0到7之间。
^{}用于将整数值转换为字符串


出于性能原因,可以将文本表面呈现为行和列的列表。最后.blit准备好的表面显示:

font = pygame.font.SysFont("freesansbold.tff", 30, False)
textColumns = [font.render(chr(ord('a') + n), True, black) for n in range(8)]
textRows    = [font.render(str(8-n), True, black) for n in range(8)]
for n, t in enumerate(textColumns):
    displaySurf.blit(t, ((n+2)*w - w/2 - 8, windowHeight - 7/8 *h)) 
for n, t in enumerate(textRows):
    displaySurf.blit(t, (2*w/3, (n+2)*h - h/2 - 10))

相关问题 更多 >

    热门问题