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

Pygame开发蓝色方块跟随红色方块功能时无法后退问题求助

问题根因

pygame.Rect 类的坐标属性(x、y)仅支持整数类型,你设置的蓝色方块移动速度velBlue=0.5为浮点数,每次加减操作后的小数部分会被自动截断丢弃,相当于位移未生效,当红蓝方块距离较小时就会出现无法移动、包括无法向后调整位置的现象。

修复方案

新增两个浮点型变量单独存储蓝色方块的精确坐标,位移计算先作用于浮点坐标,再同步更新到Rect对象即可:

  • 调整蓝色方块初始化逻辑,新增浮点坐标变量
  • 修改blueCircleMovement函数,优先更新浮点坐标再同步给Rect

修改后的完整代码

import pygame,sys
import random

#窗口配置
width=1600
height=800
window=pygame.display.set_mode((width,height))
pygame.display.set_caption("simulation")

black=(0,0,0)

#红色方块配置
redCircleCoords=(60, 60)
redCircleSize=(60, 60)
redCircle = pygame.Rect(redCircleCoords[0], redCircleCoords[1], redCircleSize[0], redCircleSize[1])
red=(255,0,0)
velRed=1

#蓝色方块配置
blueCircleSize=(60,60)
# 新增浮点型变量存储精确坐标
blue_x = float(width-120)
blue_y = float(height-120)
blueCircle=pygame.Rect(int(blue_x), int(blue_y), blueCircleSize[0], blueCircleSize[1])
blue=(0,0,255)
velBlue=0.5

def redCircleMovement():
    pressed=pygame.key.get_pressed()
    if pressed[pygame.K_a] and redCircle.x > 0: #左移
        redCircle.x-=velRed
    if pressed[pygame.K_d] and redCircle.x < width - 60: #右移
        redCircle.x+=velRed
    if pressed[pygame.K_s] and redCircle.y < height - 60: #下移
        redCircle.y+=velRed
    if pressed[pygame.K_w] and redCircle.y > 0: #上移
        redCircle.y-= velRed

def blueCircleMovement():
    global blue_x, blue_y
    # 先更新浮点坐标
    if redCircle.x > blue_x:
        blue_x += velBlue
    if redCircle.x < blue_x:
        blue_x -= velBlue
    if redCircle.y > blue_y:
        blue_y += velBlue
    if redCircle.y < blue_y:
        blue_y -= velBlue
    # 同步更新Rect的整数坐标
    blueCircle.x = int(blue_x)
    blueCircle.y = int(blue_y)
            
def draw():
    redCircleVector=(redCircle.x, redCircle.y)
    blueCircleVector=(blueCircle.x, blueCircle.y)
    print('red:',redCircleVector)
    print('blue:',blueCircleVector)
    window.fill(black) #填充黑色背景
    pygame.draw.rect(window, red, redCircle) #绘制红色方块
    pygame.draw.rect(window,blue,blueCircle) #绘制蓝色方块
    pygame.display.flip() #更新画面

def callFunctions():
    draw()
    redCircleMovement()
    blueCircleMovement()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    callFunctions()

内容的提问来源于stack exchange,提问作者Bob The Bean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:54:00