如何在 X 时间后\n

How to \n after an amount of X time

我是 python 编程的初学者。 我需要制作一个井字游戏,但用户可以在其中输入 X 和 Y 的数量。

这是我的代码:

    def printboards():
    board_s1 = " _ "
    board_s2 = "| |"
    board_s3 = " _ "
    backspace = ("\n")
    print board_s1
    print board_s2
    print board_s3
    return
boardX = raw_input("How many X boards do you want? (insert 1 more than you want) > ")
boardY = raw_input("How many Y boards do you want? (insert 1 more than you want) > ")
for xx in range(1,int(boardX)):
    printboards()
    for yy in range(1,int(boardY)):
        printboards()

但每次我 运行 我得到这个程序:

enter image description here

我的第二个问题是,如果我在 BoardX 和 BoardY 中输入 3,我只会得到 6 个盒子,而不是 3x3 个盒子。

请帮忙

通过修改函数以传递一个参数来控制宽度,使其工作。

def printboards(x): board_s1 = " _ " * x board_s2 = "| |" * x board_s3 = " - " * x backspace = ("\n") print board_s1 print board_s2 print board_s3

删除的插入内容比你想要的多

boardX = raw_input("How many X boards do you want?  > ")
boardY = raw_input("How many Y boards do you want?  > ")

在 for 循环中添加额外的一个作为 int(boardX)+1 来控制适当的深度

for xx in range(1,int(boardX)+1):
    #int(boardY) parameter controls the width
    printboards(int(boardY))

欢迎来到python编程。换行符的问题是,每个 print 都是在新行中完成的。所以在你的情况下,如果你多次调用 printboards(),它会把所有的框都画在另一个下面。

您只得到 6 个框,因为 python 函数 range() 使用 0 索引,这意味着它从 0 开始计数。如果您使用 range(0,int(boardX))range(0,int(boardY)) 它会给你正确数量的盒子。但是,如果您想从 0 开始,您只需丢弃 0 并使用 range(int(boardX)).

如果您使用函数来绘制棋盘,只需让它完成整个事情即可:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#The function now takes the dimensions of the board in x and y as arguments
def printboards(x,y):
    # This results in y rows of boxes
    for i in range(y):
        # with x * "some text" you can multiply text
        print x*" _  "
        print x*"| | "
        print x*" ‾  " 

boardX = raw_input("How many X boards do you want? > ")
boardY = raw_input("How many Y boards do you want? > ")
printboards(int(boardX), int(boardY))

还有一件事:我还添加了 # -*- coding: utf-8 -*- 因为我在框的底部使用了一个特殊字符。

希望我能帮到你。