我想在Python中重新创建Game Fifteen,但我仍然坚持在二维上画板。我之前在C中做过这个,我尝试再次使用列表,如下所示:
numbers = d * d - 1
global blankx, blanky, board
blankx = d - 1
blanky = d - 1
for i in range(d):
for j in range(d):
board[i][j] = numbers
numbers -= 1
board[blankx][blanky] = d * d
其中d是尺寸,blankx和y是右下角空白区域的坐标。然而它说: '列出索引超出范围'在线路板[i] [j] =数字 我不明白为什么,有什么提示吗?
答案 0 :(得分:3)
在Python中,访问list
的索引不会自动将list
扩展到最小必需长度。您必须初始化空板,或者一起创建并填充它。我建议list
理解:
board = [[d*d-1-i-d*j for i in range(d)] for j in range(d)]
这相当于以下显式循环,它使用list
向每个append()
添加新项:
board = []
for i in range(d):
row = []
for j in range(d):
row.append(d*d-1-i-d*j)
board.append(row)
答案 1 :(得分:0)
board = [[i*d + j + 1 for i in range(d)] for j in range(d)]
board[blankx][blanky] = d * d