How to display dynamically in Pygame? [duplicate]

狂风中的少年 提交于 2021-02-04 07:41:27

问题


I am able to display a number "1" on my display. Now, my goal is to display the numbers 1...4. That means "1" is displayed first, then after 1 "2" is displayed, etc. How to solve that problem?

Here is my code:

import pygame
import time

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False

font = pygame.font.SysFont("comicsansms", 72)  
text = font.render("1", True, (0, 128, 0))

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True

    screen.fill((255, 255, 255))
    screen.blit(text,
                (320 - text.get_width() // 2, 240 - text.get_height() // 2))

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

回答1:


Create a counter and us str() to convert a value to a string:

counter = 1
text = font.render(str(counter), True, (0, 128, 0))

Add a timer event (see pygame.event) with a certain time interval. A timer event is started by pygame.time.set_timer()

mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 1000) # 1000 milliseconds = 1 socond 

Increment the counter and change the text on the event:

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True

        if event.type == mytimerevent: # timer event
            counter += 1
            text = font.render(str(counter), True, (0, 128, 0))


    # [...]




回答2:


Update text each frame like so:

# Setup stuff

number = 1
text = font.render(str(number), True, (0, 128, 0))

while not done:
    # Show stuff on screen

    number += 1
    text = font.render(str(number), True, (0, 128, 0))


来源:https://stackoverflow.com/questions/56453574/how-to-display-dynamically-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!