python - cmd console game; reduction of blinking -


i'm writing arcanoid game in python on windows console , bothers me annoying blinking after every iteration of "displaying" loop. have idea how reduce it? part of code:

#-*- coding: utf-8 -*- import time import os  clear = lambda: os.system('cls') def gra():     koniec='0'     while koniec!='1':         in range(4):             j in range(10):                 print '[___]',             print '\n',         in range(10):             print '\n'         in range(10):             print ' ',         print '~~~~~~~~~~'         time.sleep(0.1)         clear() gra() 

there limit can do, gathering 1 big string , printing once between screen clears better number of small prints in loop. run following code , how better second half of program runs first half:

import time, os, random  def display1(chars):     os.system('cls')     row in chars:         print(''.join(row))  def display2(chars):     os.system('cls')     print('\n'.join(''.join(row) row in chars))   chars = [] in range(40):     chars.append(["-"]*40)  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 = [] in range(40):     chars.append(["-"]*40)  in range(100):     r = random.randint(0,39)     c = random.randint(0,39)     chars[r][c] = "x"     time.sleep(0.1)     display2(chars) 

on edit: can combine these ideas excellent idea of @gingerplusplus avoid cls. trick print large number of backspaces.

first -- write own version of cls:

def cls(n = 0):     if n == 0:         os.system('cls')     else:         print('\b'*n) 

the first time called -- pass 0 , clear screen.

the following function pushes character array command window in 1 big print , returns number of characters printed (since number of backspaces needed reposition cursor):

def display(chars):     s = '\n'.join(''.join(row) row in chars)     print(s)     return len(s) 

used thus:

chars = [] in range(40):     chars.append(["-"]*40)  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 above code run, display changes smoothly virtually no flicker.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -