【问题标题】:Python Drawing a tic tac toe boardPython 绘制井字棋盘
【发布时间】:2017-05-30 18:41:20
【问题描述】:

我正在尝试画一个假的 3x3 井字游戏板。我是 python 新手,我不明白为什么这不起作用。帮助将不胜感激。谢谢!

def draw():
    for i in range(4):
        board = (" ___ " * 3)

    for i in board:
        ("|    " * 4).join(board)

    print(board)


draw()

编辑:

最终代码:

def draw():
    board = ''

    for i in range(-1,6):

        if i%2==0:
            board += '|      ' * 4
            board += '\n|      |      |      |'

        else:
            board += ' _____ ' * 3

        board += '\n'
    print (board)

draw()

输出:

 _____  _____  _____ 
|      |      |      |      
|      |      |      |
 _____  _____  _____ 
|      |      |      |      
|      |      |      |
 _____  _____  _____ 
|      |      |      |      
|      |      |      |
 _____  _____  _____ 

双重编辑:

另一种方式:

def drawsmall():
    a = (' ___' *  3 )
    b = '   '.join('||||')
    print('\n'.join((a, b, a, b, a, b, a, )))

drawsmall()

输出:

 ___ ___ ___
|   |   |   |
 ___ ___ ___
|   |   |   |
 ___ ___ ___
|   |   |   |
 ___ ___ ___

【问题讨论】:

    标签: python python-3.x range


    【解决方案1】:

    我发现在一个循环中执行此操作更容易,每次迭代打印一行板。您可以使用% 运算符检查当前迭代是偶数还是奇数,从而在垂直和水平条之间交替。

    对于字符串,您不需要使用连接 -- 附加 += 运算符会更清楚。

    def draw():
        # initialize an empty board
        board = ""
    
        # there are 5 rows in a standard tic-tac-toe board
        for i in range(5):
            # switch between printing vertical and horizontal bars
            if i%2 == 0:
                board += "|    " * 4
            else:
                board += " --- " * 3
            # don't forget to start a new line after each row using "\n"
            board += "\n"
    
        print(board)
    
    draw()
    

    输出:

    |    |    |    |    
     ---  ---  --- 
    |    |    |    |    
     ---  ---  --- 
    |    |    |    |   
    

    【讨论】:

      【解决方案2】:

      试试这个代码:

      def draw():
          a=('\n _____  _____  _____ ')
          b= ('\n|     |      |      |')
          print(a,b,b,a,b,b,a,b,b,a)
      draw()
      

      输出:

       _____  _____  _____  
      |     |      |      | 
      |     |      |      | 
       _____  _____  _____  
      |     |      |      | 
      |     |      |      | 
       _____  _____  _____  
      |     |      |      | 
      |     |      |      | 
       _____  _____  _____ 
      

      为了更好的视图使用:

      def print_tic_tac_toe():
          print("\n")
          print("\t     |     |")
          print("\t     |     |  ")
          print('\t_____|_____|_____')
       
          print("\t     |     |")
          print("\t     |     |  ")
          print('\t_____|_____|_____')
       
          print("\t     |     |")
       
          print("\t     |     |  ")
          print("\t     |     |")
          print("\n")
      print_tic_tac_toe()
      

      输出:

               |     |
               |     |  
          _____|_____|_____
               |     |
               |     |  
          _____|_____|_____
               |     |
               |     |  
               |     |
      ​
      

      【讨论】:

        【解决方案3】:

        查看join 函数的工作原理。首先,它采用给定的字符串并将其用作“胶水”,即连接其他字符串的字符串。其次,它返回构造的字符串;您的join 操作未能保存结果。

        尝试首先使用嵌套循环执行此操作:打印一行框,然后是水平分隔线等。然后,逐位将其转换为您想要的单字符串输出。

        【讨论】:

          【解决方案4】:

          你可以试试这个:

          def draw():
             return [["__" for b in range(3)] for i in range(3)]
          

          现在您有一个包含您的板的列表列表。要打印出来,您可以这样做:

          the_board = draw()
          
          for i in the_board:
              for b in i:
          
                  print('|'.join(i), end="") 
          
              print()
          
          print("  |    |  ")
          

          【讨论】:

            【解决方案5】:

            我想我会简化一些事情,以便我自己理解它。此代码产生与上面相同的输出:

            def draw_board():
                v = '|    |    |    |'
                h = ' ____ ____ ____ '
                for i in range(0,10):
                    if i%3==0:
                        print(h)
                    else:
                        print(v)
            draw_board()
            

            输出:

             ____ ____ ____ 
            |    |    |    |
            |    |    |    |
             ____ ____ ____ 
            |    |    |    |
            |    |    |    |
             ____ ____ ____ 
            |    |    |    |
            |    |    |    |
             ____ ____ ____ 
            

            【讨论】:

              【解决方案6】:

              如果您不想使用变量/函数/循环并想要一个基于打印命令的简单单行解决方案:

              print("__|__|__", "__|__|__", "  |  |  ", sep='\n')
              

              【讨论】:

                【解决方案7】:

                你可以试试这个: 在下面找到用于端到端交互式井字棋棋盘游戏的 python 代码。 代码看起来很长,可以优化,但它可以完美地作为交互式井字棋盘游戏。

                #Function code to clear the output space (screen)
                 
                 from IPython.display import clear_output
                
                #code to display just board-
                
                def ttt_borad(board):
                cl = clear_output()
                print('Your Tic-Tac-Toe board now:\n')
                print(board[1] + "|" + board[2] + "|" + board[3])
                print("________")
                print(board[4] + "|" + board[5] + "|" + board[6])
                print("________")
                print(board[7] + "|" + board[8] + "|" + board[9])
                
                #function code to accept player key choices-
                
                def player_key():
                player_choice = ''
                play1 = ''
                play2 = ''
                while player_choice not in ('Y', 'N'):
                    player_choice = input("Player-1 would like to go first ? Enter Y/N: ")
                    player_choice = player_choice.upper()
                    if player_choice not in ('Y', 'N'):
                        print("Invalid Key")
                    else:
                        pass
                if player_choice == 'Y':
                
                    while play1 not in ('X', 'O'):
                        play1 = input("Select your Key for Player-1 X or O: ")
                        play1 = play1.upper()
                        if play1 not in ('X', 'O'):
                            print("Invalid Key")
                        else:
                            pass
                else:
                    while play2 not in ('X', 'O'):
                        play2 = input("Select your Key for Player-2 X or O: ")
                        play2 = play2.upper()
                        if play2 not in ('X', 'O'):
                            print("Invalid Key")
                        else:
                            pass
                
                if play1 == 'X':
                    play2 = 'O'
                elif play1 == 'O':
                    play2 = 'X'
                elif play2 == 'X':
                    play1 = 'O'
                elif play2 == 'O':
                    play1 = 'X'
                
                print(f'Key for Player-1 is: {play1} and Key for Player-2 is: {play2}')
                return play1, play2
                
                
                
                #function code to accept key strokes to play game
                
                def enter_key(key, bp):
                play1, play2 = key
                ind = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
                i = 1
                while i < 10:
                    j = 0
                    k = 0
                    print(f'Game Move: {i}')
                    while j not in ind:
                        j = input("Player-1: Select position (1-9) for your Move: ")
                        if j not in ind:
                            print("Invalid Key or Position already marked")
                        else:
                            pass
                    x = ind.index(j)
                    ind.pop(x)
                    j = int(j)
                    bp[j] = play1
                    ttt_borad(bp)
                    i = i + 1
                    tf = game_winner(key, bp)
                    if tf == 1:
                        print("The Winner is: Player-1 !!")
                        break
                    print(f'Game Move: {i}')
                    if i == 10:
                        break
                
                    while k not in ind:
                        k = input("Player-2: Select position (1-9) for your Move: ")
                        if k not in ind:
                            print("Invalid Key or Position already marked")
                        else:
                            pass
                    y = ind.index(k)
                    ind.pop(y)
                    k = int(k)
                    bp[k] = play2
                    ttt_borad(bp)
                    i = i + 1
                    ft = game_winner(key, bp)
                    if ft == 2:
                        print("The Winner is: Player-2 !!")
                        break
                return bp
                
                #function code to calculate and display winner of the game-
                def game_winner(key, game):
                p1, p2 = key
                p = 0
                if game[1] == game[2] == game[3] == p1:
                    p = 1
                    return p
                elif game[1] == game[4] == game[7] == p1:
                    p = 1
                    return p
                elif game[1] == game[5] == game[9] == p1:
                    p = 1
                    return p
                elif game[2] == game[5] == game[8] == p1:
                    p = 1
                    return p
                elif game[3] == game[6] == game[9] == p1:
                    p = 1
                    return p
                elif game[4] == game[5] == game[6] == p1:
                    p = 1
                    return p
                elif game[3] == game[5] == game[7] == p1:
                    p = 1
                    return p
                elif game[1] == game[2] == game[3] == p2:
                    p = 2
                    return p
                elif game[1] == game[4] == game[7] == p2:
                    p = 2
                    return p
                elif game[1] == game[5] == game[9] == p2:
                    p = 2
                    return p
                elif game[2] == game[5] == game[8] == p2:
                    p = 2
                    return p
                elif game[3] == game[6] == game[9] == p2:
                    p = 2
                    return p
                elif game[4] == game[5] == game[6] == p2:
                    p = 2
                    return p
                elif game[3] == game[5] == game[7] == p2:
                    p = 2
                    return p
                else:
                    p = 3
                    return p
                
                #Function code to call all functions in order to start and play game-
                
                def game_play():
                clear_output()
                entry = ['M', '1', '2', '3', '4', '5', '6', '7', '8', '9']
                ttt_borad(entry)
                plk = player_key()
                new_board = enter_key(plk, entry)
                tie = game_winner(plk, new_board)
                if tie == 3:
                    print("Game Tie !!! :-( ")
                
                print('Would you like to play again? ')
                pa = input("Enter Y to continue OR Enter any other key to exit game: ")
                pa = pa.upper()
                if pa == 'Y':
                    game_play()
                else:
                    pass
                
                game_play()
                

                #在任何 Python3 编辑器中尝试整个代码,并告诉我您的反馈。 我附上了代码如何显示的示例板。Sample Tic-Tac-Toe board by code

                谢谢

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多