Python Forum

Full Version: connect 4 unknown erroer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is the start of a 4 in a row game / connect 4. I am experiencing the error:

line 10, in is_valid_location
if board[bottom_row][column] == 0:
IndexError: index 5 is out of bounds for axis 0 with size 5


I would really appreciate some help thanks.
import numpy as np
turn = 0
game_over = False

def board_create(column, row):
    board = np.zeros((row,column))
    return board

def is_valid_location(column_choice, board, bottom_row):
    if board[bottom_row][column] == 0:
        return False
    else:
        return True

row = 5
column = int(input("How many columns: "))
board = board_create(column, row)

while not game_over:
    if turn == 0:
        invalid = True
        bottom_row = row
        while invalid == True:
            column = str(column)
            column_choice = int(input("Player 1 make your selection (1-"+column+"):"))
            column = int(column)
            invalid = is_valid_location(column_choice, board, bottom_row)
    else:
        while invalid == True:
            column = str(column)
            column_choice = int(input("Player 2 make your selection (1-"+column+"):"))
            column = int(column)
            invalid = is_valid_location(column_choice, board, bottom_row)
    turn = turn + 1
    turn = turn % 2
(Aug-16-2019, 10:27 AM)Help_me_Please Wrote: [ -> ]IndexError: index 5 is out of bounds for axis 0 with size 5
axis is with size 5, so indexes are from 0 to 4
What does that mean? and so what do I need to change?
(Aug-16-2019, 10:43 AM)Help_me_Please Wrote: [ -> ]What does that mean? and so what do I need to change?

There are zero-based index and there is finger-based index. Formula for converting:

finger-based index - 1 = zero-based index
zero-based index + 1 = finger-based index

Users count with their fingers, but for Python you need to convert it into zero-based index.
What do I change the line too, to avoid this issue.
you take index as input from user and ask for number between 1 and column. Because indexes are zero-based, you need a number between 0 and column-1. It's up to you how you will achieve that - ask the user or post-process the user input before using it in your code that raise IndexError.
Note also that the function is_valid_location can be simplified to, e.g. return not board[bottom_row][column] == 0. Since the expression board[bottom_row][column] == 0 already evaluates to a boolean, the if and else are unnecessary.