How to create an empty PyGame window?


PyGame

Pygame is a Python library used to develop games and multimedia applications. It provides functionality for handling user input, graphics, sound, and other multimedia-related tasks.

Pygame is built on the SDL (Simple DirectMedia Layer) library, providing low-level access to audio, keyboard, mouse, joystick, and graphics hardware. Pygame provides a high-level interface to SDL, making it easier to use for Python developers.

With Pygame, developers can create 2D games, arcade-style games, educational games, simulations, and other multimedia applications. Pygame provides a set of modules for handling graphics, audio, input, and other game-related tasks. It also includes tools for working with image and sound files and building game menus and interfaces.

Pygame is open-source and available under the LGPL (Lesser General Public License) or GPL (General Public License). It can be installed using pip, the Python package manager, or downloaded directly from the Pygame website.

Installing PyGame

To Install Pygame, you can Follow These Steps

  • Step 1 − Make sure that you have Python installed on your system. Pygame works with Python versions 3.5 and above. You can download Python from the official website (https://www.python.org/downloads/).

  • Step 1 − Open a terminal/command prompt window.

  • Step 2 − Install Pygame using pip by typing the following command and pressing Enter −

pip install pygame
  • Step 3 − Wait for the installation to complete. It may take a few minutes, depending on your internet speed.

  • Step 4 − Test it by importing pygame inside code. If you don't see any error messages, Pygame is successfully installed on your system.

Note − Depending on your operating system, you may need to install additional libraries or packages for Pygame to work properly. Check the Pygame documentation for more information on specific requirements for your system.

PyGame Window

Syntax

Users can follow the syntax below to create an empty PyGame window.

import pygame
pygame.init()
size = (800, 600)  # Width, Height
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Pygame Window")

To Create an Empty Pygame Window, you can Follow These Steps

  • After importing pygame, initialize it by calling the pygame.init() function.This function initializes all the Pygame modules and should be called before any other Pygame functions.

  • Set the size of the window by creating a tuple with the width and height in pixels.

  • Create the Pygame window by calling the pygame.display.set_mode() function, passing in size tuple as an argument. This function creates a new Pygame window with the specified size.

  • Set the title of the window by calling the pygame.display.set_caption() function. This function sets the title of the window to the specified string.

  • Game loop: Finally, you need to set up a game loop that will keep the window open.

  • The game loop should contain the following code. This loop runs indefinitely until the user closes the window by clicking the close button or pressing Alt+F4.

When you run this code, you should see an empty Pygame window with the title "My Pygame Window".

Example1

This program creates a Pygame window and includes a main game loop that handles events, draws circles, rectangles, and lines using Pygame's built-in drawing functions, and updates the window. You can modify the arguments of the pygame.draw.circle(), pygame.draw.rect(), and pygame.draw.line() functions to change the position, size, color, and thickness of the shapes.

import pygame
pygame.init()

window_size = (800, 600)
window = pygame.display.set_mode(window_size)
pygame.display.set_caption("My Pygame Window")

running = True
while running:
   # Handle events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False
    
   # Draw shapes
   window.fill((255, 255, 255))
   pygame.draw.circle(window, (255, 0, 0), (150, 200), 50)
   pygame.draw.rect(window, (0, 200, 0), (100, 300, 300, 200))
   pygame.draw.line(window, (0, 0, 100), (100, 100), (700, 500), 5)
    
   pygame.display.flip()
pygame.quit()

Output

Example2

This program creates a Pygame window and adds a button with a white rectangular shape, a black text label, and a hovering effect that changes the button colour when the mouse cursor is over the button area. The program also handles mouse events to detect when the button is clicked and prints a message to the console. You can modify the properties of the button_rect, button_font, and button_text objects to change the position, size, colour, font, and label of the button. Also, it displays a clock that shows the elapsed time in seconds since the program started.

The program also limits the frame rate to 60 FPS using Pygame's Clock object. You can modify the font size, color, and position of the clock text by changing the properties of the clock_font and clock_text_rect objects.

import pygame
pygame.init()

window_size = (800, 600)
window = pygame.display.set_mode(window_size)
pygame.display.set_caption("My Pygame Window")

# Define button properties
button_color = (255, 255, 255)
button_hover_color = (200, 200, 200)
button_rect = pygame.Rect(300, 250, 200, 100)
button_font = pygame.font.SysFont(None, 36)
button_text = button_font.render("Click me!", True, (0, 0, 0))
button_text_rect = button_text.get_rect(center=button_rect.center)

# Initialize Pygame clock
clock = pygame.time.Clock()

running = True
while running:
   # Limit the frame rate to 60 FPS
   clock.tick(60)
    
   # Handle events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False
        
      # Handle mouse events
      if event.type == pygame.MOUSEBUTTONDOWN:
         mouse_pos = pygame.mouse.get_pos()
         if button_rect.collidepoint(mouse_pos):
            print("Button clicked!")
        
      if event.type == pygame.MOUSEMOTION:
         mouse_pos = pygame.mouse.get_pos()
         if button_rect.collidepoint(mouse_pos):
            button_color = button_hover_color
         else:
            button_color = (255, 255, 255)
    
   # Draw button and clock
   window.fill((128, 128, 128))
   pygame.draw.rect(window, button_color, button_rect)
   window.blit(button_text, button_text_rect)
   current_time = pygame.time.get_ticks()
   clock_text = button_font.render(f"Time: {current_time/1000:.2f} s", True, (255, 255, 255))
   clock_text_rect = clock_text.get_rect(topright=(780, 10))
   window.blit(clock_text, clock_text_rect)
    
   pygame.display.flip()
pygame.quit()

Output

Conclusion

In this tutorial, we learned about PyGame, how to install PyGame, and how to create an empty PyGame window using the code. We learned how to draw shapes in the example2

and we also learned how to add buttons and a clock in example 3.

Updated on: 11-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements