Reputation: 29
COLUMNS = 5
ROWS = 4
def empty_board():
board_rows =["| \t\t |"] * ROWS
board_columns = [" ___ "] * COLUMNS
for i in range (ROWS):
print(board_rows[i])
print("+", end= " " )
for i in range(COLUMNS):
print(board_columns[i], end="")
print
print("+")
for i in range(COLUMNS):
column_number = i+1
print(" " + str(column_number), end = " ")
def column_choice():
player = 1
if player % 2 != 0 :
column = input("Player 1, please choose a column to make your next move ")
else:
column = input("Player 2, please choose a column to make your next move ")
player += 1
return column
def new_board(column):
moves = 0
column = int(column) - 1
if moves % 2 == 0:
key = "X"
else:
key = "O"
board_rows = ["| \t\t |"] * ROWS
board_columns = [" ___ "] * COLUMNS
for i in range (ROWS):
print(board_rows[i])
board_rows.pop(column)
board_rows = board_rows.insert(column, key)
print(board_rows)
print("+", end= " " )
for i in range(COLUMNS):
print(board_columns[i], end="")
print("+")
for i in range(COLUMNS):
column_number = i+1
print(" " + str(column_number), end = " ")
if __name__ == "__main__":
print()
print("Welcome to Connect 4")
print()
new_board(column_choice())
I have to create a connect 4 board with the given column and row dimensions (for now). I currently have the board created, but I can't quite figure out how to get the X
or O
to go in the correct spot. For instance, right now when I run the program, the X
will go in the whole column. If you could offer any help I would appreciate it!
Upvotes: 0
Views: 2007
Reputation:
board_rows =["| \t\t |"] * ROWS
board_columns = [" ___ "] * COLUMNS
points each entry/item in the list to the same memory address, so changing one column changes them all since they each point to the same place.
for row in board_rows:
print id(row)
Use list comprehension or a for loop instead to get different items (memory location) in the list.
board_rows =["| \t\t |" for row in ROWS]
for row in board_rows:
print id(row)
Upvotes: 1
Reputation: 2968
Honestly, that is a very complicated way to represent a textual board. I would recommend, if possible, using an object-oriented approach, such as making the board into a list of lists, where every entry in the list is an list of strings that represents a row, with a __repr__
method to help visualize it more easily. Here is an example I wrote.
class Board(object):
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.board = [['_' for i in range(self.columns)] for i in range(self.rows)]
def __repr__(self):
board = ''
for row in self.board:
board += ''.join(row) + '\n'
return board
f = Board(5, 5)
=> None
f
=> _____
_____
_____
_____
_____
This way, a blank board is represented as a dual list-comprehension, where your rows parameter is the vertical length, and your columns parameter is the horizontal length.
With this code, try writing a method to add a piece onto the board, by finding the lowest point in a column that isn't the opponents piece.
Upvotes: 0