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

为何Pygame中矩形移动正常,改为圆形后仅t键控制的移动失效?

圆形移动失效的问题修复

问题根源

  1. 你误将pg.draw.circle()的返回值当作圆形的位置对象——实际上这个函数返回的是绘制区域的边界矩形,不是圆形的坐标数据,修改它的y值不会改变圆形的绘制位置。
  2. 循环里绘制圆形时始终使用固定坐标[300, 300],不管你怎么修改其他变量,圆形都会被画在初始位置。

修复方案

需要单独存储圆形的坐标,通过修改坐标值来实现移动:

  • 初始化时定义圆形的位置列表(列表可修改,元组不行):circ_pos = [300, 300]
  • 删除无效的circ = pg.draw.circle(...)初始化代码
  • 按键控制时修改坐标列表的y值:circ_pos[1] -= speed
  • 绘制圆形时传入这个坐标列表

修复后的完整代码

import pygame as pg

# 初始化屏幕
screen = pg.display.set_mode((500, 500))
# 时钟控制帧率
clock = pg.time.Clock()
# 矩形对象
rect = pg.Rect(200, 400, 100, 10)
# 存储圆形的位置坐标(用列表方便修改)
circ_pos = [300, 300]
speed = 6

done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
            
    # 玩家输入控制
    keys = pg.key.get_pressed()
    # 矩形移动控制
    if keys[pg.K_a] and not rect.x <= 0:
        rect.x -= speed
    if keys[pg.K_d] and not rect.x >= 400:
        rect.x += speed
    if keys[pg.K_s] and not rect.y >= 480:
        rect.y += speed
    if keys[pg.K_w] and not rect.y <= 320:
        rect.y -= speed
    # 圆形移动控制(修改坐标列表的y值)
    if keys[pg.K_t]:
        circ_pos[1] -= speed

    # 清空屏幕
    screen.fill((40, 40, 40))

    # 绘制图形
    pg.draw.rect(screen, (150, 200, 20), rect)
    pg.draw.circle(screen, (0, 255, 0), circ_pos, 10, 0)

    # 更新显示
    pg.display.flip()
    clock.tick(30)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:54:27