Created
March 29, 2023 13:45
-
-
Save robvanderleek/2228ccdb815e21a3fb1cc1220ce470f0 to your computer and use it in GitHub Desktop.
Code Along: Fun with Escape Codes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
def clear_screen(): | |
goto_position(1, 1) | |
print('\033[J', end='') | |
def goto_position(x, y): | |
print(f'\033[{y};{x}H', end='') | |
def put(x, y, c): | |
goto_position(x, y) | |
print(c) | |
def waggle(duck, snack): | |
if duck[0] < snack[0]: | |
duck[0] += 1 | |
elif duck[0] > snack[0]: | |
duck[0] -= 1 | |
elif duck[1] < snack[1]: | |
duck[1] += 1 | |
else: | |
duck[1] -= 1 | |
def random_position(): | |
return [random.randint(1, 78), random.randint(1,24)] | |
def random_snack(): | |
return random.choice(['🌭', '🍔', '🍕']) | |
def hide_cursor(): | |
print('\033[?25l', end='') | |
def show_cursor(): | |
print('\033[?25h', end='') | |
def loop(): | |
hide_cursor() | |
ducks = [random_position()] | |
snack = random_position() | |
snack_type = random_snack() | |
while True: | |
clear_screen() | |
put(snack[0], snack[1], snack_type) | |
next_ducks = [] | |
for duck in ducks: | |
put(duck[0], duck[1], '🦆') | |
waggle(duck, snack) | |
if duck == snack: | |
snack = random_position() | |
snack_type = random_snack() | |
next_ducks.append(random_position()) | |
if len(ducks) < 5: | |
next_ducks.append(duck) | |
else: | |
next_ducks.append(duck) | |
ducks = next_ducks | |
time.sleep(0.10) | |
try: | |
loop() | |
except: | |
clear_screen() | |
show_cursor() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment