如何更改green circlenumpy 陣列中坐標(x,y)的位置?
import numpy as np
matrix = np.array(
[
['??', '?', '?', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?']
]
)
x, y = tuple(zip(*np.where(matrix=='??')))[0]
yield "\n".join("".join(x for x in i) for i in matrix)
uj5u.com熱心網友回復:
您可以將舊位置設定為方形,將新位置設定為圓形:
old_pos = (0,0)
new_pos = (1,2)
def change_pos(matrix,old,new):
matrix[old] = '?'
matrix[new] = '??'
change_pos(matrix, old_pos, new_pos)
matrix
輸出:
array([['?', '?', '?', '?'],
['?', '?', '??', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?']], dtype='<U1')
使用類
如果你的目標是制作某種游戲,你應該為你的棋盤使用一個類:
import numpy as np
class Matrix():
def __init__(self, pos=(0,0), size=(3,3)):
self.pos = pos
self.matrix = np.empty(size, dtype='<U1')
self.matrix[:,:] = '?'
self.matrix[pos] = '??'
def __repr__(self):
return self.matrix.__repr__()
def __str__(self):
return self.matrix.__str__()
def change_pos(self, new):
self.matrix[self.pos] = '?'
self.matrix[new] = '??'
self.pos = new
例子:
m = Matrix()
print(m)
m.change_pos((2,1))
print(m)
uj5u.com熱心網友回復:
import numpy as np
matrix = np.array(
[
['??', '?', '?', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?']
]
)
def change_green(x, y):
x1, y1 = tuple(zip(*np.where(matrix=='??')))[0]
matrix[x1][y1] = '?'
matrix[x][y] = '??'
change_green(1, 1)
print(matrix)
結果:
[
['?', '?', '?', '?'],
['?', '??', '?', '?'],
['?', '?', '?', '?'],
['?', '?', '?', '?']
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371017.html
