我正在为一个类创建这个程序,当它运行这个文件时,网格的一角将无法完全填充:
我无法弄清楚我的问题在哪里。我的另一个问题是计算颜色“腔室”的数量,计数器保持数字大于总平方数。以下是我遇到的两个问题。任何想法都将不胜感激。
def fill(cave, row, col, color):
"""Fill a chamber of the cave with water, starting
at row, col. Water can spread in all four cardinal
directions, but cannot penetrate stone. No effect
if row or col are not inside the cave.
Attempting to pour water where there is already WATER or STONE
has no effect. Attempting to pour water outside the cavern has
no effect. Attempting to pour water in a cell containing AIR
not only places colored water in that cell, but also spreads it
in all directions by causing it to be poured in the cell to the
left and right and above and below.
Args:
cave: A matrix (list of lists) representing the cavern. Each
cell in the cave may hold AIR, STONE, or WATER.
row: Starting row of the grid cell where we pour water
col: Starting column of the grid cell where we pour water
color: color of the water we try to pour in.
"""
if cave[row][col] == AIR :
cave[row][col] = WATER
if row > len(cave) or col > len(cave):
grid.fill_cell(row, col, color)
return
if row < 0 or col < 0:
grid.fill_cell(row, col, color)
return
grid.fill_cell(row, col, color)
fill(cave, row+1, col, color)
fill(cave, row-1, col, color)
fill(cave, row, col+1, color)
fill(cave, row, col-1, color)
def main():
"""Reads a cave from a specified configuration file,
displays it, and fills each chamber with a different color
of water.
Args (from command line):
Cave description file, example, "cave.txt"
Usage: python3 cavern.py cave.txt
"""
desc = sys.argv[1]
cave = read_cave(desc)
dump_cave(cave) ## May be useful for debugging
display(cave)
chambers = 0
for row in range( len(cave)) :
for col in range( len(cave[0])):
print("Testing row ", row, "col", col, " Found: ", cave[row][col])
color = grid.get_cur_color()
fill(cave, row, col, color)
if cave[row][col] == STONE:
chambers += 1
grid.get_next_color()
print(chambers, " chambers in cavern")
input("Press enter to close display")
答案 0 :(得分:0)
我不是100%确定网格是什么,或者它初始化的是什么,但这看起来像是一个边界问题:
if row > len(cave) or col > len(cave):
grid.fill_cell(row, col, color)
return
if row < 0 or col < 0:
grid.fill_cell(row, col, color)
return
首先,即使它超出范围,您还要填充单元格吗?为什么?即使这并没有引发一些错误,显然它不是,也不会给你提供比你的网格更多的方块?
另外,好吧,我可以看到一个小于0的行或列不在网格中,但让我们看看你的len(洞穴)...我也会假设len (cave)是网格侧面的单元格数,因为cave是列表的列表。它很好地映射。所以如果len(cave)是8,我们有一个8乘8的网格。但是你使用的是基于0的二维数组。所以你的最大细胞数应该是len(cave)-1。
解决这两个问题应该可以解决这个问题。但是,除此之外,很酷的计划。请稍后添加更新,显示工作网格的外观:)
编辑: 还有一件事我看错了。
if row > len(cave) or col > len(cave):
需要:
if row > len(cave) or col > len(cave[0]):