如何在游戏窗口中显示“分数”?

1 投票
2 回答
3868 浏览
提问于 2025-04-17 04:51

在我的贪吃蛇游戏中,分数现在是在Python的命令行窗口里显示的。我想知道怎么才能把分数显示在游戏窗口里,这样游戏和分数就可以在同一个窗口里了?谢谢,Eric

while running:


    screen.fill((0, 0, 0))
    worm.move()
    worm.draw()
    food.draw()

    if worm.crashed:
        exit();
    elif worm.x <= 0 or worm.x >= w -1:
        running = False
    elif worm.y <= 0 or worm.y >= h-1:
        running = False
    elif worm.position() == food.position():
        score += 1
        worm.eat()
        print " score: %d" % score
        food = Food(screen)
    elif food.check(worm.x, worm.y):
        score += 1
        worm.eat()
        print "score: %d" % score
        food = Food(screen)
    elif running == False:
        exit();

    for event in pygame.event.get():
        if event.type == pygame.quit:
            running = False
        elif event.type == pygame.KEYDOWN:
            worm.event(event)

    pygame.display.flip()
    clock.tick(100)

补充-

while running:


screen.fill((0, 0, 0))
worm.move()
worm.draw()
food.draw()
pygame.font.init()
pygame.font.get_fonts() 

if worm.crashed:
    exit();
elif worm.x <= 0 or worm.x >= w -1:
    running = False
elif worm.y <= 0 or worm.y >= h-1:
    running = False

elif food.check(worm.x, worm.y):
    score += 1
    worm.eat()
    food = Food(screen)
    message = 'score: %d' % score
    font = pygame.font.Font(None, 40)
    text = font.render(message, 1, white)
    screen.blit(text, (50, 50))

elif running == False:
    exit();

for event in pygame.event.get():
    if event.type == pygame.quit:
        running = False
    elif event.type == pygame.KEYDOWN:
        worm.event(event)

为什么分数不显示呢?我没有收到任何错误提示。

2 个回答

1

关于你修改的内容:你只有在特定的情况下(也就是当虫子吃到食物的时候)才把文本显示到屏幕上。在下一帧时,你清空了屏幕,但食物不在了,所以分数就没有显示出来。你应该在每一帧都把分数显示到屏幕上,而不是只在特定情况下显示。

1

使用 font 模块可以在屏幕上显示字体。

来自用户指南:

white = (255, 255, 255)

message = 'your message'
font = pygame.font.Font(None, 40)
text = font.render(message, 1, white)
screen.blit(text, (x_position,y_position))

撰写回答