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

如何在Python的Pygame中绘制虚线?乒乓游戏代码问题求助

解决Pygame乒乓游戏中间虚线绘制问题

你的虚线绘制代码无效的原因是:循环中i的取值是0, 40, 80, ..., 760(因为HEIGHT=800,HEIGHT//20=40),所有i都是偶数,i % 2 == 1的条件永远不成立,没有跳过任何矩形,最终画出来的是实心竖条,而非虚线。

修改方案:通过循环的索引来判断是否跳过绘制,而非i本身的值。修改后的draw函数如下:

def draw(win, paddles):
    win.fill(BLACK)
    for paddle in paddles:
        paddle.draw(win)

    segment_height = HEIGHT // 20
    # 用索引判断是否跳过,奇数索引不绘制
    for idx, i in enumerate(range(0, HEIGHT, segment_height)):
        if idx % 2 == 1:
            continue
        pygame.draw.rect(win, WHITE, (WIDTH//2 - 5, i, 10, segment_height))

    pygame.display.update()

替换这段代码后,就能在画面中间画出交替的虚线了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:15:48