2

I have a simple Pygame program:

#!/usr/bin/env python

import pygame
from pygame.locals import *

pygame.init()

win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")

But every time I try to run it, I get this:

pygame 2.0.0 (SDL 2.0.12, python 3.8.3)
Hello from the pygame community. https://www.pygame.org/contribute.html

And then nothing happens. Why I can't run this program?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Itay
  • 41
  • 5

2 Answers2

5

Your application works well. However, you haven't implemented an application loop:

import pygame
from pygame.locals import *

pygame.init()

win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()

run = True
while run:

    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update game objects
    # [...]

    # clear display
    win.fill((0, 0, 0))

    # draw game objects
    # [...]

    # update display
    pygame.display.flip()

    # limit frames per second
    clock.tick(60) 

pygame.quit()

The typical PyGame application loop has to:

repl.it/@Rabbid76/PyGame-MinimalApplicationLoop See also Event and application loop

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

This is interesting. Computer read your program line by line[python]. When all the line are interpreted, the program closed. To solve this problem you need to add a while loop to make sure the program will continue until you close the program.

import pygame,sys
from pygame.locals import *

pygame.init()

pygame.display.set_caption("My first game")
win = pygame.display.set_mode((400,400))

#game loop keeps the game running until you exit the game.
game_running=True
while game_running:
    for event in pygame.event.get():
        if event.type==QUIT:            
            pygame.quit()
            sys.exit()
    win.fill((0, 250, 154)) #Fill the pygame window with specific color. You can use hex or rgb color
    pygame.display.update() #Refresh the pygame window

You can check more pygame Examples. https://github.com/01one/Pygame-Examples I think this will be helpful.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
01one
  • 1
  • 2