How to make a program run inside a window in pygame?

I made a window using pygame, and I have a code that wanted it to run inside it, but I don't know how to do it, 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")
Author: jsbueno, 2018-11-21

1 answers

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

Doesn't have an easy way to put text inside a pygame window - and terminal output techniques, where text automatically scrolls upwards, don't mix in the least with the API pygame provides.

The way to put text in a pygame window has 3 Steps:

  1. creates a font object, where you choose the font itself (typeface and the 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 you a rectangle with the drawn text and transparent background.
  3. you "stamp" (method .blit) that drawn text in a position on the screen.

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

Has an extra problem that doesn't show up there: pgame doesn't do line breaking automatic for 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 code example 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 the pygame use a standard, non-serif font-it can be a path to any fotnes file of type "ttf" (and maybe others))

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

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

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

Https://github.com/parogers/pgu

Has a project of mine also that is the "mapengine" - it is very little documented, but it has support for what I call "cut scenes" - precisely scenes in which it gives to write some text, and wait for a user action, and switch to the next screen-I would easily adapt this "story telling" there: https://github.com/jsbueno/mapengine/tree/master/mapengine

Mapengine has support for a map larger than the screen, and "block" items like platform games - it can serve well to develop some game you have in mind without having to do everything from scratch on top of pygame. (and if it is to use, you can write to me to tidy up problems / add features). There's an "examples" folder there.

 1
Author: jsbueno, 2018-11-22 13:13:31