Sir AskA Lot
Sir AskA Lot

Reputation: 23

How can I flip around the coordinates inside a multidimensional array in Python?

So I'm making a game very similar to checkers that uses a 10x10 board. Each player has 15 checkers and one player starts on the top left while the other player starts on the bottom right. So far the idea I have for movement is that a player will input the x and y coordinate of the checker he wants to move. However I'd like to "flip" the gameboard each time a player makes a move so a player doesn't have to work with different sides of the board. I don't have much code other than the board itself and the print of the board. If it's any help this is the code I have so far, nothing too fancy.

matrix = [[1,1,1,1,1,0,0,0,0,0], [1,1,1,1,0,0,0,0,0,0], [1,1,1,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2], [0,0,0,0,0,0,0,0,2,2], [0,0,0,0,0,0,0,2,2,2], [0,0,0,0,0,0,2,2,2,2], [0,0,0,0,0,2,2,2,2,2]]

print "\n".join(" ".join(str(el) for el in row) for row in matrix)


print matrix[0][0]

This is the result:

1 1 1 1 1 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 2 2
0 0 0 0 0 0 0 2 2 2
0 0 0 0 0 0 2 2 2 2
0 0 0 0 0 2 2 2 2 2

So theoretically speaking if I wanted to move the checkers on the lowest row I would input x = 0 and y = 4 which would contain a "1" checker. However if the second player wants to move the same checker on their side they would have to input x = 9 and y = 5.

Is there any way to flip the coordinates in a way in which person two also inputs x = 0 and y = 4 to move the last checker. I'd prefer this system because I feel it's a lot less confusing.

Upvotes: 0

Views: 1929

Answers (2)

jason
jason

Reputation: 493

if you don't want to flip the array everytime, you could just transform the 2nd player input

def transform_p2(x,y):
    p2_x = 9-x
    p2_y = 9-y
    return p2_x, p2_y

Upvotes: 0

sebacastroh
sebacastroh

Reputation: 618

If I understand, you want the second user see the following matrix

2 2 2 2 2 0 0 0 0 0
2 2 2 2 0 0 0 0 0 0
2 2 2 0 0 0 0 0 0 0
2 2 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 1 1 1 1 1

If that's correct, the easiest way I think is using numpy

import numpy as np

new_matrix = np.fliplr(np.flipud(matrix)) # flip left-right and flip up-down
new_matrix = new_matrix.tolist() # If you want to use a list
                                 # instead a numpy array after the operation

Upvotes: 1

Related Questions