Reputation: 133
how can i change position of green circle
by coordinates(x, y) in numpy array?
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)
Upvotes: 1
Views: 914
Reputation: 260790
You can set the old position to square and the new to circle:
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
output:
array([['⬛', '⬛', '⬛', '⬛'],
['⬛', '⬛', '🟢', '⬛'],
['⬛', '⬛', '⬛', '⬛'],
['⬛', '⬛', '⬛', '⬛']], dtype='<U1')
If your goal is to make some kind of game, you should use a class for your board:
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
example:
m = Matrix()
print(m)
m.change_pos((2,1))
print(m)
Upvotes: 1
Reputation: 106
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)
result:
[
['⬛', '⬛', '⬛', '⬛'],
['⬛', '🟢', '⬛', '⬛'],
['⬛', '⬛', '⬛', '⬛'],
['⬛', '⬛', '⬛', '⬛']
]
Upvotes: 0