Skip to content
Advertisement

How to reset the index counter?

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.

JavaScript

` [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.

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement