我需要创建一个8x8的网格,并将10个硬币随机分布在网格上。我面临的问题是randint函数有时会生成相同的随机坐标,因此只有9或8个硬币被生成并放置在网格上。我该如何确保这不会发生?谢谢 :) 这是我的代码:
from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
#create 10 random treasure chests
#problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while c_x == 7 and c_y == 0:
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
else:
grid[c_x][c_y] = "C"
for row in grid:
print(" ".join(row))
我已经包含了一个while/else - 因为在网格的左下角不能有硬币。