The code is an implementation of looping text (similar to a circular buffer - wraps around when it reaches the edge of the defined bounds) with directional control.
The code is functional and works as intended, but I'm curious if there is anyway to improve the code even if it is only a small improvement (e.g. less garbage produced per loop cycle as a micro-optimisation, etc).
# cleaned up and improved prototype code for looping text scroll.
# added direction from the original code.
from sys import stdout
from time import sleep
global_shifted_text_array = []
global_text_length = 0
DIRECTION_LEFT_TO_RIGHT = -1
DIRECTION_RIGHT_TO_LEFT = 1
def set_text(text):
global global_shifted_text_array
global global_text_length
global_shifted_text_array = pad_text(text)
global_text_length = len(global_shifted_text_array)
def pad_text(text, padding = 5):
text += ' ' * padding
return list(text)
def shift_text(direction):
global global_shifted_text_array
range = xrange(global_text_length - 1, -1, -1) if direction == DIRECTION_LEFT_TO_RIGHT else xrange(global_text_length)
# by the time the zero element is set in the for loop.
# it is set to the last element (which is empty)
# so we have to account for this by correcting for it.
if direction == DIRECTION_RIGHT_TO_LEFT:
first_element = global_shifted_text_array[0]
for i in range:
global_shifted_text_array[i] = global_shifted_text_array[((i + direction) % global_text_length)]
# print 'global_shifted_text_array[{}] = global_shifted_text_array[{}]'.format(i, ((i + direction) % global_text_length))
if direction == DIRECTION_RIGHT_TO_LEFT:
global_shifted_text_array[global_text_length - 1] = first_element
def update_loop(direction = DIRECTION_LEFT_TO_RIGHT, frequency = 0.1):
while 1:
shift_text(direction)
stdout.write('\r{0}'.format(''.join(global_shifted_text_array)))
sleep(frequency)
set_text('Beautiful Lie')
update_loop()