如何格式化井字游戏板(Python)

问题描述 投票:0回答:1

本质上,我正在尝试格式化井字棋板,因此它以带有网格线的 3 x 3 图案打印。

首先,我尝试对网格进行硬编码,但后来它不可编辑。现在我创建了一个列表列表,我试图迭代每个元素,并为每个元素打印与其相邻的行。然而,当我这样做时,我遇到了“TypeError: can only concatenate str (not “list”) to str”,现在我不确定该怎么做。

相关代码:

class Tictactoe:

    def __init__(self, playerone, playertwo,):
        self.playerone = playerone
        self.playertwo = playertwo
        
        

    def newBoard(self):
        # creates new board
        return [[None, None, None],
                 [None, None, None],
                 [None, None, None]
                 ]
        
        
        
        


    def renderBoard(self):
        #todo: prints current state of board
        board = self.newBoard()
        for i in board:
            print("|" + i + "|")



    def getMove(self):
        #todo: get inputfor current player's move
        pass

    def makeMove(self):
        #todo: code the current player's move
        pass

    def getWinner(self):
        #todo write win conditions
        '''if player one marks 3 in a row, player one wins, end game
        if player two marks 3 in a row, player 2 wins, end game
        '''
        pass

    def resetButton(self):
        #todo: create a reset button that clears the board.
        pass

    def runGame(self):
        #todo: write code that starts the game.
        pass

    def isBoardFull(self):
        #todo: write code that checks if board is full
        pass


def main():
    test = Tictactoe("playerone", "playertwo")
    test.renderBoard()

if __name__ == '__main__':
    main()
python arrays tic-tac-toe
1个回答
0
投票

解决方案

def newBoard(self):
    # creates new board
    return [['x', 'o', ' '], # add markers to board
            [' ', ' ', ' '],
            [' ', ' ', ' ']]

def renderBoard(self):
    #todo: prints current state of board
    board = self.newBoard()
     
    print(f" {board[0][0]} | {board[0][1]} |  {board[0][2]} ")
    print("---+---+---")
    print(f" {board[1][0]} | {board[1][1]} |  {board[1][2]} ")
    print("---+---+---")
    print(f" {board[2][0]} | {board[2][1]} |  {board[2][2]} ")

您遇到的问题是您试图打印一行板,但

+
操作员不知道如何处理这些类型。因此,为了简单起见,我对电路板进行了硬编码,但我使用
f"{}"
以便可以打印出电路板的当前状态。现在,您可以通过将索引传递到游戏板来更新板。

© www.soinside.com 2019 - 2024. All rights reserved.