glad0s
glad0s

Reputation: 11

How to not let text overlap each other in pygame?

i have two text examples, but they just appear on top of each other. how do i make it so that the second one replaces the first?

if player_x_coor <= -2750:
        text = font.render("text 1", True, WHITE)
        screen.blit(text, [100, 150])

if player_x_coor <= -6310:
        text = font.render("text 2", True, WHITE)
        screen.blit(text, [100, 150])

as you can see, I tried to replace the first text with the second text by assigning text = font.render("text 2", ...)

but the first test still shows so that the second overlaps with it.

Upvotes: 1

Views: 787

Answers (2)

francium
francium

Reputation: 2480

When you draw onto the screen, everything that is already there doesn't clear on its own. You have to blank the screen using some color, let's say black. Once the screen is clear of previous frame, you can redraw each object from bottom to top.

It is possible, if say you have a simple square underneath the text you're trying to replace, to just draw that square (instead of redrawing whole screen), and then draw new text. But this becomes more complicated if you're not dealing with a small number of trival shapes.

In general, a game loop is used to redraw the frame x times a second. The pattern is as follows:

def game_loop():
    BLACK = (0, 0, 0)

    while True:
        # Do this loop, at maximum, 50 times a second
        clock.tick(50)

        # Clear screen
        screen.fill(BLACK)
        # Draw background
        #      characters
        #      user interface

        # Get user input

Upvotes: 2

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

You need to erase the first text before writing another.

See this similar questions here and here.

I think there are many ways to do what you want. The best way could be:

  • copy the current surface (without text) in a cache
  • render the text
  • blit the text in your cached surface

Upvotes: -1

Related Questions