Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ hình học trên cửa sổ Pygame Python

Mô tả

Pygame là thư viện multimedia/game cho Python. Demo vẽ các hình cơ bản: hình tròn, elip, chữ nhật.

Code hoàn chỉnh

import pygame

# Khởi tạo
pygame.init()

# Màu sắc (R, G, B)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 150)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# Kích thước cửa sổ
X, Y = 400, 400
display_surface = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Drawing Shapes')

# Fill nền
display_surface.fill(WHITE)

# 1. Vẽ hình tròn: draw.circle(surface, color, center, radius, width=0)
# width=0: fill, width>0: độ dày viền
pygame.draw.circle(display_surface, BLACK, (300, 250), 80, 0)

# 2. Vẽ elip: draw.ellipse(surface, color, rect, width=1)
# rect = (x, y, width, height) - bounding rectangle
pygame.draw.ellipse(display_surface, RED, (50, 200, 100, 150), 4)

# 3. Vẽ chữ nhật: draw.rect(surface, color, rect, width=0)
pygame.draw.rect(display_surface, BLUE, (50, 50, 150, 100))

# Vòng lặp chính
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    pygame.display.update()

pygame.quit()

Các hàm vẽ phổ biến khác

HàmMô tảTham số chính
draw.lineĐường thẳngsurface, color, start_pos, end_pos, width
draw.linesĐường gãysurface, color, closed, point_list, width
draw.polygonĐa giácsurface, color, point_list, width
draw.arcCung trònsurface, color, rect, start_angle, stop_angle, width
draw.aalineĐường thẳng anti-aliasedsurface, color, start_pos, end_pos

Mở rộng: Vẽ text (font)

font = pygame.font.Font(None, 36)  # None = default font
text = font.render("Hello Pygame", True, BLACK)
display_surface.blit(text, (100, 100))

Lưu ý

  • Tọa độ (0,0) ở góc trên-trái.
  • Mọi vẽ đều lên Surface, cần display.update() hoặc display.flip() để hiện ra màn hình.
  • Vòng lặp while giữ cửa sổ mở và xử lý event.