5
\$\begingroup\$

I'm a student to programming. I currently just working a thing where the player can walk around a field of hashtags. so far you can only walk horizontally but before i go any further, i realized that the program flickers a lot? Is there any cure for this? I'm using python 3 on windows.

import os
from msvcrt import getch

def clear():
    os.system( 'cls' )

map1=("#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#")
def draw_setting(x):
    edit_map=list(map1)
    del edit_map[x]
    edit_map.insert(x,"o") #The player is represented by o
    print (*edit_map, sep='')

x=0
draw_setting(x)
while True:
    key = ord(getch()) #Fetching the key pressed
    if key==100: #If d is pressed
        if x<30:
            x=x+1
            load_map=1
    elif key==97: #If a is pressed
        if x>0:
            x=x-1
            load_map=1
    elif key=="stop":
        break
    if load_map==1: #Only render if necessary
        clear()
        draw_setting(x)
        load_map=0
\$\endgroup\$
1
\$\begingroup\$

You may want to use the curses library.

def clear():
    os.system('cls')

You complain about "flicker", which is related to perceptible "slowness". Almost certainly your environment supports xterm/vt100 ANSI escape sequences. You forked off a command, cls, that printed <ESC>[H to put cursor at top of screen, and <ESC>[2J to clear screen. You could more quickly print() such escape sequences.

map1=("#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#")

Please don't do that. Express it as map1 = '#' * 31

del edit_map[x]
edit_map.insert(x, "o")

Delete and insert both have linear cost, which is small for a 31-char string, but still, avoid turning O(1) ops into O(n) ops. Instead, just assign: edit_map[x] = 'o'.

You can reposition the cursor with a simple CR rather than ANSI sequences: print(edit_map + '\r'). That alone could make the flicker negligible.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.