I'm trying to make a board game with python 3 using the pygame library. What I'm trying to do is create an x by y 2d list of objects which I've termed spaces to represent the board. First I initialize all of the spaces with the color as gray and the is_piece attribute set to False, indicating that they are all empty spaces. Then I want to replace the empty spaces with pieces by replacing the board[x][y] values with objects that have the is_piece attribute set to true.
The bug that I'm having is that the self.coords values are getting flipped. For example, in the below code, the stone object with the [2, 3] self.coords value is ending up in the board[3][2] position, and visa versa. Adding more stones also screws up the self.coords by flipping the index values and sometimes subsequently adding one to one of them.
def initialize_board():
#creates an array of empty spaces representing the board
board = [[Space(GRAY, RADIUS, [x, y], False) for x in range(BOARDWIDTH)]
for y in range(BOARDHEIGHT)
#Create the center stones
board[3][3] = Space(RED, RADIUS, [3, 3], True)
board[2][3] = Space(RED, RADIUS, [2, 3], True)
board[4][3] = Space(RED, RADIUS, [4, 3], True)
board[3][2] = Space(RED, RADIUS, [3, 2], True)
board[3][4] = Space(RED, RADIUS, [3, 4], True)
Here's the init method of the Space class that I'm using:
def __init__(self, color, size, coords, is_stone):
self.color = color
self.size = size
self.coords = coords
self.is_stone = is_stone #false if empty
self.pos = [CCONSTANT + DISTANCE * self.coords[0],
CCONSTANT + DISTANCE * self.coords[1]]
Can anyone tell me what I'm messing up?
As @Joran Beasley already pointed out you can access the values using [row][col] (which would be [y][x]) in your current code. In order to access using [x][y] you can slightly change the loop that creates your board:
board = [[Space(GRAY, RADIUS, [x, y], False) for y in range(BOARDHEIGHT)]
for x in range(BOARDWIDTH)
To get a shape (BOARDWIDTH, BOARDHEIGHT)
in the resulting board.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.