Python 绘制井字棋盘 [英] Python Drawing a tic tac toe board

查看:58
本文介绍了Python 绘制井字棋盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制一个假的 3x3 井字棋盘.我是 python 新手,我不明白为什么这不起作用.帮助将不胜感激.谢谢!

I am trying to draw a fake 3x3 tic tac toe board. I am new to python and I don't understand why this does not work. Help would be appreciated. Thanks!

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

输出:

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

推荐答案

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

I found it easier to do this in one loop, printing a row of the board each iteration. You can alternate between vertical and horizontal bars by checking if the current iteration is an even or odd number using the % operator.

对于字符串,您不需要使用连接——使用 += 操作符附加会更清晰.

With strings you don't need to use join -- it can be more clear to append with the += operator.

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

输出:

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

这篇关于Python 绘制井字棋盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆