我需要创建一个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))
Run Code Online (Sandbox Code Playgroud)
我已经包含了一段时间/其他 …