简体   繁体   English

在适当位置打印多行

[英]Print multiple lines in place

for index in range(0, len(order_of_fruits)):
    maze[prevY][prevX] = ' '
    curr = order_of_fruits[index]
    maze[curr[1]][curr[0]] = 'P'
    prevX = curr[0]
    prevY = curr[1]

    result_maze = ""
    for i in range(len(maze)):
        for j in range(len(maze[0])):
            result_maze = result_maze + maze[i][j]
        result_maze = result_maze + '\n'

    animation.append(result_maze)

#animate
for index in range(0, len(animation)):
    time.sleep(0.2)
    sys.stdout.write("\r" + str(animation[index]))
    sys.stdout.flush()

Hi, my problem is that I have a two-dimentionay array whose condition will update. 嗨,我的问题是我有一个二维数组,其条件将更新。 Then I convert each updated array to a string and append each string to a list which are used to print in the console. 然后,我将每个更新的数组转换为字符串,并将每个字符串附加到用于在控制台中打印的列表。 Now I want print the changing condition of this maze which have already been converted to string in place. 现在,我要打印此迷宫的变化情况,该变化情况已经转换为字符串。 I used the "\\r" and flush but it does not work. 我使用了“ \\ r”并刷新,但是它不起作用。 I guess this might because I have "\\n" in each of my string. 我想这可能是因为我的每个字符串中都有“ \\ n”。 So is there any way that I can print the series of maze in console in place? 那么,有什么方法可以在控制台中适当地打印一系列迷宫? So the result looks like only one maze appears on the console whose condition will update every 0.2? 因此,结果看起来好像只有一个迷宫出现在控制台上,其状态每0.2更新一次? Thanks! 谢谢!

"\\r" maybe put in the end of line. “ \\ r”可能放在行尾。

import time
for index in range(0, len(animation)):
    sys.stdout.write(str(animation[index]) + "\r")
    sys.stdout.flush()
    time.sleep(0.2)

You might consider using the curses module. 您可以考虑使用curses模块。 This program updates the screen, waits 0.2 seconds, and updates the screen again: 该程序更新屏幕,等待0.2秒,然后再次更新屏幕:

from curses import wrapper
import time

def main(stdscr):
    stdscr.clear()
    for i in range(5):
        for y in range(5):
            for x in range(5):
                stdscr.addstr(y, x, chr(ord('1')+i))
            stdscr.refresh()
            time.sleep(0.2)
    stdscr.getkey()

wrapper(main)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM