我正在为学校创建一个扫雷项目。部分内容是随机分配10个炸弹的坐标。这些将放置在9x9平方。我不希望重复炸弹坐标。然后我从列表buttonNames中删除炸弹的坐标。我添加了print语句,试图弄清楚为什么这段代码不起作用。
这是我的代码:
for i in range(11):
Bombx = randrange(1,10)
Bomby = randrange(1,10)
newBomb = (Bombx,Bomby)
self.BombList.append(newBomb)
sumValues = []
for (x,y) in self.BombList:
value = x+y
print(x,y)
sumValues.append(value)
for value in sumValues:
count = sumValues.count(value)
while count != 1:
Bombx = randrange(1,10)
Bomby = randrange(1,10)
newBomb = (Bombx,Bomby)
oldBomb = (x, y)
print(oldBomb)
self.BombList.remove(oldBomb)
self.BombList.append(newBomb)
count = 1
self.buttonNames.remove(newBomb)
它输出:
3 4
3 4
6 8
3 4
6 8
4 4
3 4
6 8
4 4
5 4
3 4
6 8
4 4
5 4
9 2
3 4
6 8
4 4
5 4
9 2
4 2
3 4
6 8
4 4
5 4
9 2
4 2
6 1
(6, 1)
(6, 1)
Traceback (most recent call last):
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 222, in <module>
main()
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 219, in main
gameBoard = Sweeper(win)
File "/Users/gould942/Documents/Intro Comp Sci/Minesweeper.py", line 98, in __init__
self.BombList.remove(oldBomb)
ValueError: list.remove(x): x not in list
感谢任何帮助。
答案 0 :(得分:1)
我通常更愿意尝试帮助您弄清楚为什么您的代码正在做他们正在做的事情,但说实话,我很难尝试遵循逻辑。相反,我会说,因为只有9x9 = 81个选项可供选择,简单的解决方案是生成所有可能选项的序列并使用random.sample()
:
self.BombList = []
for x in range(1, 10):
for y in range(1, 10):
self.BombList.append((x, y))
self.BombList = random.sample(self.BombList, 9)
如果您熟悉列表推导,整个过程可以在一行中完成:
self.BombList = random.sample([(x, y) for x in range(1, 10) for y in range(1, 10)], 9)