How to make a program run inside a pygame window?

Asked

Viewed 748 times

1

I made a window using pygame, and I have a code that I wanted to run inside it, but I don’t know how to do that, if anyone can help I’m very grateful.

Here the window code:

pygame.init()
tela = pygame.display.set_mode([500, 400])
pygame.display.set_caption('Redenção')
relogio = pygame.time.Clock()
cor_branca = (255,255,255)
cor_azul = (108, 194, 236)

sair = False

while sair != True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sair = True
    relogio.tick(27)
    tela.fill(cor_azul)
    pygame.display.update()

pygame.quit()

and here’s the code I want to run inside the window:

def intro():

    print("▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄\n")
    print("Durante a 3ª guerra mundial, que explodiu no dia 12 de março do ano 2065 entre as nações mundiais...\n")
    time.sleep(5)
    print("A OTAN das quais fazem parte EUA, Europa ocidental e mais alguns países da parte oriental, como Austrália,\n"
          "Japão e Coreia do Sul, entrou em conflito com o B.R.C.I.S a aliança entre Brasil, Rússia, China,\n"
          "Índia e Africa do Sul.\n")
    time.sleep(5)
    print("Como consequência, a fome se espalhou pelo mundo, as intrigas entre as nações aumentaram,\n"
          "surgiram agitações nas grandes cidades e o que todos temiam, a caixa de Pandora foi aberta, as terrivéis\n"
          "bombas atômicas começaram espalhar seu terror pelo mundo...\n")
    time.sleep(5)
    print(
        "O Brasil, por possuir um vasto território e abundantes recursos naturais, se tornou um alvo fácil para as\n"
        "maiores potências mundiais, os países da OTAN temendo uma escassez completa, iniciaram um invasão pelo\n"
        "norte do país, com a intenção de dominar toda a nação e explorar sua grande extensão cultivável...\n")
    time.sleep(6)
    print("O B.R.C.I.S começou um contra-ataque ao saber que o Brasil estava sendo atacado, adentraram o Brasil,\n"
          "inciando pelos estados do nordeste e começam um bombardeio contra a OTAN....\n")
    time.sleep(5)
    print("No dia 25 de novembro de 1965, as nações já se encontravam exaustas em consequência da guerra, veem como\n"
          "última solução, usar as mortais G-BOMBS e o Brasil se torna um cenário de devastação, com milhares de\n"
          "mortos e cidades destruídas.\n")
    time.sleep(5)
    print("Nesse inferno na terra, você é um dos poucos sobreviventes em meio ao caos e irá com o restante das suas\n")
  • And what is the expected result? Each string appearing after a certain time? Could you review the indentation of your codes in the question? There seems to be a lot wrong and it is fundamental to the correct understanding of your code.

  • It was time to paste, the code got messy, it would be better to put a picture?

  • exactly as you quoted, each string appearing in the window consecutively after the given time.

  • No, just format it correctly in your editor, paste it here in Sopt, select all the code and press Ctrl+K.

  • Thank you, I’ll do it to improve understanding.

1 answer

1


Pygame gives you a window to draw, and some drawing primitives.

There’s no easy way to put text inside a pygame window - and terminal output techniques, where text scrolls up automatically don’t mix with the API pygame provides.

How to put text in a pygame window has 3 steps:

  1. creates a Font object, where you choose the font itself (typeface and size)
  2. creates a Surface with the written text. In this step you provide the characters you want to write on the screen and the desired color - it returns a rectangle with the drawn text and transparent background.
  3. You "stamp" (method .blit) this text drawn in a screen position.

If the text is to change position (because more text appeared below and the existing text needs to be pushed up), you have to delete the screen, and repeat steps 2-3 for the text that was already there.

There is an extra problem that does not appear there: pgame does not break line automatic to text - it renders a line. If the maximum width of the text in your game window is 40 or 80 characters, you have to break the text into pieces of the appropriate size and generate rectangles with each row, and paste in the right place.

Here is the example in code to put a "Hello world" on the screen with pygame:

import pygame
screen = pygame.display.set_mode((800, 600))
pygame.font.init()
font1 = pygame.font.Font(None, 150)
text = font1.render("Alô Mundo", True, (255, 255, 255))
screen.blit(text, (0, 200))
pygame.display.flip()

def principal():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               return
        pygame.time.delay(30)

principal() 

(The None in the call to pygame.font.Font makes pygame use a standard, serif-free font - it can be a path to any "ttf" type fotnes file (and maybe others))

All this is doable with programming, of course - but it’s a lot to do, and it’s between you and your game concept.

The best is to use an intermediate layer that allows text in pygame - there’s PGU (Phil’s Pygame Utilities) - it has no packages - but it’s easy to install right from github - https://github.com/parogers/pgu

It allows creating interfaces similar to window programs within the Pygame window - the concept is still different from the terminal,and will not only work with "print" and "Sleep" - but at least it can manage the presentation of the text for you.

https://github.com/parogers/pgu

There is a project of mine that is also the "mapengine" - it is very poorly documented, but has support for what I call "cut Scenes" - just scenes where you can write some text, and expect a user action, and switch to the next screen - I could easily adapt this "tell of history" there: https://github.com/jsbueno/mapengine/tree/master/mapengine

The mapengine supports a map larger than the screen, and "block" items like platform games - can serve well to develop some game you have in mind without having to do everything from scratch on top of the pygame. (and if you are going to use it, you can write to me so I can find any problems/add functionalities). There is an "examples" folder there.

  • Thank you very much!

  • you accepted the answer, and I hadn’t even finished yet - my hand slipped here and posted unintentionally. Have the suggestion to use the "PGU"

  • added an example code for a line of text

  • I asked for an answer and I won a class, thank you very much, it helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.