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

Pygame循环创建Sword类实例所有对象均被绘制到同一位置问题咨询

问题原因

你在循环外仅创建了1个Rect实例,Python中可变对象是引用传递,你把同一个rect对象传入所有Sword类实例时,所有实例的self.rect都指向内存里的同一个Rect对象。每次循环修改self.rect.x,self.rect.y时,本质都是修改同一个对象的属性,最后一次循环赋值为(300,300)后,所有实例关联的rect属性都变成了这个坐标,因此渲染时所有对象都在同一个位置。

解决方法

两种修改方案任选其一即可:

  • 方案1:在循环内部给每个Sword实例单独创建新的Rect对象,不要复用循环外的同一个rect
    示例代码:
    extend = []#object array
    liste = [100,200,300]#object points x and y    
    image= pygame.image.load('sword.png')
    # 移除循环外创建rect的代码,放到循环内部
    for i in range(3):
        rect = image.get_rect() # 每次生成全新的Rect实例
        extend.append(Sword(image,rect,1,(liste[i],liste[i])))
    
    while True:
        for tile in extend:
            tile.draw(display)
    
  • 方案2:在Sword类的__init__方法里对接收到的rect做拷贝,避免所有实例共享同一个对象
    示例代码:
    class Sword():
        def __init__(self, image, rect, speed, center):
            self.image = image
            self.rect = rect.copy() # 对传入的rect做拷贝,生成新的Rect实例
            self.rect.x,self.rect.y = center #set x and y position
            self.speed = speed
            self.alive = True
    
        def live(self, enemy): #check if the image touches any object
            if self.rect.colliderect(enemy):
                self.alive = False
                mixer.music.play()
    
        def update(self): #move object
            self.rect.x += self.speed
    
        def draw(self, surface): #display object
           if self.alive:
                surface.blit(self.image, (self.rect))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:51:02