Certainly! Let's enhance and expand upon your original script to create a more sophisticated and visually appealing terminal animation using the curses library in Python. This improved version will feature:
- Enhanced Syntax Highlighting: More accurate and diverse syntax highlighting resembling real programming languages.
- Dynamic Code Generation: Generates more complex and realistic code snippets.
- Advanced Animations: Introduces additional animations such as moving lines, variable speed updates, and interactive elements.
- Multiple Sections: Divides the screen into different sections like code editor, output console, and status bars.
- Responsive Design: Adjusts to different terminal window sizes gracefully.
- User Interactivity: Allows users to interact with the animation, such as pausing, resuming, or exiting.
Below is the comprehensive script with detailed comments and explanations to help you understand each component.
import curses
import time
import random
import textwrap
# Constants for colors
COLOR_KEYWORD = 1
COLOR_FUNCTION = 2
COLOR_VARIABLE = 3
COLOR_COMMENT = 4
COLOR_STRING = 5
COLOR_OPERATOR = 6
COLOR_NUMBER = 7
COLOR_DEFAULT = 8
COLOR_STATUS = 9
COLOR_BOX = 10
# List of programming language elements for code generation
KEYWORDS = [
"def", "return", "if", "elif", "else", "for", "while", "import",
"from", "class", "try", "except", "finally", "with", "as", "pass",
"break", "continue", "raise", "lambda", "yield", "global", "nonlocal"
]
FUNCTIONS = [
"connect", "disconnect", "process", "calculate", "check_status",
"log_error", "initialize", "render", "update", "fetch_data",
"send_response", "handle_request", "parse", "validate", "serialize"
]
VARIABLES = [
"data", "connection", "response", "value", "status", "output",
"result", "index", "item", "config", "buffer", "iterator", "temp"
]
OPERATORS = ["=", "+", "-", "*", "/", "==", "!=", "<", ">", "<=", ">=", "and", "or", "not"]
COMMENTS = [
"TODO: Refactor this function",
"FIXME: Handle edge cases",
"Note: Temporary workaround",
"Debugging variable values",
"Optimization needed here"
]
STRINGS = [
"Initializing system...",
"Connection established.",
"Processing data...",
"An error occurred.",
"Operation successful.",
"Loading resources...",
"Shutting down gracefully."
]
SYMBOLS = ["(", ")", "{", "}", "[", "]", ",", ":", ";", ".", "->", "=>"]
class AnimatedCodeDisplay:
def __init__(self, stdscr):
self.stdscr = stdscr
self.max_y, self.max_x = self.stdscr.getmaxyx()
self.code_window_height = self.max_y - 6
self.code_window_width = self.max_x - 4
self.code_lines = []
self.output_lines = []
self.status_message = "Initializing..."
self.animation_speed = 0.05 # Smaller is faster
self.running = True
self.paused = False
def setup_colors(self):
curses.start_color()
curses.use_default_colors()
curses.init_pair(COLOR_KEYWORD, curses.COLOR_BLUE, -1)
curses.init_pair(COLOR_FUNCTION, curses.COLOR_CYAN, -1)
curses.init_pair(COLOR_VARIABLE, curses.COLOR_GREEN, -1)
curses.init_pair(COLOR_COMMENT, curses.COLOR_YELLOW, -1)
curses.init_pair(COLOR_STRING, curses.COLOR_MAGENTA, -1)
curses.init_pair(COLOR_OPERATOR, curses.COLOR_RED, -1)
curses.init_pair(COLOR_NUMBER, curses.COLOR_BLUE, -1)
curses.init_pair(COLOR_DEFAULT, curses.COLOR_WHITE, -1)
curses.init_pair(COLOR_STATUS, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(COLOR_BOX, curses.COLOR_WHITE, curses.COLOR_BLUE)
def generate_code_line(self):
"""Generates a random code line with syntax-like elements."""
line_structure = random.choice([
self.generate_def_line,
self.generate_if_line,
self.generate_for_line,
self.generate_assignment_line,
self.generate_function_call_line,
self.generate_class_definition_line,
self.generate_try_except_line
])
return line_structure()
def generate_def_line(self):
"""Generates a function definition line."""
func_name = random.choice(FUNCTIONS)
params = ", ".join(random.sample(VARIABLES, k=random.randint(1, 3)))
line = f"{random.choice(KEYWORDS)} {func_name}({params}):"
return line
def generate_if_line(self):
"""Generates an if statement line."""
var = random.choice(VARIABLES)
op = random.choice(["==", "!=", "<", ">", "<=", ">=", "in", "not in"])
value = random.choice(VARIABLES + STRINGS + [str(random.randint(1, 100))])
line = f"{random.choice(KEYWORDS)} {var} {op} {value}:"
return line
def generate_for_line(self):
"""Generates a for loop line."""
var = random.choice(VARIABLES)
iterable = random.choice(["range(10)", "items", "data_list", "values"])
line = f"{random.choice(KEYWORDS)} {var} in {iterable}:"
return line
def generate_assignment_line(self):
"""Generates a variable assignment line."""
var = random.choice(VARIABLES)
operator = random.choice(OPERATORS)
value = random.choice(VARIABLES + STRINGS + [str(random.randint(1, 100))])
line = f"{var} {operator} {value}"
return line
def generate_function_call_line(self):
"""Generates a function call line."""
func = random.choice(FUNCTIONS)
args = ", ".join(random.sample(VARIABLES, k=random.randint(0, 3)))
line = f"{func}({args})"
return line
def generate_class_definition_line(self):
"""Generates a class definition line."""
class_name = ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ', k=1)) + ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=random.randint(3,7)))
line = f"{random.choice(KEYWORDS)} {class_name}:"
return line
def generate_try_except_line(self):
"""Generates a try-except block line."""
line = f"{random.choice(KEYWORDS)}:"
return line
def generate_output_line(self):
"""Generates a random output line."""
return random.choice(STRINGS)
def add_code_line(self):
"""Adds a generated code line to the code buffer."""
if len(self.code_lines) >= self.code_window_height - 2:
self.code_lines.pop(0) # Remove oldest line to maintain window size
self.code_lines.append(self.generate_code_line())
def add_output_line(self):
"""Adds a generated output line to the output buffer."""
if len(self.output_lines) >= 4:
self.output_lines.pop(0) # Keep output buffer limited
self.output_lines.append(self.generate_output_line())
def render_boxes(self):
"""Draws boxes around different sections."""
# Code Editor Box
self.draw_box(1, 2, self.code_window_height, self.code_window_width, " Code Editor ")
# Output Console Box
output_height = 4
self.draw_box(self.code_window_height + 2, 2, output_height, self.code_window_width, " Output Console ")
# Status Bar
self.draw_status_bar()
def draw_box(self, start_y, start_x, height, width, title=""):
"""Draws a box with a title."""
for y in range(start_y, start_y + height):
for x in range(start_x, start_x + width):
if y == start_y or y == start_y + height -1:
self.stdscr.addch(y, x, ord('-'), curses.color_pair(COLOR_BOX))
elif x == start_x or x == start_x + width -1:
self.stdscr.addch(y, x, ord('|'), curses.color_pair(COLOR_BOX))
else:
self.stdscr.addch(y, x, ord(' '), curses.color_pair(COLOR_DEFAULT))
# Add corners
self.stdscr.addch(start_y, start_x, ord('+'), curses.color_pair(COLOR_BOX))
self.stdscr.addch(start_y, start_x + width -1, ord('+'), curses.color_pair(COLOR_BOX))
self.stdscr.addch(start_y + height -1, start_x, ord('+'), curses.color_pair(COLOR_BOX))
self.stdscr.addch(start_y + height -1, start_x + width -1, ord('+'), curses.color_pair(COLOR_BOX))
# Add title
if title:
self.stdscr.addstr(start_y, start_x + 2, title, curses.color_pair(COLOR_BOX) | curses.A_BOLD)
def render_code(self):
"""Renders the code section with syntax highlighting."""
start_y = 2
start_x = 4
for idx, line in enumerate(self.code_lines):
x = start_x
tokens = self.tokenize_code_line(line)
for token, token_type in tokens:
color = curses.color_pair(COLOR_DEFAULT)
if token_type == "keyword":
color = curses.color_pair(COLOR_KEYWORD) | curses.A_BOLD
elif token_type == "function":
color = curses.color_pair(COLOR_FUNCTION) | curses.A_BOLD
elif token_type == "variable":
color = curses.color_pair(COLOR_VARIABLE)
elif token_type == "comment":
color = curses.color_pair(COLOR_COMMENT) | curses.A_DIM
elif token_type == "string":
color = curses.color_pair(COLOR_STRING)
elif token_type == "operator":
color = curses.color_pair(COLOR_OPERATOR)
elif token_type == "number":
color = curses.color_pair(COLOR_NUMBER)
elif token_type == "symbol":
color = curses.color_pair(COLOR_OPERATOR)
# Handle line wrapping
if x >= self.code_window_width + 2:
break
try:
self.stdscr.addstr(start_y + idx, x, token, color)
except curses.error:
pass # Prevents crash if trying to write outside window
x += len(token)
self.stdscr.refresh()
def tokenize_code_line(self, line):
"""Tokenizes a code line for syntax highlighting."""
tokens = []
words = line.split(' ')
for word in words:
if word in KEYWORDS:
tokens.append((word + ' ', "keyword"))
elif word.endswith('('): # Function
func_name = word[:-1]
tokens.append((func_name, "function"))
tokens.append( ('(', "symbol") )
elif word in FUNCTIONS:
tokens.append( (word, "function") )
elif word in VARIABLES:
tokens.append( (word + ' ', "variable") )
elif word in OPERATORS:
tokens.append( (word + ' ', "operator") )
elif word.startswith('#'):
tokens.append( (word, "comment") )
elif word.startswith('"') or word.startswith("'"):
tokens.append( (word + ' ', "string") )
elif word.isnumeric():
tokens.append( (word + ' ', "number") )
else:
tokens.append( (word + ' ', "default") )
return tokens
def render_output(self):
"""Renders the output console section."""
start_y = self.code_window_height + 3
start_x = 4
for idx, line in enumerate(self.output_lines):
try:
self.stdscr.addstr(start_y + idx, start_x, line, curses.color_pair(COLOR_STRING))
except curses.error:
pass
self.stdscr.refresh()
def draw_status_bar(self):
"""Draws the status bar at the bottom of the screen."""
status = f" {self.status_message} "
try:
self.stdscr.attron(curses.color_pair(COLOR_STATUS))
self.stdscr.addstr(self.max_y -1, 0, status.ljust(self.max_x))
self.stdscr.attroff(curses.color_pair(COLOR_STATUS))
except curses.error:
pass
self.stdscr.refresh()
def update_status(self, message):
"""Updates the status bar message."""
self.status_message = message
self.draw_status_bar()
def handle_input(self):
"""Handles user input for interactivity."""
self.stdscr.nodelay(True) # Non-blocking input
try:
key = self.stdscr.getch()
if key == ord('q'):
self.running = False
elif key == ord('p'):
self.paused = not self.paused
status = "Paused" if self.paused else "Resumed"
self.update_status(status)
elif key == ord('+'):
self.animation_speed = max(0.01, self.animation_speed - 0.01)
self.update_status(f"Speed: {self.animation_speed:.2f}s")
elif key == ord('-'):
self.animation_speed += 0.01
self.update_status(f"Speed: {self.animation_speed:.2f}s")
except:
pass # No input
def run_animation(self):
"""Main loop for running the animation."""
while self.running:
self.handle_input()
if not self.paused:
self.add_code_line()
if random.random() < 0.3:
self.add_output_line()
self.render_boxes()
self.render_code()
self.render_output()
# Randomly update status
if random.random() < 0.1:
self.update_status(random.choice(["Running...", "Processing...", "Awaiting input...", "Idle", "Executing command..."]))
time.sleep(self.animation_speed)
def start(self):
"""Initializes the display and starts the animation."""
self.setup_colors()
self.run_animation()
def main(stdscr):
# Clear screen
stdscr.clear()
# Create an instance of AnimatedCodeDisplay
animation = AnimatedCodeDisplay(stdscr)
# Start the animation
animation.start()
# Run the curses application
if __name__ == "__main__":
curses.wrapper(main)
Detailed Explanation
1. Importing Necessary Modules
import curses
import time
import random
import textwrap
- curses: Library for creating text-based user interfaces.
- time: Used for controlling animation speed.
- random: Generates random elements for dynamic content.
- textwrap: Assists in formatting text, though not heavily used here.
2. Color Constants and Syntax Elements
# Constants for colors
COLOR_KEYWORD = 1
COLOR_FUNCTION = 2
COLOR_VARIABLE = 3
COLOR_COMMENT = 4
COLOR_STRING = 5
COLOR_OPERATOR = 6
COLOR_NUMBER = 7
COLOR_DEFAULT = 8
COLOR_STATUS = 9
COLOR_BOX = 10
Defines constants to map different syntax elements to specific colors for better readability and aesthetic appeal.
KEYWORDS = [...]
FUNCTIONS = [...]
VARIABLES = [...]
OPERATORS = [...]
COMMENTS = [...]
STRINGS = [...]
SYMBOLS = [...]
Lists that contain various programming language elements used to generate dynamic and realistic code snippets.
3. AnimatedCodeDisplay Class
This class encapsulates all functionalities required to create the animated display.
a. Initialization
def __init__(self, stdscr):
self.stdscr = stdscr
self.max_y, self.max_x = self.stdscr.getmaxyx()
self.code_window_height = self.max_y - 6
self.code_window_width = self.max_x - 4
self.code_lines = []
self.output_lines = []
self.status_message = "Initializing..."
self.animation_speed = 0.05 # Smaller is faster
self.running = True
self.paused = False
- stdscr: The main window object from curses.
- max_y, max_x: Dimensions of the terminal window.
- code_window_height, code_window_width: Dimensions for the code editor section.
- code_lines, output_lines: Lists to store generated code and output lines.
- status_message: Message displayed in the status bar.
- animation_speed: Controls how fast the animation updates.
- running, paused: Flags to control the main loop and pause functionality.
b. Color Setup
def setup_colors(self):
curses.start_color()
curses.use_default_colors()
curses.init_pair(COLOR_KEYWORD, curses.COLOR_BLUE, -1)
...
curses.init_pair(COLOR_BOX, curses.COLOR_WHITE, curses.COLOR_BLUE)
Initializes color pairs that will be used for different syntax elements and UI components.
c. Code Generation Methods
These methods generate different types of code lines to simulate real programming code.
def generate_code_line(self):
...
return line_structure()
Randomly chooses a type of code line to generate.
Each specific generator (e.g., generate_def_line, generate_if_line, etc.) creates a particular structure of code line, such as function definitions, if statements, for loops, etc.
d. Output Line Generation
def generate_output_line(self):
"""Generates a random output line."""
return random.choice(STRINGS)
Simulates output messages that might appear in a console.
e. Buffer Management
def add_code_line(self):
...
def add_output_line(self):
...
Adds new lines to the code and output buffers while ensuring they don't exceed the designated window size.
f. Rendering Boxes
def render_boxes(self):
"""Draws boxes around different sections."""
# Code Editor Box
self.draw_box(1, 2, self.code_window_height, self.code_window_width, " Code Editor ")
# Output Console Box
output_height = 4
self.draw_box(self.code_window_height + 2, 2, output_height, self.code_window_width, " Output Console ")
# Status Bar
self.draw_status_bar()
Draws UI boxes around the code editor, output console, and status bar sections.
def draw_box(self, start_y, start_x, height, width, title=""):
...
# Add title
if title:
self.stdscr.addstr(start_y, start_x + 2, title, curses.color_pair(COLOR_BOX) | curses.A_BOLD)
Draws a box with borders and an optional title.
g. Rendering Code with Syntax Highlighting
def render_code(self):
"""Renders the code section with syntax highlighting."""
...
tokens = self.tokenize_code_line(line)
for token, token_type in tokens:
...
self.stdscr.addstr(start_y + idx, x, token, color)
self.stdscr.refresh()
Iterates through each line of code, tokenizes it, and applies appropriate color highlighting.
def tokenize_code_line(self, line):
...
return tokens
Breaks down a line of code into tokens with their corresponding types for syntax highlighting.
h. Rendering Output Console
def render_output(self):
"""Renders the output console section."""
...
self.stdscr.addstr(start_y + idx, start_x, line, curses.color_pair(COLOR_STRING))
self.stdscr.refresh()
Displays output messages in the designated console section.
i. Status Bar
def draw_status_bar(self):
"""Draws the status bar at the bottom of the screen."""
status = f" {self.status_message} "
...
self.stdscr.addstr(self.max_y -1, 0, status.ljust(self.max_x))
...
Displays the current status message at the bottom of the terminal.
j. User Input Handling
def handle_input(self):
"""Handles user input for interactivity."""
self.stdscr.nodelay(True) # Non-blocking input
try:
key = self.stdscr.getch()
if key == ord('q'):
self.running = False
elif key == ord('p'):
self.paused = not self.paused
status = "Paused" if self.paused else "Resumed"
self.update_status(status)
elif key == ord('+'):
self.animation_speed = max(0.01, self.animation_speed - 0.01)
self.update_status(f"Speed: {self.animation_speed:.2f}s")
elif key == ord('-'):
self.animation_speed += 0.01
self.update_status(f"Speed: {self.animation_speed:.2f}s")
except:
pass # No input
Allows users to control the animation:
- 'q': Quit the program.
- 'p': Pause/Resume the animation.
- '+': Increase animation speed.
- '-': Decrease animation speed.
k. Main Animation Loop
def run_animation(self):
"""Main loop for running the animation."""
while self.running:
self.handle_input()
if not self.paused:
self.add_code_line()
if random.random() < 0.3:
self.add_output_line()
self.render_boxes()
self.render_code()
self.render_output()
# Randomly update status
if random.random() < 0.1:
self.update_status(random.choice(["Running...", "Processing...", "Awaiting input...", "Idle", "Executing command..."]))
time.sleep(self.animation_speed)
Continuously updates the display by adding code and output lines, rendering UI components, handling user input, and updating the status message.
l. Starting the Animation
def start(self):
"""Initializes the display and starts the animation."""
self.setup_colors()
self.run_animation()
Sets up colors and begins the main animation loop.
4. Main Function and Execution
def main(stdscr):
# Clear screen
stdscr.clear()
# Create an instance of AnimatedCodeDisplay
animation = AnimatedCodeDisplay(stdscr)
# Start the animation
animation.start()
# Run the curses application
if __name__ == "__main__":
curses.wrapper(main)
- main: Initializes the
AnimatedCodeDisplay and starts the animation.
- curses.wrapper: Ensures proper initialization and termination of the curses application, handling any exceptions gracefully.
Usage Instructions
-
Save the Script:
Save the provided script to a file, for example, animated_code_display.py.
-
Run the Script:
Open your terminal and navigate to the directory containing the script. Run the script using Python:
python animated_code_display.py
-
Interacting with the Animation:
- Pause/Resume: Press
p to pause or resume the animation.
- Increase Speed: Press
+ to make the animation faster.
- Decrease Speed: Press
- to slow down the animation.
- Quit: Press
q to exit the program.
Enhancements Over the Original Script
-
Structured Layout:
- Divided the screen into distinct sections: Code Editor, Output Console, and Status Bar for better organization.
-
Advanced Syntax Highlighting:
- Implemented tokenization for different syntax elements such as keywords, functions, variables, comments, strings, operators, and numbers.
- Applied distinct colors and text attributes (like bold) to enhance readability.
-
Dynamic Code Generation:
- Generated more realistic and varied code snippets, including different structures like function definitions, if statements, loops, class definitions, and try-except blocks.
-
Responsive User Input:
- Allowed users to control the animation in real-time by pausing, resuming, and adjusting the speed.
-
Status Bar Updates:
- Provided dynamic status messages that reflect the current state of the animation, enhancing the interactivity.
-
Buffer Management:
- Managed code and output buffers to ensure that the display remains within the terminal window's dimensions, preventing overflow.
-
Error Handling:
- Included basic error handling to prevent crashes when drawing outside the window boundaries.
-
Code Organization:
- Organized the script into a class structure for better modularity and readability.
Final Thoughts
This enhanced script provides a more immersive and interactive terminal-based animation that simulates a dynamic code editor and output console. By leveraging Python's curses library, it offers a powerful foundation for creating text-based user interfaces and animations. You can further expand upon this script by adding features such as:
- Scrolling Mechanism: Allowing users to scroll through the code if it exceeds the window size.
- Syntax Accuracy: Implementing a more accurate syntax parser for better highlighting, possibly integrating with existing libraries.
- Interactive Editing: Enabling users to input their own code snippets within the animation.
- Additional UI Components: Incorporating more sections like a sidebar, toolbar, or log window.
Experimenting with these features can provide deeper insights into terminal UI development and enhance the functionality of your animations.