Reputation: 37
First, post so sorry if this isn't the right way to format everything but I'm trying to make a connect 4 game for two players and I can't figure out why I'm getting this error.
#Creates the board
def Boardmaker(field):
for row in range(12): #0,1,2,3,4,5,6,7,8,9,10,11
NewRow = int(row/2)
if row%2 == 0:
for column in range(13):
NewColumn = int(column/2)
if column%2 == 0:
if column != 12:
print(field[NewColumn][NewRow],end="")
else:
print(field[NewColumn][NewRow])
else:
print("|",end="")
else:
print("-------------")
#Play space
player = 1 #0 1 2 3 4 5 6
Currentfield = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
#Player Controller and turn allocator
Boardmaker(Currentfield)
while(True):
MoveColumn = int(input("Please enter a column"))
if player == 1:
#if Currentfield[MoveColumn] == " ":
Currentfield[MoveColumn] = "X"
player = 2
else:
#if Currentfield[MoveColumn] == " ":
Currentfield[MoveColumn] = "O"
player = 1
Boardmaker(Currentfield)
Upvotes: 0
Views: 75
Reputation: 33
In a connect 4 game you have to set the column
and the row
of the board, doing that your code will be:
player = 1
Currentfield = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "]]
while(True):
MoveColumn = int(input("Please enter a column:"))
MoveRow = int(input("Please enter a row:"))
if player == 1:
#if Currentfield[MoveColumn] == " ":
Currentfield[MoveColumn][MoveRow] = "X"
player = 2
else:
#if Currentfield[MoveColumn] == " ":
Currentfield[MoveColumn][MoveRow] = "O"
player = 1
Boardmaker(Currentfield)
Also, I noticed that you don't use correctly the indexes of the list, first the row
and then the column
, the code above should work in your program but, if you want to change it, you just have to change field[NewColumn][NewRow]
with field[NewRow][NewColumn]
and Currentfield[MoveColumn][MoveRow]
with Currentfield[MoveRow][MoveColumn]
Upvotes: 1
Reputation: 7863
In the code
if player == 1:
#if Currentfield[MoveColumn] == " ":
Currentfield[MoveColumn] = "X"
player = 2
you are replacing one of the lists of Currentfield
with the string "X"
since you are not specifying the row index. Then, while printing the game board you iterate over this string, and since this is a string of length 1 you get the index error.
Upvotes: 1