Trong bài viết này, tôi sẽ chia sẻ quy trình thiết kế game level sử dụng hai mô hình AI mạnh mẽ nhất hiện nay: Stable Diffusion 3 để sinh hình ảnh và GPT-4o để lập kế hoạch nội dung. Đây là workflow tôi đã thực chiến trong 6 tháng qua tại dự án game indie của team, giúp giảm 70% thời gian thiết kế level.
Kịch bản lỗi thực tế: ConnectionError timeout khiến deadline trễ 3 ngày
Tôi vẫn nhớ rõ buổi tối deadline production. Mọi thứ đã sẵn sàng, nhưng khi gọi API để sinh 50 hình ảnh terrain cho level 5, tôi nhận được:
Traceback (most recent call last):
File "level_generator.py", line 87, in generate_terrain_batch
response = client.images.generate(
File "httpx/_client.py", line 1254, in generate
model=model, timeout=Timeout(30.0, connect=5.0)
httpx.ConnectTimeout: Connection timeout exceeded (30s)
Status: 504 Gateway Timeout
Retry attempt 1/3...
Lỗi này xảy ra vì API gốc có rate limit cực kỳ nghiêm ngặt. Sau 3 lần retry thất bại, tôi phải chuyển sang HolySheheep AI — nơi tôi có thể gọi cùng API endpoint nhưng với latency trung bình chỉ <50ms thay vì 3-5 giây như trước. Từ đó, tôi xây dựng hoàn chỉnh pipeline tự động hóa sinh game level.
Tổng quan kiến trúc Dual-Model Pipeline
Quy trình hoạt động theo 4 giai đoạn chính:
- Giai đoạn 1: GPT-4o phân tích yêu cầu game design → xuất ra level blueprint
- Giai đoạn 2: GPT-4o tạo prompt cho Stable Diffusion 3 dựa trên blueprint
- Giai đoạn 3: Stable Diffusion 3 sinh hình ảnh terrain, NPC, items
- Giai đoạn 4: GPT-4o đánh giá chất lượng và tối ưu nếu cần
Triển khai chi tiết với HolySheep AI API
Bước 1: Cài đặt và cấu hình Client
# Cài đặt thư viện cần thiết
pip install openai httpx pillow asyncio aiohttp
File: config.py
import os
from openai import OpenAI
⚠️ Sử dụng HolySheep AI - KHÔNG dùng api.openai.com
Tiết kiệm 85%+ chi phí: GPT-4o chỉ $8/MTok vs $60/MTok chính hãng
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Thay bằng key của bạn
client = OpenAI(
base_url=HOLYSHEEP_BASE_URL,
api_key=API_KEY,
timeout=60.0,
max_retries=3
)
Cấu hình model
TEXT_MODEL = "gpt-4o" # $8/MTok - rẻ hơn 88% so với $60
IMAGE_MODEL = "stable-diffusion-3" # Model mới nhất
Bước 2: Module phân tích Game Design với GPT-4o
# File: game_designer.py
import json
from typing import Dict, List, Optional
class GameLevelDesigner:
"""GPT-4o phân tích và tạo level blueprint"""
def __init__(self, client):
self.client = client
async def generate_level_blueprint(
self,
game_theme: str,
difficulty: str,
level_number: int
) -> Dict:
"""
Phân tích yêu cầu và xuất blueprint chi tiết cho level
Returns: Dictionary chứa terrain, enemies, items, obstacles
"""
system_prompt = """Bạn là Game Designer chuyên nghiệp với 10 năm kinh nghiệm.
Nhiệm vụ: Tạo blueprint chi tiết cho game level với:
- Terrain type và đặc điểm
- Enemy placement và behavior
- Item placement và rarity
- Puzzle/obstacle design
- Difficulty curve
Output format: JSON với cấu trúc rõ ràng"""
user_prompt = f"""Thiết kế Level {level_number} cho game {game_theme}
Độ khó: {difficulty}
Yêu cầu:
1. Mô tả terrain chính (rừng, sa mạc, dungeon...)
2. Danh sách enemies (tên, số lượng, vị trí)
3. Items và power-ups
4. Obstacles và puzzles
5. Suggested color palette cho hình ảnh
6. Generation prompt cho Stable Diffusion"""
response = self.client.chat.completions.create(
model="gpt-4o", # $8/MTok - tiết kiệm 85%+
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.7,
max_tokens=2000
)
blueprint = json.loads(response.choices[0].message.content)
return blueprint
async def create_sd3_prompt(self, blueprint: Dict) -> str:
"""Tạo optimized prompt cho Stable Diffusion 3"""
prompt_template = """Create a game level illustration for {theme}:
Main elements:
- Terrain: {terrain}
- Color scheme: {colors}
- Atmosphere: {mood}
Style requirements:
- Top-down view or isometric perspective
- Clean, game-ready assets
- High contrast for visibility
- {difficulty} difficulty visual cues
Technical specs:
- Aspect ratio: 16:9
- Detailed enough for game reference
- Include layer information for sprite separation"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Bạn là expert prompt engineer cho Stable Diffusion 3"},
{"role": "user", "content": f"Tạo prompt tối ưu cho SD3 từ blueprint: {json.dumps(blueprint)}"}
],
temperature=0.8
)
return response.choices[0].message.content