You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pygame绘制Pac-Man风格的缺角黄色圆形精灵?

Pygame绘制带缺角的Pac-Man(吃豆人)图形

为什么pygame.draw.arc()不行?

pygame.draw.arc()不管width设多少,都只会绘制弧线轮廓,不会填充区域,所以用它做缺角填充是行不通的。下面给你两种简单易懂的实现方法:


方法一:直接绘制填充的缺角多边形(推荐)

思路是生成一个"带缺口的饼形"顶点列表,用多边形填充工具直接画出黄色吃豆人。

import pygame
import math

pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

# 吃豆人基础参数
center_pos = (200, 200)
pac_radius = 50
# 嘴巴的角度范围(30°到150°,可自行调整)
mouth_start = math.radians(30)  # 转成弧度(Pygame用弧度计算)
mouth_end = math.radians(150)

running = True
while running:
    screen.fill((0, 0, 0))  # 黑色背景

    # 生成缺角多边形的顶点
    polygon_points = [center_pos]  # 先加中心坐标
    # 从嘴巴结束角度往起始角度遍历,生成圆周上的点(间隔2°保证边缘平滑)
    current_angle = mouth_end
    while current_angle >= mouth_start:
        x = center_pos[0] + pac_radius * math.cos(current_angle)
        y = center_pos[1] + pac_radius * math.sin(current_angle)
        polygon_points.append((x, y))
        current_angle -= math.radians(2)

    # 填充黄色的吃豆人
    pygame.draw.polygon(screen, (255, 255, 0), polygon_points)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

方法二:遮罩法(先画圆再盖缺角)

先画完整的黄色圆形,再用背景色(或黑色)画一个填充扇形盖住部分区域,形成缺角:

import pygame
import math

pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

center_pos = (200, 200)
pac_radius = 50
mouth_start = math.radians(30)
mouth_end = math.radians(150)

running = True
while running:
    screen.fill((0, 0, 0))

    # 先画完整的黄色圆形
    pygame.draw.circle(screen, (255, 255, 0), center_pos, pac_radius)
    # 生成扇形顶点,用背景色填充盖住形成缺角
    mask_points = [center_pos]
    current_angle = mouth_start
    while current_angle <= mouth_end:
        x = center_pos[0] + pac_radius * math.cos(current_angle)
        y = center_pos[1] + pac_radius * math.sin(current_angle)
        mask_points.append((x, y))
        current_angle += math.radians(2)
    pygame.draw.polygon(screen, (0, 0, 0), mask_points)

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

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

额外小技巧

如果想让吃豆人嘴巴动起来,只要在循环里动态调整mouth_start和mouth_end的值就行,比如:

# 示例:让嘴巴慢慢张开再合上
mouth_angle = 30 + math.sin(pygame.time.get_ticks()/500) * 20
mouth_start = math.radians(90 - mouth_angle)
mouth_end = math.radians(90 + mouth_angle)

内容的提问来源于stack exchange,提问作者José LEBRUN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:52:46