python贪吃蛇游戏项目 pygame绘制图形与背景

import pygame
import sys

# 初始化 pygame
pygame.init()

# 画面大小
WIDTH, HEIGHT = 480, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Drawing Shapes")

# 设定字体(用于文字显示)
font = pygame.font.SysFont("Arial", 24)

# 颜色定义 (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE  = (0, 0, 255)


clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 背景颜色填充
    screen.fill((30, 30, 30))   # 深灰色背景

    # 绘制矩形 (rect)
    pygame.draw.rect(screen, RED, (50, 50, 120, 80))  
    # 参数 = surface, color, (x,y,width,height)

    # 绘制圆形 (circle)
    pygame.draw.circle(screen, GREEN, (300, 200), 50)
    # 参数 = surface, color, (center_x, center_y), radius

    # 绘制线条 (line)
    pygame.draw.line(screen, BLUE, (0, 0), (500, 400), 5)
    # 参数 = surface, color, start_pos, end_pos, width

    # 绘制文字
    text_surface = font.render("Hello Pygame!", True, WHITE)
    screen.blit(text_surface, (200, 20))

    # 更新画面
    pygame.display.flip()
    clock.tick(60)  # 限制 60 FPS

pygame.quit()
sys.exit()
功能 代码 用途
背景颜色 screen.fill((r,g,b)) 设定画面背景
矩形 pygame.draw.rect() 角色、地图砖块常用
圆形 pygame.draw.circle() 玩家/敌人原型测试
线条 pygame.draw.line() UI、路线可视化
文字 font.render() 显示分数、状态