Firearrow5235
Firearrow5235

Reputation: 296

Connect 4 Horizontal Victory Checking Error

I've been trying to solve this issue for a couple of days now... here's the code...

def checkhor(array):
    for x in range(1, 8):
        if (array[x] == "#") or (array[x] == "@") and (array[x] <= 4):
            if (array[x] == array[(x + 1)]) and (array[x] == array[(x + 2)]) and (array[x] == array[(x + 3)]):
                if turn == 0:
                    print "You Won!"
                    return True
                else:
                    print "You Lost..."
                    return True

... here's the error

File "/home/firearrow5235/PycharmProjects/Connect 4/Connect 4.py", line 132, in <module>
if checkhor(f):
  File "/home/firearrow5235/PycharmProjects/Connect 4/Connect 4.py", line 77, in checkhor
if (array[x] == array[(x + 1)]) and (array[x] == array[(x + 2)]) and (array[x] == array[(x + 3)]):
IndexError: list index out of range

the points are which this error pops up is really sporadic... I can go a few rounds placing pieces in ANY of the seven slots without issues... I'll put my last input in...

['A', '#', 'O', 'O', 'O', 'O', 'O', 'O']
['B', '@', 'O', 'O', 'O', 'O', 'O', 'O']
['C', '@', 'O', 'O', 'O', 'O', 'O', 'O']
['D', '#', 'O', 'O', 'O', 'O', 'O', 'O']
['E', '@', '@', 'O', 'O', 'O', 'O', 'O']
['F', '@', '#', '#', 'O', '#', '#', 'O']
[' ', '1', '2', '3', '4', '5', '6', '7']
Enter the column you'd like to drop your piece in4

and I'll also add a board showing that it's not where the piece is that's the problem

Enter the column you'd like to drop your piece in5
['A', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['B', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['C', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['D', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['E', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['F', 'O', 'O', 'O', 'O', '@', 'O', 'O']
[' ', '1', '2', '3', '4', '5', '6', '7']

Upvotes: 1

Views: 101

Answers (1)

Mostly Harmless
Mostly Harmless

Reputation: 917

I believe it's a couple of things with your conditional:

if (array[x] == "#") or (array[x] == "@") and (array[x] <= 4):

If I understand your code correctly, the final check should be to make sure you don't go out of bounds with x >= 4, but you have array[x] >= 4 instead.

Additionally, you might want to throw some extra parenthesis around the or:

>>> True or False and False
True
>>> (True or False) and False
False

Either of those could contribute to getting past the conditional, and then getting your IndexError when you try to index x+3

Upvotes: 1

Related Questions