Skip to content

Commit 7561f46

Browse files
committed
Re-factor to put screen erase + screen draw as close as possible
1 parent d21c62d commit 7561f46

File tree

2 files changed

+7
-11
lines changed

2 files changed

+7
-11
lines changed

examples/readme_example.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ def keypress_event(e):
2323
game = SnakeGame()
2424

2525
while True:
26-
new_state = game.process(last_direction) # Produce new frame
27-
sys.stdout.write("\033[2J\n") # Clear terminal screen
28-
sys.stdout.write(new_state.to_string()) # Print new game state
29-
sys.stdout.flush() # Flush output
26+
new_state = game.process(last_direction) # Produce new frame
27+
new_state_string = new_state.to_string()
28+
sys.stdout.write("\033[2J\n" + new_state_string) # Clear terminal screen and print new game state
29+
sys.stdout.flush() # Flush output
3030
time.sleep(0.05)

snakeng/__main__.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,14 @@ def keypress_event(e):
3535
runtime_data['last_direction'] = ret
3636

3737

38-
def draw_screen(state):
39-
sys.stdout.write("\033[2J\n")
40-
sys.stdout.write(state.to_string())
41-
sys.stdout.flush()
42-
43-
4438
def process_frame(game, frame_time):
4539
runtime_data["scheduler_event"] = scheduler.enterabs(time.time() + frame_time, 0, process_frame, argument=(game, frame_time))
4640

4741
if not runtime_data['paused']:
4842
new_state = game.process(runtime_data['last_direction'])
49-
draw_screen(new_state)
43+
new_state_string = new_state.to_string()
44+
sys.stdout.write("\033[2J\n" + new_state_string)
45+
sys.stdout.flush()
5046

5147
if new_state.dead:
5248
scheduler.cancel(runtime_data["scheduler_event"])

0 commit comments

Comments
 (0)