English 中文(简体)
Pygame - Hello World
  • 时间:2024-11-03

Pygame - Hello World


Previous Page Next Page  

First step is to import and initiapze pygame modules with the help of init() function.


import pygame
pygame.init()

We now set up Pygame display window of preferred size, and give it a caption.


screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Hello World")

This will render a game window which needs to be put in an infinite event loop. All event objects generated by user interactions such as mouse movement and cpck etc. are stored in an event queue. We shall terminate the event loop when pygame.QUIT is intercepted. This event is generated when user cpcks the CLOSE button on the title bar.


while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()

Complete code for displaying Pygame window with Hello World caption is as follows −


import pygame, sys

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Hello World")
while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()
         sys.exit()

Save above script as hello.py and run to get following output −

Hello World

This window will be closed only if the close (X) button is cpcked.

Advertisements