对于小型角色扮演游戏,我会创建包含特定数量值的棋盘。
让我举个例子:
board =[[0, 0, 0, 15, 0, 0, 0, 0, 0, 0],
[0, 0, 15, 0, 15, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 15, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 15, 0, 0, 0, 0, 15, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 15, 0, 0, 0, 0, 0, 15, 0, 0],
[0, 0, 0, 0, 0, 15, 0, 0, 15, 0],
[15, 0, 15, 15, 0, 0, 0, 0, 0, 0]]
这是一个 10 x 10 的棋盘,其中 13 乘以值 15。
为了得到这个结果,我使用了一个在板上随机给出坐标的程序。
b2x = []
b2y = []
for i in range(B):
x = random.randint(0,L-1)
y = random.randint(0,H-1)
b2x.append(x)
b2y.append(y)
board[x][y] = 15
print('x : ',x, ' and y : ', y)
这里一个明显的问题是我们可以得到两个相似的坐标,这将使整数值减一。
事实上,在第一个示例的面板中,我没有值的数量,因为我向程序询问了 15 个值,它返回了 13。
所以我尝试在没有坐标检查的情况下解决这个问题,现在似乎无法正常工作。
for j in range(len(bo2x)):
if (x == b2x[j-1]) and (y == b2y[j-1]):
i -= 1 # affect the for i in range(B) loop
完整代码:
b2x = []
b2y = []
for i in range(B):
x = random.randint(0,L-1)
y = random.randint(0,H-1)
for j in range(len(bo2x)):
if (x == b2x[j-1]) and (y == b2y[j-1]):
i -= 1 # affect the for i in range(B) loop
b2x.append(x)
b2y.append(y)
board[x][y] = 15
print('x : ',x, ' and y : ', y)
结果,经过多次尝试,根本没有任何变化:
random generation
x : 5 and y : 4
x : 1 and y : 3
x : 7 and y : 7
x : 7 and y : 5
x : 0 and y : 7
x : 0 and y : 1
x : 6 and y : 2
x : 3 and y : 6
x : 9 and y : 4
x : 5 and y : 9
x : 6 and y : 8
x : 6 and y : 7
x : 3 and y : 6
x : 3 and y : 7
x : 7 and y : 5
[Finished in 0.2s]
如您所见,行 x : 7 and y : 5
和行 x : 3 and y : 6
在生成中出现了两次。
有人可以帮助我达到我的预期结果吗?
预期结果(概念):
x : 5 and y : 4
x : 1 and y : 3
x : 7 and y : 7
x : 7 and y : 5
x : 0 and y : 7
x : 0 and y : 1
x : 6 and y : 2
x : 3 and y : 6
x : 9 and y : 4
x : 5 and y : 9
x : 6 and y : 8
x : 6 and y : 7
x : 3 and y : 6
this line already exist !
x : 3 and y : 7
x : 7 and y : 5
this line already exist !
x : 1 and y : 3
x : 9 and y : 4
board :
[[0, 15, 15, 0, 0, 0, 0, 15, 0, 0],
[0, 0, 0, 15, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 15, 15, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 15, 0, 0, 0, 0, 15],
[0, 0, 15, 0, 0, 0, 0, 15, 15, 0],
[0, 0, 0, 0, 0, 15, 0, 15, 0, 0],
[0, 0, 0, 15, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 15, 0, 0, 0, 0, 0]]
最佳答案
您想创建一个 LxB 板。
L, H = 10, 10
这可以通过一行代码实现:
board = [[0] * L for _ in range(H)]
您想在棋盘上的不同位置放置某个数字 15 次。
生成随机坐标,但如果数字已分配给索引字段,则跳过坐标:
count = 15
number = 15
b = []
while count > 0:
x, y = random.randint(0,L-1), random.randint(0,H-1)
if board[y][x] != number:
board[y][x] = number
b.append((x, y))
count -= 1
for row in board:
print(row)
print(b)
关于python - 游戏 : Generate x random and different coordinates in a definited board,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923970/