Pygame:在一个确定的棋盘上生成x个随机和不同的坐标

2024-10-02 12:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个小的rpg游戏,我会创建一个包含特定数值的棋盘。你知道吗

让我介绍一个例子:

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乘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)

一个明显的问题是我们可以得到两个相似的坐标,这将减少一个值的整数。你知道吗

事实上,在第一个示例的board中,我没有值的数目,因为我向程序请求了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在生成中出现两次。你知道吗

有人能帮我达到预期的结果吗?你知道吗

EXPECTED RESULT ( concept ) :

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]]

Tags: andin程序boardforlenrangerandom
1条回答
网友
1楼 · 发布于 2024-10-02 12:38:22

您想创建一个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)

相关问题 更多 >

    热门问题