是否有python 3命令清除输出控制台?

问题描述 投票:1回答:1

因此,我试图在PyCharm中制作一个简单的Conway生活游戏,而我只能在输出控制台中获得一堆输出,而没有像流一样的视频。是否有一条命令可以让我清除程序中每个循环的输出。我已经尝试过“ sys”命令和ANSI转义键(希​​望我拼写正确)。似乎没有任何作用!我正在使用Python 3。

我想在while循环的第一个打印语句上清除控制台。如果有帮助。

import copy
import random
import time
WIDTH = 60
HEIGHT = 10


nextCells = []
for x in range(WIDTH):
    column = []
    for y in range(HEIGHT):
        if random.randint(0, 1) == 0:
            column.append('#')
        else:
            column.append(' ')
    nextCells.append(column)

while True:
    # print('\n\n\n\n')
    currentCells = copy.deepcopy(nextCells)

    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y], end='')
        print()
python-3.x pycharm
1个回答
1
投票

尝试使用curses库将光标上移并在当前迭代上打印下一个迭代:

import copy
import random
import time

import curses

WIDTH = 60
HEIGHT = 10

scr = curses.initscr()

nextCells = []
for x in range(WIDTH):
    column = []
    for y in range(HEIGHT):
        if random.randint(0, 1) == 0:
            column.append('#')
        else:
            column.append(' ')
    nextCells.append(column)

while True:
    # print('\n\n\n\n')
    currentCells = copy.deepcopy(nextCells)

    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y], end='')
        print()
    for x in range(WIDTH):
        for y in range(HEIGHT):
            leftCoord = (x - 1) % WIDTH
            rightCoord = (x + 1) % WIDTH
            aboveCoord = (y - 1) % HEIGHT
            belowCoord = (y + 1) % HEIGHT

            numNeighbors = 0
            if currentCells[leftCoord][aboveCoord] == '#':
                numNeighbors += 1
            if currentCells[x][aboveCoord] == '#':
                numNeighbors += 1
            if currentCells[rightCoord][aboveCoord] == '#':
                numNeighbors += 1
            if currentCells[leftCoord][y] == '#':
                numNeighbors += 1
            if currentCells[rightCoord][y] == '#':
                numNeighbors += 1
            if currentCells[leftCoord][belowCoord] == '#':
                numNeighbors += 1
            if currentCells[x][belowCoord] == '#':
                numNeighbors += 1
            if currentCells[rightCoord][belowCoord] == '#':
                numNeighbors += 1

            if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
                nextCells[x][y] = '#'
            elif currentCells[x][y] == ' ' and numNeighbors == 3:
                nextCells[x][y] = '#'
            else:
                nextCells[x][y] = ' '

    # Here we move the cursor back up:
    y,x = curses.getsyx()
    curses.setsyx(y-HEIGHT,x)

    time.sleep(1)
© www.soinside.com 2019 - 2024. All rights reserved.