Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmd console game; reduction of blinking

Tags:

python

I'm writing an arcanoid game in python on windows console and what bothers me is annoying blinking after every iteration of "displaying" loop. Does anyone have any idea how to reduce it? This is part of the code:

#-*- coding: UTF-8 -*-
import time
import os

clear = lambda: os.system('cls')
def gra():
    koniec='0'
    while koniec!='1':
        for i in range(4):
            for j in range(10):
                print '[___]',
            print '\n',
        for i in range(10):
            print '\n'
        for i in range(10):
            print ' ',
        print '~~~~~~~~~~'
        time.sleep(0.1)
        clear()
gra()
like image 844
Jarshah Avatar asked Jan 16 '16 14:01

Jarshah


1 Answers

There is a limit to what you can do, but gathering everything into 1 big string and then printing once between screen clears is better than a number of small prints in a loop. Run the following code and look how much better the second half of the program runs 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)

On Edit: You can combine these ideas with the excellent idea of @GingerPlusPlus 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 -- pass it zero and it just clear the screen.

The following function pushes a character array to the command window in one big print and returns the number of characters printed (since this is the number of backspaces needed to reposition the cursor):

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

Used like thus:

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 run, the display changes smoothly with virtually no flicker.

like image 140
John Coleman Avatar answered Oct 07 '22 15:10

John Coleman