accelerate
accelerate

Reputation: 51

Printing a 2D game board

I have to make an othello game board and I was wondering how you make it so it prints the board properly. This is my code at the moment.

import collections

NONE = 0
BLACK = 'B'
WHITE = 'W'

BOARD_COLUMNS = int(input('How many board columns? '))
BOARD_ROWS = int(input('How many board rows? '))

class OthelloGameState:

    def _new_game_board() -> [[int]]:

        board = []

        for col in range(BOARD_COLUMNS):
            board.append([])
            for row in range(BOARD_ROWS):
                board[-1].append(NONE)
        return board

    print (_new_game_board())

I used the print to see what the board looks like and it came out like:

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

How would I make it so it's supposed to be the way it's supposed to be?

Upvotes: 1

Views: 1083

Answers (2)

Ben Harris
Ben Harris

Reputation: 557

You might want to make your board a state variable of the OthelloGameState class. That way you can update that and your _new_game_board() method will just fill that with the proper size of rows and columns.

Then you can use Copy and Paste's answer to print the board (or your own method if you want to display it without the braces).

def print_board(board):
    for col in range(BOARD_COLUMNS):
        print(' '.join([row for row in range(BOARD_ROWS)]))

Python's print() method will not format your output at all, so you will need to do that yourself.

https://ideone.com/bNxew0 for a working example

Upvotes: 0

Copy and Paste
Copy and Paste

Reputation: 526

import pprint

board = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
pprint.pprint(board)

Outputs:

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Check out a full run of the above: https://ideone.com/6buCwM

Upvotes: 1

Related Questions