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

pygame中如何调用字典键对应对象方法仅修改该对象属性

问题根源

  1. 字典绑定逻辑错误:你在_create_holes方法中使用嵌套循环给字典赋值,会导致所有hole键最终都对应counter_group的最后一个Counter实例。相当于所有圆形绑定的是同一个计数器,点击任意圆形修改的都是同一个计数器的值,自然所有位置显示的数值都会同步更新。
  2. 计数器位置逻辑冗余:Counter类的prep_counter方法写死了将计数器位置设置在屏幕右上角,虽然你后续在渲染时覆盖了位置,但会导致总计数器和单个圆形的计数器逻辑耦合。

修复方案

1. 修正圆形与计数器的绑定逻辑

修改dig_hole.py的_create_holes方法,删除冗余的嵌套循环,直接在创建每个计数器时与对应圆形绑定:

def _create_holes(self):
    for row_number in range(2):
        for hole_number in range(5):
            self._create_hole(row_number, hole_number)

    # 遍历holes列表,一一对应创建计数器并绑定
    for hole in self.holes:
        counter = Counter(self)
        counter.counter_rect.midbottom = hole.rect.midtop
        self.counter_group.append(counter)
        # 直接绑定当前hole和当前counter,不需要嵌套循环
        self.dict[hole] = counter

2. 优化计数器位置逻辑(可选)

修改counter.py的prep_counter方法,移除固定位置设置,避免重复赋值带来的性能损耗:

def prep_counter(self):
    counter_str = str(self.count_clock)
    self.counter_image = self.font.render(counter_str, True, self.text_color, self.settings.bg_color)
    self.counter_rect = self.counter_image.get_rect()

然后在DigHole类的__init__方法中,单独设置全局总计数器的位置:

def __init__(self):
    pygame.init()
    self.settings = Settings()

    self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
    pygame.display.set_caption("Dig Hole")
    pygame.display.set_icon(Hole(self).image)

    self.count = Counter(self)
    # 单独设置总计数器的位置到右上角
    screen_rect = self.screen.get_rect()
    self.count.counter_rect.right = screen_rect.right - 20
    self.count.counter_rect.top = 20
    self.counter_group = list()
    self.holes = list()

    self.dict = dict()

    self._create_holes()
    self.hole = Hole(self)

    self.mouse_pos = (0, 0)

额外优化

如果右上角的全局计数器是用来统计总点击次数,需要补充累加逻辑,同时添加break跳出循环减少不必要的遍历:

def _check_hole_clicked_events(self, mouse_pos):
    for key in self.dict:
        if key.rect.collidepoint(mouse_pos):
            self.dict[key].count_clock += 1
            self.dict[key].prep_counter()
            # 总计数器累加
            self.count.count_clock += 1
            self.count.prep_counter()
            # 匹配到点击的hole后直接跳出循环
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:36:04