2

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)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Derick Kolln
  • 633
  • 7
  • 17

2 Answers2

2

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))


    # [...]

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • hey man, how can I solve this problem if i wanna push a button to make this function work? – Derick Kolln Jun 05 '19 at 14:28
  • 1
    @DerickKolln Don't start the timer before the main loop. Start the timer when the button is pressed. The button covers a rectangular area with a position (x, y) and a size (w, h). Use [`b = pygame.Rect(x, y, w, h)`](https://www.pygame.org/docs/ref/rect.html) and `if event.type == pygame.MOUSEBUTTONDOWN and b.rect.collidepoint(event.pos):` `pygame.time.set_timer(mytimerevent, 1000)`. See also [Call function by button click in Pygame](https://stackoverflow.com/questions/56160746/call-function-by-button-click-in-pygame). – Rabbid76 Jun 05 '19 at 19:08
1

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))
Omegastick
  • 1,773
  • 1
  • 20
  • 35