refactor code to fix animation issue: import os import time import threading import sys…
- User
refactor code to fix animation issue:
import os import time import threading import sys
ANSI color codes for console output
YELLOW = '\033[93m' BROWN = '\033[38;5;52m' RESET = '\033[0m'
Clear the screen based on the operating system
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear')
Generate the garden frame based on the current stage of animation
def generate_garden_frame(stage): # Base frame with soil layers frame = [ " ", " ", " ", " ", f"{BROWN}~~~~~~~~~~~~~~~~{RESET}", f"{BROWN}################{RESET}", f"{BROWN}################{RESET}", f"{BROWN}################{RESET}", f"{BROWN}################{RESET}", f"{BROWN}################{RESET}" ]
# Place the plant at the appropriate stage if stage < 4: frame[3 - stage] = f" {YELLOW}(q*){RESET} " elif 4 <= stage <= 7: frame[stage] = f"{BROWN}######{YELLOW}(q*){BROWN}######{RESET}" return "\n".join(frame)The main loop to display the animation
def display_animation(): while True: for stage in range(8): clear_screen() print(generate_garden_frame(stage)) time.sleep(0.5)
Listen for a key press to stop the animation
def listen_for_keypress(): if os.name == 'nt': # Windows import msvcrt msvcrt.getch() # Waits for any key press else: # Unix-based (Linux, macOS) import tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) raise KeyboardInterrupt
Start the animation with a background key listener
def start_animation(): clear_screen() # Clear the screen initially
key_listener = threading.Thread(target=listen_for_keypress, daemon=True) key_listener.start() try: display_animation() # Start the animation loop except KeyboardInterrupt: clear_screen() print("\nAnimation stopped.")Entry point of the script
if name == "main": start_animation()
Assistant