gpt4 book ai didi

python - 替换 numPy 中二维数组中的一项特定项

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:33 24 4
gpt4 key购买 nike

我正在尝试编写一个战舰游戏脚本(即你说“B4”而敌人说“HIT”)

实际上我正在尝试让电脑随机选择船的位置。一切都很好,但现在我需要更改“X”中所选框的值或其他不同的值。

from random import *
import numpy as np

def nuovaPartita():

campo = np.arange(100).reshape(10,10)
navi = [
[True, True],
[True, True],
[True, True],
[True, True],
[True, True, True],
[True, True, True],
[True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True, True]
]

direzioni = [0,1,2,3]



for x in navi:
posTrovata = False
while posTrovata == False:

lenNave = len(x)
scegliCasella = choice(choice(campo))
scegliDirezione = choice(direzioni)
posCasella = np.where(campo == scegliCasella)

R = int(posCasella[0])
C = int(posCasella[1])
print("============================\nHo scelto la casella: {}\nLunghezza nave: {}".format(scegliCasella, lenNave))

if scegliDirezione == 0:
print("Vado in alto")
chunk = campo[R-(lenNave - 1): R+1, C]
if int(chunk.shape[0]) < lenNave:
print("Assolutamente")
posTrovata = False
else:
posTrovata = True
print("La nave si trova nelle caselle")
print(chunk)

elif scegliDirezione == 1:
print("Vado a destra")
chunk = campo[R, C: C + lenNave ]
if int(chunk.shape[0]) < lenNave:
print("Assolutamente")
posTrovata = False
else:
posTrovata = True
print("La nave si trova nelle caselle")
print(chunk)


elif scegliDirezione == 2:
print("Vado in basso")
chunk = campo[R: R+lenNave, C]
if int(chunk.shape[0]) < lenNave:
print("Assolutamente")
posTrovata = False
else:
posTrovata = True
print("La nave si trova nelle caselle")
print(chunk)


elif scegliDirezione == 3:
print("Vado a sinistra")
chunk = campo[R, C - lenNave: C]
if int(chunk.shape[0]) < lenNave:
print("Assolutamente")
posTrovata = False
else:
posTrovata = True
print("La nave si trova nelle caselle")
print(chunk)


print(campo)


def main():
nuovaPartita()


if __name__ == "__main__":

main()

现在,如果我显示该字段(名为“campo”),我会得到这个

[[ 0  1  2  3  4  5  6  7  8  9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]

现在,假设我在 [54, 55, 56, 57] 上有一艘军舰,在 [31, 41, 51] 上有一艘军舰,我如何将这些盒子 int 替换为“x”?

最佳答案

您可以通过访问它的索引来简单地更改 Campo 中的值。 Campo 是列表的列表,因此可以通过访问索引 5 处列表的索引 6 处的值来访问数字 56,如下所示:

campo[5][6] = 'x'

您甚至可以将其概括为:

def update_campo(campo, number):
campo[number // 10][number % 10] = 'x'
return campo

for i in range(56, 60):
campo = update_campo(campo, i)

关于python - 替换 numPy 中二维数组中的一项特定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com