How to make a program run inside a pygame window?

1

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

Here is 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 is the code I want it 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")
    
asked by anonymous 21.11.2018 / 17:39

1 answer

1

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

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

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

  • creates a Source object, where you choose the font itself (typeface and size)
  • creates Surface with 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 text drawn and background transparent.
  • You "stamp" (method .blit ) this text drawn in a position on the screen.
  • If the text changes position (because more text appeared underneath and existing text needs to be pushed up), you have to erase 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 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 line, and paste it in the right place.

    Here's 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() 
    

    ( None in call to pygame.font.Font makes pygame use a default, non-serif font - can be a path to any "ttf" (and perhaps others)

    This is all possible with programming, of course - but it's a lot to do, and it's between you and your game concept.

    It is best to use an intermediate layer that allows text in the pygame - it has the PGU (Phil's Pygame Utilities) - it does not have packages - but it is easy to install downloading directly from github - link

    It allows the creation of interfaces similar to those of the window programs inside 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.

    link

    There is a project of mine that is also the "mapengine" - it is very little documented, but it has support for what I call "cut scenes" - just scenes in which you can write some text and wait for user action, and change to the next screen - you could easily adapt this "story story" there: link

    The mapengine has support for a map larger than the screen, and "block" items like platform games - may well serve to develop some game you have in mind without having to do everything from scratch on top of pygame. (and if you use it, you can write me to fix any problems / add features). It has a "examples" folder there.

        
    22.11.2018 / 13:39