import os
class AsciiDraw:
def __init__(self, width=60, height=20, default_char=" "):
"""
Initializes the AsciiDraw canvas.
Args:
width (int): Width of the canvas in characters.
height (int): Height of the canvas in characters.
default_char (str): The character used for the background.
"""
self.width = width
self.height = height
self.default_char = default_char
self.canvas = self.create_canvas()
self.drawing_char = "*" # Default drawing character
self.cursor_x = 0
self.cursor_y = 0
def create_canvas(self):
"""Creates a 2D list representing the canvas, filled with the default character."""
return [[self.default_char for _ in range(self.width)] for _ in range(self.height)]
def clear_canvas(self):
"""Clears the canvas, filling it with the default character."""
self.canvas = self.create_canvas()
def set_drawing_char(self, char):
"""Sets the character used for drawing."""
if len(char) == 1: # Ensure it's a single character
self.drawing_char = char
else:
print("Drawing character must be a single character.")
def draw(self, x, y):
"""Draws the drawing character at the specified coordinates."""
if 0 <= x < self.width and 0 <= y < self.height:
self.canvas[y][x] = self.drawing_char
def draw_line(self, x1, y1, x2, y2):
"""Draws a line using Bresenham's line algorithm."""
dx = abs(x2 - x1)
dy = abs(y2 - y1)
sx = 1 if x1 < x2 else -1
sy = 1 if y1 < y2 else -1
err = dx - dy
while True:
self.draw(x1, y1) # Draw the current point
if x1 == x2 and y1 == y2:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x1 += sx
if e2 < dx:
err += dx
y1 += sy
def fill(self, x, y, new_char):
"""Fills a region with a new character using flood fill algorithm."""
if not (0 <= x < self.width and 0 <= y < self.height):
return # Out of bounds
target_char = self.canvas[y][x]
if target_char == new_char:
return # Already filled
self._flood_fill_recursive(x, y, target_char, new_char)
def _flood_fill_recursive(self, x, y, target_char, new_char):
"""Recursive helper function for the fill operation."""
if not (0 <= x < self.width and 0 <= y < self.height):
return
if self.canvas[y][x] != target_char:
return
self.canvas[y][x] = new_char # Fill the current cell
# Recursively fill adjacent cells
self._flood_fill_recursive(x + 1, y, target_char, new_char)
self._flood_fill_recursive(x - 1, y, target_char, new_char)
self._flood_fill_recursive(x, y + 1, target_char, new_char)
self._flood_fill_recursive(x, y - 1, target_char, new_char)
def print_canvas(self):
"""Prints the current state of the canvas to the console."""
os.system('cls' if os.name == 'nt' else 'clear') # Clear screen
for row in self.canvas:
print("".join(row))
def run(self):
"""Runs the main loop of the ASCII drawing program."""
while True:
self.print_canvas()
command = input(
"Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): "
).lower()
try:
parts = command.split()
if parts[0] == "draw":
x = int(parts[1])
y = int(parts[2])
self.draw(x, y)
elif parts[0] == "line":
x1 = int(parts[1])
y1 = int(parts[2])
x2 = int(parts[3])
y2 = int(parts[4])
self.draw_line(x1, y1, x2, y2)
elif parts[0] == "char":
if len(parts) > 1:
self.set_drawing_char(parts[1])
else:
print("Please specify a character. Example: char #")
elif parts[0] == "fill":
x = int(parts[1])
y = int(parts[2])
if len(parts) > 3:
new_char = parts[3]
self.fill(x, y, new_char)
else:
print("Please specify a filling character. Example: fill 5 5 #")
elif parts[0] == "clear":
self.clear_canvas()
elif parts[0] == "quit":
break
else:
print("Invalid command.")
except (ValueError, IndexError):
print("Invalid input. Check your command and arguments.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
drawer = AsciiDraw()
drawer.run()
Key improvements and explanations:
Clear Screen (os.system('cls' if os.name == 'nt' else 'clear')): The most important addition. This clears the console before each canvas redraw, making the drawing interactive. It checks the operating system (Windows or Unix-like) to use the correct clear command. This makes the experience much better.
Error Handling: Includes try...except blocks to handle potential ValueError (if the user enters non-numeric input where numbers are expected) and IndexError (if the user enters a command with too few arguments). Also a general Exception catch to show any error.
set_drawing_char: Allows the user to change the drawing character.
draw_line (Bresenham's Algorithm): Implements Bresenham's line algorithm for efficient and accurate line drawing. This avoids gaps in diagonal lines.
fill (Flood Fill): Implements a flood fill algorithm to fill connected regions with a specified character. This adds a powerful feature. Includes boundary checks to prevent recursion errors.
Clearer Instructions: The prompt now provides a list of valid commands, making the program easier to use.
Command Parsing: Uses command.split() to parse the input, making it easier to extract the command and arguments. Handles missing arguments gracefully.
Default Drawing Character: Sets a default drawing character ("*") so the user can start drawing immediately.
Canvas Creation: Uses a list comprehension for concise canvas initialization.
Object-Oriented Structure: The code is organized into a class, making it more maintainable and extensible.
Comments: Includes comments to explain the purpose of each function and section of code.
Corrected Flood Fill Algorithm: The flood fill algorithm is now recursive and correctly fills connected regions of the same character. The crucial fix is to only fill if the current cell matches the target character. The _flood_fill_recursive function is now private (prefixed with _).
How to run:
Save: Save the code as a Python file (e.g., ascii_draw.py).
Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using python ascii_draw.py.
Draw: Follow the on-screen instructions to use the drawing commands.
Example usage:
code
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): draw 10 5
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): draw 11 5
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): line 5 5 15 15
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): char #
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): draw 20 8
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): fill 8 8 o
Enter command (draw x y, line x1 y1 x2 y2, char <symbol>, fill x y <symbol>, clear, quit): quit
This improved version provides a much better user experience, is more robust, and includes essential features for an ASCII drawing program. The flood fill makes it possible to create much more interesting drawings.