井字游戏python游戏

时间:2020-01-20 03:56:07

标签: python

我是python的新手,正在从事井字游戏。 我陷入了make_move和next_player函数中。每当我运行代码时,都会出现如下错误。

1 | 2 | 3

4 | 5 | 6

7 | 8 | 9

X

轮到1:选择一个方块:1

回溯(最近通话最近):
在第268行中输入文件 display_board(board)
在display_board中,文件“第58行” board_to_show + = player_name(board [i])#显示玩家的标记
文件“第23行,在player_name中 返回PLAYER_NAMES [player_id]
TypeError:列表索引必须是整数或切片,而不是str

我想解决此错误,并确保make_move和next_player正常工作,但是我不知道该怎么做...谢谢您的帮助

    # CONSTANTS

    PLAYER_NAMES = ["Nobody", "X", "O"] 


    # FUNCTIONS
    def player_name(player_id):
        '''return the name of a player with a specified ID

        Looks up the name in the PLAYER_NAMES global list

        Parameters
        ----------
        player_id: int
            player's id, which is an index into PLAYER_NAMES

        Returns
        -------
        string
            the player's name

        '''
        return PLAYER_NAMES[player_id]

    # for current_player in range(len(PLAYER_NAMES)):
    #     print(player_name(current_player))



    def display_board(board):
        '''display the current state of the board

        board layout:
        1 | 2 | 3
        4 | 5 | 6
        7 | 8 | 9

        Numbers are replaced by players' names once they move. 
        Iterate through the board and choose the right thing
        to display for each cell.

        Parameters
        ----------
        board: list
            the playing board

        Returns
        -------
        None
        '''

        board_to_show = "" # string that will display the board, starts empty
        for i in range(len(board)):
            if board[i] == 0: # 0 means unoccupied
                # displayed numbers are one greater than the board index
                board_to_show += str(i + 1) # display cell number
            else:
                board_to_show += player_name(board[i]) # display player's mark
            if (i + 1) % 3 == 0: # every 3 cells, start a new row
                board_to_show += "\n"
            else:
                board_to_show += " | " # within a row, divide the cells
        print()
        print(board_to_show)


    def make_move(player, board):
        '''allows a player to make a move in the game

        displays who's move it is (X or O)
        prompts the user to enter a number 1-9
        validates input, repeats until valid input is entered
        checks move is valid (space is unoccupied), repeats until valid move
        is entered

        Parameters
        ----------
        player: int
            the id of the player to move (1 = X, 2 = O)

        board: list
            the board upon which to move
            the board is modified in place when a valid move is entered
        '''
        # TODO: Implement function


        if player == 1:
            marking = 'X'

        if player == 2:
            marking = 'O'


        invalid_input = "sorry, please enter a valid input. You can select a number 1-9."

        try:
            selection = int(input("{}'s turn: Select a square: ".format(player)))-1
            board[selection] = marking
                # display_board(board)

        except ValueError:
            print(invalid_input)

        except IndexError:
            print(invalid_input)







    def check_win_horizontal(board):
        # TODO: write docstring
        '''
        Way to check for horizontal victories.
        The player who marked 1,2,3 / 4,5,6/ 7,8,9 on board will win.

        parameter
        ---------
            board: list

        '''
        if (board[0] != 0 and 
            board[0] == board[1] and 
            board[0] == board[2]):
            return board[0]
        if (board[3] != 0 and
            board[3] == board[4] and 
            board[3] == board[5]):
            return board[3]
        if (board[6] != 0 and
            board[6] == board[7] and 
            board[6] == board[8]):
            return board[6]
        return 0


    def check_win_vertical(board):
        # TODO: write docstring
        '''
        Way to check for Vertical victories.
        The player who marked 1,4,7 / 2,5,8/ 3,6,9 on board will win.

        parameter
        ---------
            board: list

        '''
        # TODO: implement function
        if (board[0] != 0 and 
            board[0] == board[3] and 
            board[0] == board[6]):
            return board[0]
        if (board[1] != 0 and
            board[1] == board[4] and 
            board[1] == board[7]):
            return board[1]
        if (board[2] != 0 and
            board[2] == board[5] and 
            board[2] == board[8]):
            return board[2]
        return 0


    def check_win_diagonal(board):
        # TODO: write docstring
        '''
        Way to check for diagonal victories.
        The player who marked 1,5,9 / 3,5,7 on board will win.

        parameter
        ---------
            board: list

        '''
        # TODO: implement function
        if (board[0] != 0 and 
            board[0] == board[4] and 
            board[0] == board[8]):
            return board[0]
        if (board[2] != 0 and
            board[2] == board[4] and 
            board[2] == board[6]):
            return board[2]
        return 0


    def check_win(board):
        '''checks a board to see if there's a winner

        delegates to functions that check horizontally, vertically, and 
        diagonally to see if there is a winner. Returns the first winner
        found in the case of multiple winners.

        Parameters
        ----------        
        board: list
            the board to check

        Returns
        -------
        int
            the player ID of the winner. 0 means no winner found.
        '''

        winner = check_win_horizontal(board)
        if (winner != 0):
            return winner

        winner = check_win_vertical(board)
        if (winner != 0):
            return winner

        return check_win_diagonal(board)


    def next_player(current_player):
        '''determines who goes next

        given the current player ID, returns the player who should 
        go next

        Parameters
        ----------        
        current_player: int
            the id of the player who's turn it is now

        Returns
        -------
        int
            the id of the player to go next
        '''
        # TODO: Implement function
        # if player_turn == 'O':
        #     marking = "O"

        return 2 

    # MAIN PROGRAM (INDENT LEVEL 0)

    # GLOBAL VARIABLES
    board = [0, 0, 0,   # top row:    indices 0, 1, 2
             0, 0, 0,   # middle row: indices 3, 4, 5
             0, 0, 0]   # bottom row: indices 6, 7, 8

    player = 1          # X goes first
    moves_left = 9      # number of moves so far 
    winner = 0          # "Nobody" is winning to start

    while(moves_left > 0 and winner == 0):
        display_board(board)
        make_move(player, board)
        winner = check_win(board)
        player = next_player(player)
        moves_left -= 1

1 个答案:

答案 0 :(得分:0)

从错误和代码中,您在棋盘中分配了玩家的标记(X或O),而不是其在PLAYER_NAMES中的位置的索引。这意味着board[i]正在访问字符串的位置,而不是引用索引的整数(因此会出错)。

要解决此问题,请将board_to_show += player_name(board[i])更改为board_to_show += player_name(PLAYER_NAMES.index(board[i]))