Pygame
Awesome links
Getting Started
Installing Pygame
Importing Pygame
import pygame
from pygame.locals import *
Initializing and Quitting
# Initialize Pygame
pygame.init()
# Quit Pygame
pygame.quit()
Creating a Game Window
Setting Up the Display
# Set up the game window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Game Title")
Main Game Loop
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
# Update game state
# Draw everything
pygame.display.update()
pygame.quit()
Drawing Shapes
Drawing a Rectangle
rect = pygame.Rect(x, y, width, height)
pygame.draw.rect(screen, (255, 0, 0), rect)
Drawing a Circle
pygame.draw.circle(screen, (0, 255, 0), (x, y), radius)
Drawing a Line
pygame.draw.line(screen, (0, 0, 255), (start_x, start_y), (end_x, end_y), width)
Handling Events
Event Types
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
print("Left mouse button clicked at", event.pos)
Working with Surfaces
Creating a Surface
surface = pygame.Surface((width, height))
Blitting a Surface
screen.blit(surface, (x, y))
Loading and Displaying Images
Loading an Image
image = pygame.image.load("path/to/image.png")
Displaying an Image
screen.blit(image, (x, y))
Playing Sounds
Loading a Sound
sound = pygame.mixer.Sound("path/to/sound.wav")
Playing a Sound
Loading and Playing Background Music
pygame.mixer.music.load("path/to/music.mp3")
pygame.mixer.music.play(-1) # -1 means loop indefinitely
Checking Key States
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
print("Left arrow key is pressed")
if keys[K_RIGHT]:
print("Right arrow key is pressed")
Getting Mouse Position
mouse_pos = pygame.mouse.get_pos()
print(mouse_pos)
mouse_buttons = pygame.mouse.get_pressed()
if mouse_buttons[0]: # Left mouse button
print("Left mouse button is pressed")
Fonts and Text
Creating a Font
font = pygame.font.Font(None, 36) # None for default font, 36 for font size
Rendering Text
text = font.render("Hello, Pygame!", True, (255, 255, 255)) # True for antialiasing
screen.blit(text, (x, y))
Setting Up the Clock
Creating a Clock
clock = pygame.time.Clock()
Limiting the Frame Rate
clock.tick(60) # Limit to 60 frames per second