pygame 程序中的字体未打印出来

Font not printing out in pygame program

我正在 Python 中编写一个程序,该程序将用作刮刮票类型的游戏。除了当用户 'scratches off' 票上的正方形时打印出数字外,我已经完成了所有工作。 这是我的代码:

    import pygame
    pygame.init()
    pygame.font.init()

    screen = pygame.display.set_mode((300,450))
    pygame.display.set_caption("test grid")

    background = pygame.Surface(screen.get_size())
    background.fill((209, 95, 238))

    clock = pygame.time.Clock()
    keepGoing = True

    pos = [0, 0]

    x = 40
    for line in range(5):
        y = 200
        for row in range(4):
            pygame.draw.rect(background, (238, 201, 0), (x, y, 40, 40), 0)
            y += 45
        x += 45

    board = [[1, 1, 3, 15, 11],
             [1, 14, 13, 15, 9],
             [2, 6, 7, 15, 5],
             [8, 10, 4, 12, 7]]

    myfont = pygame.font.SysFont("arial", 50)

    while keepGoing:
        clock.tick(30)

        y = 200
        x = 40
        x1 = 40
        x2 = 80
        y1 = 200
        y2 = 240
        num = 0
        label = myfont.render(str(num),1,(255,255,255))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                print pygame.mouse.get_pos()
                for row in range(4):
                    for line in range(5):
                        if pos[0] >= x1 and pos[0] <= x2 and pos[1] >= y1 and pos[1] <= y2:
                            pygame.draw.rect(background, (0,0,0), (x,y,40,40), 0)
                            num = board[row][line]
                            label = myfont.render(str(num), 1, (255,255,255))
                            x1 += 45
                        else:
                            x1 += 45
                            x2 += 45
                            x += 45
                    x = 40
                    y += 45
                    y1 += 45
                    y2 += 45
                    x1 = 40
                    x2 = 80

        screen.blit(label,(200,200))         
        screen.blit(background, (0,0))
        pygame.display.flip()

    pygame.quit()

出于某种我无法弄清楚的原因,无论我做什么,none 的字体内容都会打印出来。我尝试仅在循环外声明它,我尝试仅在循环内声明它,我同时尝试了这两种方法,但由于某种原因什么都不起作用,而且我无法弄清楚为什么我的文本拒绝在屏幕上打印。请帮忙?

我的老师说这与我的 x1 和 x2 变量有关,但我检查了一下,它们正在做它们应该做的事情。

(对于任何想知道的人,即使 if 中的语句为真,我将 45 添加到 x1 的原因是因为这样它不会继续重复并一次又一次地打印出数字,直到 for 循环是结束了。这不是最好的解决方案,但我能想到的唯一解决方案。)

就在使用 pygame.display.flip 更新屏幕之前,您的代码运行 screen.blit(background,(0,0)),这将完全覆盖您在屏幕上绘制的所有内容。将背景的 blitting 移动到 while keepGoing 循环的开头可以解决这个问题。