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

Python条件判断未按预期执行,游戏网格全部填充为1问题排查

问题根因

你的代码问题出在类属性、类实例的使用错误,核心问题如下:

  • 二维列表emptyBoard存储的是cell类本身而非类的实例:你写的[[cell for i in range(ROWS)] for k in range(COLS)]中直接引用了cell类,没有加()实例化,整个列表所有元素都指向同一个类对象,你修改任意元素的contents属性都是修改这个全局唯一的类属性,最后遍历到y>20的区域时,类属性被覆盖为1,自然整块棋盘都显示1。
  • cell类的属性定义为类属性:就算你实例化了cell,直接在类下定义的属性是所有实例共享的,修改时还是会出现全局同步变更的问题。
  • board类的cells是类属性且绑定了全局的emptyBoard:所有board实例会共享同一份棋盘数据,不符合常规使用逻辑。
修正后的代码
ROWS = 56 
COLS = 79

# put the cursor at position x,y on screen
def gotoxy(x,y):
    print ("%c[%d;%df" % (0x1B, y, x), end='')

# class for objects that populate the grid
class Cell:
    # 改为实例属性,每个实例单独持有属性
    def __init__(self):
        self.Xloc = 0
        self.Yloc = 0
        self.contents = 0

# class for the board
class Board:
    def __init__(self):
        # 实例初始化时单独生成棋盘,每个实例独立存储,每个元素是Cell的实例
        self.cells = [[Cell() for i in range(ROWS)] for k in range(COLS)]

    # function: write the board to the screen
    def dispBoard(self):
        for x in range(0,COLS):
            for y in range(0, ROWS):
                gotoxy(x,y)
                print (str(self.cells[x][y].contents)) 

    # function: fill the cells with 0s or 1s 
    def fillBoard(self):
        for x in range(0,COLS):
           for y in range(0, ROWS):
                self.cells[x][y].Xloc = x
                self.cells[x][y].Yloc = y
                self.cells[x][y].contents = 1 if y > 20 else 0

def main():    
    bord = Board()
    bord.fillBoard()
    bord.dispBoard()

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:54:07