I’m implementing a game (connect four). A player makes a move by selecting a column number to place their checker in, when the column is empty the checker is placed at row index (-1) if not I’m decrementing the index by -1. I am having trouble resetting the row index so that after both players play the same column the next move in a non empty column should follow the last index and not continue on the last decremented index.[In this image, third move(red) and fourth move(green) played column 2, the green checker was supposed to be in row 5(index-2) but it continued from the last decremented index in second move(green[index -2] column(1)][1].
Here is my code. The moves are implemented from line 41.
`import sys from termcolor import colored, cprint #Drawing the 7columns x 6 rows playing field rows = [] #Empty list to store row numbers def playing_field(field): for row in range(11): rows.append(row) #Storing the row numbers in a list if row % 2 == 0: height = int(row/2) for column in range(13): if column % 2 == 0: width = int(column/2) if column != 12: print(field[height][width], end="") else: print(field[height][width]) else: print("|", end="") else: print("______________") return True #Defining the players variable player = 1 index = -1 # Defining a 7 columns by 6 rows list of lists curr_field = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "]] # Draw the field by calling the playing field function playing_field(curr_field) x = colored(u'u2B24', 'red') y = colored(u'u2B24', 'green') #Loop to initiate play as long condition is true while (True): print("PLAYER: ", player) moveCol = int(input("Choose column:n")) - 1 #Player one's turn if player == 1: if curr_field[-1][moveCol] == " ": curr_field[-1][moveCol] = x player = 2 else: index += (-1) curr_field[index][moveCol] = x #Take turn to player two player = 2 #Player two's turn else: if curr_field[-1][moveCol] == " ": curr_field[-1][moveCol] = y #Take turn to player 1 player = 1 else: index += (-1) curr_field[index][moveCol] = y #Take turn to player two player = 1 #calling function playing_field(curr_field)
` [1]: https://i.stack.imgur.com/qT9HV.png
Advertisement
Answer
Instead of manipulating the index number, what about just appending the moves to the matrix. Using a dictionary would probably be the easiest.
moves={} moves[colnum] = moves.get(colnum,[]) + [playernum]
If nobody has moved into a column, the .get()
function returns an empty list, then appends (adds) the value to that list.
After a while your dictionary will look like this:
{2: [1,2], 3: [2, 1, 2]}
Showing the player number for each position (bottom up) in the column.
This way, each column’s entry in the list is the right length and uses an index that could be used to pull a color for a list in your playing_field()
function.