on
ai 주식투자
- Get link
- X
- Other Apps
Pygame is a popular Python library for making games and multimedia applications. This tutorial will guide you through the basics.
Prerequisites:
Python: Make sure you have Python installed (version 3.7 or higher is recommended).
Pygame: Install Pygame using pip: pip install pygame
1.Setting up the Basic Window
Let's create a simple window. Create a new Python file (e.g., my_game.py) and add the following code:
import pygame
# Initialize Pygame
pygame.init()
# Set window dimensions
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
# Set window title
pygame.display.set_caption("My First Pygame Window")
# Game loop
running = True
while running:
# Event handling (check for quit event)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the screen with a color (e.g., white)
screen.fill((255, 255, 255)) # RGB values for white
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()@
# ... (event handling code from before) ...
screen.fill((255, 255, 255)) # Fill with white
# Draw a rectangle
pygame.draw.rect(screen, (255, 0, 0), (50, 50, 100, 50)) # Surface, color, (x, y, width, height)
pygame.display.flip()@import pygame
# Initialize Pygame
pygame.init()
# Set window dimensions
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
# Set window title
pygame.display.set_caption("Pygame Input Example")
# Rectangle properties
rect_x = 50
rect_y = 50
rect_width = 100
rect_height = 50
rect_speed = 5
# Game loop
running = True
while running:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
rect_x -= rect_speed
if event.key == pygame.K_RIGHT:
rect_x += rect_speed
if event.key == pygame.K_UP:
rect_y -= rect_speed
if event.key == pygame.K_DOWN:
rect_y += rect_speed
# Keep rectangle within bounds
rect_x = max(0, min(rect_x, width - rect_width))
rect_y = max(0, min(rect_y, height - rect_height))
# Fill the screen
screen.fill((255, 255, 255))
# Draw the rectangle
pygame.draw.rect(screen, (255, 0, 0), (rect_x, rect_y, rect_width, rect_height))
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()@
Comments
Post a Comment