Nội dung bài họcLesson content
Pygame Zero là gì?What is Pygame Zero?
Pygame Zero (pgzero) là thư viện Python dành cho người mới bắt đầu làm game. Đơn giản hơn Pygame gốc. Có sẵn: sprite (Actor), âm thanh, va chạm, chuột, bàn phím. Cài đặt: pip install pgzero. Chạy: pgzrun ten_file.py.Pygame Zero (pgzero) is a Python library for beginners making games. Simpler than original Pygame. Includes: sprites (Actor), sounds, collision, mouse, keyboard. Install: pip install pgzero. Run: pgzrun filename.py.
Actor: nhân vật gameActor: game character
Actor là sprite trong Pygame Zero. Tạo: player = Actor("player"). Đặt vị trí: player.x = 400, player.y = 300. Di chuyển: player.x += 5. Vẽ: player.draw(). Hình ảnh đặt trong thư mục images/.Actor is a sprite in Pygame Zero. Create: player = Actor("player"). Set position: player.x = 400, player.y = 300. Move: player.x += 5. Draw: player.draw(). Images go in the images/ directory.
from pgzero.actor import Actor
player = Actor("player")
player.x = 400
player.y = 300
def draw():
screen.fill((0, 0, 0)) # Nền đen
player.draw()
def update():
if keyboard.left:
player.x -= 5
if keyboard.right:
player.x += 5
Hàm draw() và update()The draw() and update() functions
Pygame Zero có 2 hàm đặc biệt: draw() vẽ mọi thứ lên màn hình (chạy 60 lần/giây), update() cập nhật logic game (chạy 60 lần/giây). draw() luôn bắt đầu bằng screen.fill() để xóa khung cũ. update() di chuyển sprite, kiểm tra va chạm.Pygame Zero has 2 special functions: draw() draws everything to the screen (runs 60 times/second), update() updates game logic (runs 60 times/second). draw() always starts with screen.fill() to clear the old frame. update() moves sprites, checks collisions.
Va chạm trong Pygame ZeroCollision in Pygame Zero
Dùng actor.colliderect(other_actor) để kiểm tra va chạm giữa 2 Actor. Trả về True nếu chạm, False nếu không. Dùng trong update(): if player.colliderize(coin): tăng điểm + di chuyển coin đi nơi khác.Use actor.colliderect(other_actor) to check collision between 2 Actors. Returns True if touching, False if not. Use in update(): if player.colliderect(coin): increase score + move coin elsewhere.
coin = Actor("coin")
coin.x = 200
coin.y = 200
diem = 0
def update():
if keyboard.left:
player.x -= 5
if player.colliderect(coin):
diem += 1
coin.x = random.randint(0, 800)
coin.y = random.randint(0, 600)
def draw():
screen.fill((0, 0, 0))
player.draw()
coin.draw()
screen.draw.text(f"Điểm: {diem}", (10, 10), color="white")