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

如何在Pygame中创建斜菱形(Rhomboid)

如何在Pygame中绘制斜菱形

你当前代码绘制的是正菱形(顶点关于中心对称),要实现斜菱形可以用两种方式:


方法1:手动定义斜顶点坐标

直接调整四个顶点的位置,打破横竖方向的对称,就能得到斜菱形。修改后的代码示例:

import pygame as pg
pg.init()
screen = pg.display.set_mode((500, 700))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
# 调整为斜菱形顶点
points = [(180, 200), (250, 230), (220, 300), (150, 270)]
done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
    screen.fill(BG_COLOR)
    pg.draw.polygon(screen, BLUE, points)
    pg.display.flip()
    clock.tick(60)

你可以根据需求微调每个坐标的数值,直到得到理想的倾斜角度。


方法2:通过旋转正菱形实现

如果需要灵活调整倾斜角度,更高效的方式是先绘制正菱形到独立Surface,再对Surface进行旋转,最后绘制到主屏幕:

import pygame as pg
pg.init()
screen = pg.display.set_mode((500, 700))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')

# 创建透明Surface绘制正菱形
diamond_surf = pg.Surface((100, 100), pg.SRCALPHA)
diamond_points = [(50, 0), (100, 50), (50, 100), (0, 50)]
pg.draw.polygon(diamond_surf, BLUE, diamond_points)

# 旋转Surface(20为倾斜角度,可自由修改)
rotated_surf = pg.transform.rotate(diamond_surf, 20)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
    screen.fill(BG_COLOR)
    # 将旋转后的菱形绘制到屏幕指定位置
    screen.blit(rotated_surf, (150, 200))
    pg.display.flip()
    clock.tick(60)

这种方法的优势是可以通过修改rotate的第二个参数快速调整倾斜角度,无需手动计算每个顶点坐标。

内容的提问来源于stack exchange,提问作者ALex Break

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:45:34