Python绘制一个tic tac toe board

时间:2017-05-30 18:41:21

标签: python python-3.x range

我正在尝试画一个假的3x3 tic tac toe board。我是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()

输出:

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

Double Edit:

另一种方式:

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

drawsmall()

输出:

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

7 个答案:

答案 0 :(得分: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()

输出:

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

答案 1 :(得分:1)

试试这个代码:

bool mysort(int arg1,int arg2){
    return arg1 % 2 == 0 && arg2 % 2 != 0;
}

输出:

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()

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

你可以试试这个:

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("  |    |  ")

答案 4 :(得分:0)

我认为我会简化事情,以便自己理解。这段代码产生与上面相同的输出:

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

输出:

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

答案 5 :(得分:0)

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

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

答案 6 :(得分:0)

您可以尝试以下操作: 在下面找到端到端互动井字棋盘游戏的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

谢谢