There is a limit to what you can do, but put everything in one large line, and then printing once between screen cleanups is better than a few small prints in a loop. Run the following code and see how much better the second half of the program works than the first half:
import time, os, random def display1(chars): os.system('cls') for row in chars: print(''.join(row)) def display2(chars): os.system('cls') print('\n'.join(''.join(row) for row in chars)) chars = [] for i in range(40): chars.append(["-"]*40) for i in range(100): r = random.randint(0,39) c = random.randint(0,39) chars[r][c] = "X" time.sleep(0.1) display1(chars) os.system('cls') time.sleep(1) chars = [] for i in range(40): chars.append(["-"]*40) for i in range(100): r = random.randint(0,39) c = random.randint(0,39) chars[r][c] = "X" time.sleep(0.1) display2(chars)
In the editor: you can combine these ideas with the great @GingerPlusPlus idea to avoid cls . The trick is to print a large number of backspaces.
First write your own version of cls :
def cls(n = 0): if n == 0: os.system('cls') else: print('\b'*n)
The first time it is called, skip it and it will simply clear the screen.
The following function pushes an array of characters into the command window in one large print and returns the number of characters printed (since this is the number of back spaces needed to move the cursor):
def display(chars): s = '\n'.join(''.join(row) for row in chars) print(s) return len(s)
Used as follows:
chars = [] for i in range(40): chars.append(["-"]*40) for i in range(100): n = 0 r = random.randint(0,39) c = random.randint(0,39) chars[r][c] = "X" time.sleep(0.1) cls(n) n = display(chars)
when the above code is running, the display changes smoothly, with almost no flicker.
source share