Okay, here's a Python program that creates a simple interactive ASCII drawing experience in your terminal.
This version uses basic Python input/output and doesn't require external libraries like curses, making it easy to run anywhere Python is installed. However, this means you'll have to press Enter after each command (like moving the cursor or drawing).
python
import os
import sys
import time # Optional: for a slight pause if needed, though not used heavily here
# --- Configuration ---
CANVAS_WIDTH = 40
CANVAS_HEIGHT = 20
BACKGROUND_CHAR = '.'
DEFAULT_DRAW_CHAR = '*'
CURSOR_MARKER = 'X' # Character to show the cursor location (only visible during display)
# --- Helper Functions ---
def clear_screen():
"""Clears the terminal screen."""
# Works on Windows ('nt') and Linux/macOS ('posix')
os.system('cls' if os.name == 'nt' else 'clear')
def create_canvas(width, height, fill_char):
"""Creates a new canvas (list of lists) filled with fill_char."""
return [[fill_char for _ in range(width)] for _ in range(height)]
def display_canvas(canvas, cursor_x, cursor_y, draw_char, message=""):
"""Displays the canvas, cursor, status, and any messages."""
clear_screen()
print("--- ASCII Draw ---")
# Store the character under the cursor to restore it after printing
original_char_under_cursor = canvas[cursor_y][cursor_x]
# Temporarily place the cursor marker for display
canvas[cursor_y][cursor_x] = CURSOR_MARKER
# Print canvas row by row
for y, row in enumerate(canvas):
print("".join(row)) # Join characters in the row into a string
# Restore the original character
canvas[cursor_y][cursor_x] = original_char_under_cursor
# Print status line
print("-" * CANVAS_WIDTH)
print(f"Cursor: ({cursor_x}, {cursor_y}) Draw Char: '{draw_char}' Commands: [WASD] Move, [P] Place, [C <char>] Change Char, [Clear], [Save <f>], [Load <f>], [Quit]")
if message:
print(f"Message: {message}")
print("-" * CANVAS_WIDTH)
print("Enter command: ", end="") # Prompt for input on the same line
def save_canvas(canvas, filename):
"""Saves the canvas content to a text file."""
try:
# Ensure filename has a .txt extension if none provided
if not filename.lower().endswith(".txt"):
filename += ".txt"
with open(filename, 'w') as f:
for row in canvas:
f.write("".join(row) + "\n")
return f"Canvas saved to {filename}"
except Exception as e:
return f"Error saving file: {e}"
def load_canvas(filename, expected_width, expected_height):
"""Loads a canvas from a text file."""
try:
# Ensure filename has a .txt extension if none provided
if not filename.lower().endswith(".txt"):
filename += ".txt"
with open(filename, 'r') as f:
lines = [line.rstrip('\n') for line in f] # Read lines and remove newline chars
# Basic validation
if not lines:
return None, "Error: File is empty."
if len(lines) != expected_height:
return None, f"Error: File height ({len(lines)}) doesn't match canvas height ({expected_height})."
if any(len(line) != expected_width for line in lines):
return None, f"Error: A line in the file doesn't match canvas width ({expected_width})."
# Create the new canvas from file lines
new_canvas = [list(line) for line in lines]
return new_canvas, f"Canvas loaded from {filename}"
except FileNotFoundError:
return None, f"Error: File not found: {filename}"
except Exception as e:
return None, f"Error loading file: {e}"
# --- Main Program Logic ---
def main():
canvas = create_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, BACKGROUND_CHAR)
cursor_x, cursor_y = CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2 # Start cursor in the middle
draw_char = DEFAULT_DRAW_CHAR
message = "Welcome to ASCII Draw!"
running = True
while running:
display_canvas(canvas, cursor_x, cursor_y, draw_char, message)
message = "" # Clear message after displaying it once
try:
command_line = input().strip().lower()
if not command_line: # Skip if user just presses Enter
continue
parts = command_line.split(maxsplit=1) # Split into command and optional argument
command = parts[0]
args = parts[1] if len(parts) > 1 else None
# --- Process Commands ---
if command == 'q' or command == 'quit':
running = False
message = "Goodbye!"
# Movement
elif command == 'w': # Up
if cursor_y > 0:
cursor_y -= 1
else: message = "Cannot move further up."
elif command == 's': # Down
if cursor_y < CANVAS_HEIGHT - 1:
cursor_y += 1
else: message = "Cannot move further down."
elif command == 'a': # Left
if cursor_x > 0:
cursor_x -= 1
else: message = "Cannot move further left."
elif command == 'd': # Right
if cursor_x < CANVAS_WIDTH - 1:
cursor_x += 1
else: message = "Cannot move further right."
# Drawing
elif command == 'p' or command == 'place': # Place character
canvas[cursor_y][cursor_x] = draw_char
message = f"Placed '{draw_char}' at ({cursor_x}, {cursor_y})"
# Change Draw Character
elif command == 'c' or command == 'char':
if args and len(args) == 1:
draw_char = args
message = f"Drawing character changed to '{draw_char}'"
elif args:
message = "Error: Please provide a single character after 'c'."
else:
message = "Error: Use 'c <char>' to change the drawing character (e.g., 'c #')."
# Clear Canvas
elif command == 'clear':
canvas = create_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, BACKGROUND_CHAR)
cursor_x, cursor_y = CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2 # Reset cursor too
message = "Canvas cleared."
# Save Canvas
elif command == 'save':
if args:
message = save_canvas(canvas, args)
else:
message = "Error: Please provide a filename (e.g., 'save mydrawing')."
# Load Canvas
elif command == 'load':
if args:
loaded_canvas, load_message = load_canvas(args, CANVAS_WIDTH, CANVAS_HEIGHT)
if loaded_canvas:
canvas = loaded_canvas
# Optional: reset cursor position on load, or keep it
# cursor_x, cursor_y = CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2
message = load_message
else:
message = "Error: Please provide a filename (e.g., 'load mydrawing')."
# Unknown command
else:
message = f"Unknown command: '{command_line}'"
except Exception as e:
# Catch unexpected errors gracefully
message = f"An unexpected error occurred: {e}"
# Optional: add a small pause to let user see the error
# display_canvas(canvas, cursor_x, cursor_y, draw_char, message)
# time.sleep(2)
# Final display before exiting
clear_screen()
# Re-display canvas without cursor for the final view
for row in canvas:
print("".join(row))
print("-" * CANVAS_WIDTH)
print(message) # Show the final message (e.g., "Goodbye!")
if __name__ == "__main__":
main()
How to Run:
Save the code above as a Python file (e.g., asciidraw.py).
Open your terminal or command prompt.
Navigate to the directory where you saved the file.
Run the program using: python asciidraw.py
How to Use:
The program will display an empty canvas (. characters) with a cursor (X) in the middle.
The status line at the bottom shows your current cursor position, the character you'll draw with (* initially), and the available commands.
Enter commands and press Enter:
w, a, s, d: Move the cursor Up, Left, Down, Right.
p (or place): Place the current drawing character (draw_char) at the cursor's position.
c <char>: Change the drawing character. Replace <char> with the single character you want to use (e.g., c #, c @, c +).
clear: Erase the entire canvas and reset the cursor.
save <filename>: Saves the current canvas to a text file named <filename>.txt. Example: save my_art will create my_art.txt.
load <filename>: Loads a drawing from <filename>.txt. The file must match the current canvas dimensions. Example: load my_art.
quit (or q): Exit the program. The final drawing will be printed one last time without the cursor.
Limitations & Potential Improvements:
Input Latency: You have to press Enter after every command (move, draw, etc.). This is the main limitation of not using libraries like curses.
No Real-time Cursor: The cursor (X) only updates after you press Enter.
Basic Tools: Only point drawing is supported. Lines, rectangles, fill, etc., would require more complex logic.
Fixed Size: The canvas size is fixed at the start.
Simple Save/Load: Only saves/loads the raw canvas characters. Doesn't store metadata like cursor position or current draw character.
Flicker:clear_screen() can cause noticeable flicker on some terminals. curses handles screen updates more smoothly.
Single Character Drawing: Only uses one character at a time.
This program provides a good foundation for a simple ASCII drawing tool. For a more responsive and advanced experience, you would typically use the curses library (available on Linux/macOS, requires windows-curses on Windows).