pythonstringloopsindexingrange

Python: classes and for loop error


I am a beginner programmer. I'm attempting to make an object-oriented chess game in Python. This is my first step, laying out a chess board. I have written:

  #this is board whick is necessery to run a class
board_for_start=[]
for x in range(8):
   for y in range(8):
      board_for_start.append('.')

class game:

#this is a setting board in class
    def __init__(self,board):
        self.board=board

# displaying board
    def display_board(self):
        for i in range (8):
            for j in range (8):
                print (self.board[i][j])
game_board=game(board_for_start)
game_board.display_board()

Traceback (most recent call last): File "C:/Users/Goldsmitd/PycharmProjects/CHESS/chees_ver0.02.py", line 22, in game_board.display_board() File "C:/Users/Goldsmitd/PycharmProjects/CHESS/chees_ver0.02.py", line 18, in display_board print (self.board[i][j]) IndexError: string index out of range

Why am I getting this error?


Solution

  • I made some small adjustments to your code that should help you get started. I renamed your class to something slightly less generic, though I think you will end up discarding this class as your game grows, because you will realize you need several discrete objects, not one big thing called "Game" or "ChessGame".

    All the board initialization takes place in __init__ for convenience, rather than outside the class. The display_board function has been rewritten to prevent off-by-one errors as discussed in my comment.

    class ChessGame:
        def __init__(self):
            self.board = [list('........') for i in range(8)]
    
        def display_board(self):
            for row in self.board:
                for square in row:
                    print(square, end="")
                print()
    

    Example Output:

    In [4]: game = ChessGame()
    
    In [5]: game.board
    Out[5]: 
    [['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.'],
     ['.', '.', '.', '.', '.', '.', '.', '.']]
    
    In [6]: game.display_board()
    ........
    ........
    ........
    ........
    ........
    ........
    ........
    ........