Reputation: 79
I'm building a simple game, using Python, with a 2D array as a board. I user can enter numbers to play, but those numbers do not correlate very well to a place on the board.
Can I store a location of an array in a variable so that I do not have to write out board[x][y] every time I check a conditional?
So instead of:
if num == 1:
if board[3][5] == "Z":
print "Not empty!"
else
board[3][5] = "Z"
I can use:
if num == 1:
if locationOf1 == "Z":
print "Not Empty!"
else
locationOf1 == "Z"
All I want locationOf1 to do is refer me to where board[3][5] is. How can this be done?
[edited] Or even better (is this possible?):
locations = *[location of board[5][1],location of board[5][3]]*
if locations[num] == "Z":
print "Not empty!"
else
locations[num] == "Z"
Upvotes: 2
Views: 252
Reputation: 5276
If I understood correctly you want to map board coords to a single value, I guess that have some meaning for the game since x,y coords sound simple enough.
I'd statically map those coords to model the board with a dict, and another dict to the current board state:
from collections import defaultdict
board = {
1: (1, 2),
3: (3, 4)
}
board_state = defaultdict(str)
Then just use locations[x] to get or set the state ("Z").
UPDATE:
def set_value(val, pos):
assert pos in board
board_state[pos] = val
def get_value(pos):
assert pos in board
return board_state[pos]
Just to illustrate a use case, you can of course just use the board_state. The assert here is optional and depends on your code, you can validate that elsewhere (user input, etc...)
Upvotes: 0
Reputation: 6814
The easiest way to store informations based on keys is the dict. You could save the values as a tuple:
locations = {1: (3, 5), 2: (4,3)}
def get_location(num):
x, y = locations.get(num, (-1, -1, ))
if coords != (-1,-1):
return board[x,y]
else:
return None
Upvotes: 1
Reputation: 1
Well, since you already have an array at your disposal, you can not do a faster look-up as you already have a constant look-up time. I would use a map with key as std::string and values as int* (c++) to map strings of the form "locationof1" to an integer pointer pointing to the actual address in the memory.
Upvotes: 0
Reputation: 394
One simple approach would be to create a wrapper class for your 2D array. The encapsulation would give meaning to your game board and easier to work with.
eg.
Class BoardWrapper {
private int[][] board;
public BoardWrapper(int w, int l) {
board = new int[w][l];
}
public locationOf1() {
if (board[3][5] == "Z") {
...
}
}
}
Upvotes: 0