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àm | Mô tả | Tham số chính |
|---|---|---|
draw.line | Đường thẳng | surface, color, start_pos, end_pos, width |
draw.lines | Đường gãy | surface, color, closed, point_list, width |
draw.polygon | Đa giác | surface, color, point_list, width |
draw.arc | Cung tròn | surface, color, rect, start_angle, stop_angle, width |
draw.aaline | Đường thẳng anti-aliased | surface, 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ầndisplay.update()hoặcdisplay.flip()để hiện ra màn hình. - Vòng lặp while giữ cửa sổ mở và xử lý event.