# Sketchingpy

> Tiny tools for creative coding and interactive science in Python. Supporting portability across desktop, web, mobile, Jupyter notebooks, and static images. A Python creative coding library that enables anyone to start creative coding in minutes. Support games, visualizations, interactive science.

## Documentation Note

This file provides a compact overview of Sketchingpy. For the most comprehensive API reference with detailed examples and explanations, see: https://sketchingpy.org/reference.md

## Installation

### Desktop (Interactive)
```bash
pip install sketchingpy[desktop]
```
For full features including GUI dialogs:
```bash
pip install sketchingpy[desktopall]
```

### Static Images Only
```bash
pip install sketchingpy[static]
```

### Jupyter Notebook
```bash
pip install sketchingpy[notebook]
```

### Web (PyScript)
Add to your pyscript py-config:
```yaml
packages: ["sketchingpy"]
```

## Quick Start

### Basic Static Sketch
```python
import sketchingpy

sketch = sketchingpy.Sketch2D(500, 500)
sketch.clear('#F0F0F0')
sketch.set_fill('#C0C0C0')
sketch.set_stroke('#000000')
sketch.draw_ellipse(250, 250, 20, 20)
sketch.show()
```

### Interactive Sketch
```python
import sketchingpy

sketch = sketchingpy.Sketch2D(500, 500)

def draw(sketch):
    mouse = sketch.get_mouse()
    x = mouse.get_pointer_x()
    y = mouse.get_pointer_y()
    sketch.set_fill('#C0C0C0')
    sketch.set_stroke('#333333')
    sketch.draw_ellipse(x, y, 20, 20)

sketch.on_step(draw)
sketch.clear('#FFFFFF')
sketch.show()
```

### Coordinates

The default 0,0 position is upper left with positive x referring to number of pixels to right and positive y referring to number of pixels down but this may be changed through transform (translate, rotate).

## Core API Reference

### Sketch Creation

#### Sketch2D(width, height)
Create new sketch canvas with automatic backend selection.

#### Sketch2DStatic(width, height)
Static image renderer using Pillow backend.

#### Sketch2DApp(width, height)
Interactive renderer using Pygame backend.

#### Sketch2DWeb(width, height)
Web renderer for PyScript environments.

### Canvas Operations

#### clear(color)
Fill background with specified color.

#### show()
Display the sketch and start draw loop if interactive.

#### save_image(path)
Save sketch to image file.

### Drawing Functions

#### draw_ellipse(x1, y1, x2, y2)
Draw ellipse or circle at specified position. x2 is horizontal size, y2 is vertical size.

#### draw_rect(x1, y1, x2, y2)
Draw rectangle or square at specified position. x2 is horizontal size, y2 is vertical size.

#### draw_line(x1, y1, x2, y2)
Draw straight line between two points.

#### draw_arc(x1, y1, x2, y2, a1, a2)
Draw partial ellipse using starting and ending angles. x2 is horizontal size, y2 is vertical size, a1 is start angle, a2 is end angle.

#### draw_pixel(x, y)
Draw single pixel point.

#### set_ellipse_mode(mode)
Set coordinate interpretation for ellipses: 'center', 'radius', 'corner', 'corners'.

#### set_rect_mode(mode)
Set coordinate interpretation for rectangles: 'center', 'radius', 'corner', 'corners'.

#### set_arc_mode(mode)
Set coordinate interpretation for arcs: 'center', 'radius', 'corner', 'corners'.

### Styling

#### set_fill(color)
Set fill color using hex codes ('#FF0000') or color names.

#### set_stroke(color)
Set stroke/outline color.

#### set_stroke_weight(weight)
Set line thickness in pixels.

#### clear_fill()
Disable shape filling.

#### clear_stroke()
Disable shape outlines.

### Text

#### draw_text(x, y, content)
Draw text at specified position using current font.

#### set_text_font(identifier, size)
Set the font by identifier string and size in pixels.

#### set_text_align(horizontal_align, vertical_align='baseline')
Set text alignment. Horizontal values: 'left', 'center', 'right'. Vertical values: 'top', 'center', 'baseline', 'bottom'.

### Coordinate System

#### push_transform()
Save current transformation matrix to stack.

#### pop_transform()
Restore most recent transformation from stack.

#### rotate(angle)
Rotate coordinate system around current origin.

#### translate(x, y)
Move coordinate system origin.

#### scale(factor)
Scale coordinate system from current origin.

#### set_angle_mode(mode)
Set angle units: 'radians' or 'degrees'.

### Input Handling

#### get_mouse()
Get mouse input object for position and button state.

#### mouse.get_pointer_x()
Get current mouse X coordinate.

#### mouse.get_pointer_y()
Get current mouse Y coordinate.

#### mouse.get_buttons_pressed()
Get collection of mouse buttons currently pressed.

#### get_keyboard()
Get keyboard input object.

#### keyboard.get_keys_pressed()
Get list of currently pressed keys.

### Animation & Events

#### on_step(function)
Set callback function to execute each frame.

#### set_fps(rate)
Set target frames per second.

### Color Utilities

#### Color Formats
Colors can be specified as hex strings ('#FF0000', '#F00') or color names ('red', 'blue', 'green'). Color values are strings; RGB tuples are not a supported input format.

### Image Operations

#### draw_image(x, y, image)
Draw loaded image at specified position.

#### get_image(src)
Load image from file path or URL.


## Data Layer
Access file system and network for reading/writing data.

### Data Access

#### get_data_layer()
Get access to data layer for file/network operations (returns None if unavailable).

### Reading Data

#### get_csv(path)
Load CSV file as list of dictionaries.

#### get_json(path)
Read JSON file from local system or network.

#### get_text(path)
Read text file from local system or network.

### Writing Data

#### write_csv(records, columns, path)
Write list of dictionaries as CSV file.

#### write_json(target, path)
Write data as JSON file.

#### write_text(target, path)
Write string to text file.

### Data Examples
```python
# Read CSV data
records = sketch.get_data_layer().get_csv('example.csv')

# Read JSON data
data = sketch.get_data_layer().get_json('example.json')

# Write CSV data
records = [
    {'group': 'a', 'value': 1},
    {'group': 'b', 'value': 2}
]
sketch.get_data_layer().write_csv(records, ['group', 'value'], 'output.csv')
```

## Dialog Layer
Interactive dialog boxes for user interaction.

### Dialog Access

#### get_dialog_layer()
Get access to dialog layer for user interaction (returns None if unavailable).

### Dialog Functions

#### show_alert(message, callback=None)
Show message dialog box to user.

#### show_prompt(message, callback)
Ask user for text input with callback.

#### get_file_load_location(callback)
Get file to load with callback function.

#### get_file_save_location(callback)
Get file save location with callback function.

### Dialog Examples
```python
# Show alert
sketch.get_dialog_layer().show_alert('Hello!')

# Get user input
sketch.get_dialog_layer().show_prompt('Enter text:', lambda x: print(x))

# File dialogs
sketch.get_dialog_layer().get_file_load_location(lambda filename: print(filename))
```

## Buffer System
Offscreen buffers for optimized drawing.

### Buffer Functions

#### create_buffer(name, width, height, background=None)
Create offscreen buffer for optimized drawing.

#### enter_buffer(name)
Switch drawing target to specified buffer.

#### exit_buffer()
Switch drawing target back to main canvas.

#### draw_buffer(x, y, name)
Draw buffer contents at specified position.

### Buffer Examples
```python
# Create and use buffer
sketch.create_buffer('example-buffer', 100, 50)
sketch.enter_buffer('example-buffer')
sketch.draw_ellipse(50, 25, 10, 10)
sketch.exit_buffer()
sketch.draw_buffer(100, 50, 'example-buffer')
```

## Geospatial Functions
Tools for geographic data visualization.

### Map Configuration

#### set_map_pan(longitude, latitude)
Set geographic center point for map projection.

#### set_map_placement(x, y)
Set pixel location where map center appears.

#### set_map_zoom(zoom)
Set map zoom level.

#### push_map()
Save current map configuration to stack.

#### pop_map()
Restore saved map configuration from stack.

### Geographic Shapes

#### start_geo_polygon(longitude, latitude)
Create new geographic polygon starting at coordinates.

#### add_coordinate(longitude, latitude)
Add point to current geo polygon.

#### to_shape()
Convert geo polygon to pixel-space shape.

#### convert_geo_to_pixel(longitude, latitude)
Convert geographic coordinates to pixel coordinates.

#### parse_geojson(source)
Parse GeoJSON data into geo polygon objects.

### Geospatial Examples
```python
# Map setup
sketch.set_map_pan(1, 2)
sketch.set_map_placement(100, 200)
sketch.set_map_zoom(10)

# Geographic polygon
geo_polygon = sketch.start_geo_polygon(1, 2)
geo_polygon.add_coordinate(3, 4)
shape = geo_polygon.to_shape()

# GeoJSON
source = sketch.get_data_layer().get_json('example.geojson')
geo_polygons = sketch.parse_geojson(source)
```

## Advanced Shape Functions
Complex shape creation with lines and curves.

### Shape Creation

#### start_shape(x, y)
Start new complex shape at specified position.

#### add_line_to(x, y)
Add straight line segment to current shape.

#### add_bezier_to(cx1, cy1, cx2, cy2, x, y)
Add bezier curve segment to current shape.

#### close()
Close shape with line to start (enables filling).

#### end()
Finish shape without closing (stroke only).

#### draw_shape(shape)
Draw completed shape object.

### Shape Properties

#### get_is_closed()
Check if shape is closed and can be filled. Requires a finished shape (call end or close first); raises an error otherwise.

#### get_is_finished()
Check if shape is complete and ready to draw.

#### get_min_x(), get_max_x(), get_min_y(), get_max_y()
Get shape bounding box coordinates. Require a finished shape (call end or close first); raise an error otherwise.

#### get_start_x(), get_start_y()
Get shape starting point coordinates.

#### get_segments()
Get list of shape segment objects.

### Shape Examples
```python
# Simple shape
shape = sketch.start_shape(50, 100)
shape.add_line_to(150, 200)
shape.add_line_to(150, 250)
shape.close()
sketch.draw_shape(shape)

# Bezier curve
shape = sketch.start_shape(50, 100)
shape.add_bezier_to(60, 110, 140, 190, 150, 200)
shape.end()
sketch.draw_shape(shape)
```

## Advanced Styling
Extended styling and color management.

### Style Stack

#### push_style()
Save current style settings to stack.

#### pop_style()
Restore most recent style settings from stack.

#### clear_fill()
Disable shape filling (transparent fill).

#### clear_stroke()
Disable shape outlines (no stroke).

### Style Examples
```python
# Style management
sketch.set_fill('#00C000')  # Green
sketch.push_style()
sketch.set_fill('#C00000')  # Red
sketch.pop_style()  # Back to green
```

## Advanced Drawing Modes
Shape positioning and sizing modes.

### Drawing Modes

#### set_ellipse_mode(mode)
Set coordinate interpretation for ellipses: 'center', 'radius', 'corner', 'corners'.

#### set_rect_mode(mode)
Set coordinate interpretation for rectangles: 'center', 'radius', 'corner', 'corners'.

#### set_arc_mode(mode)
Set coordinate interpretation for arcs: 'center', 'radius', 'corner', 'corners'.

#### set_image_mode(mode)
Set image positioning mode: 'center', 'corner'.

#### draw_pixel(x, y)
Draw single pixel using current fill color.

## Advanced Input Handling
Extended keyboard and mouse functionality.

### Advanced Mouse

#### get_buttons_pressed()
Get list of currently pressed mouse buttons.

#### get_pointer_x(), get_pointer_y()
Get exact mouse coordinates.

#### on_button_press(callback)
Set callback for mouse button press events.

#### on_button_release(callback)
Set callback for mouse button release events.

### Advanced Keyboard

#### on_key_press(callback)
Set callback for key press events.

#### on_key_release(callback)
Set callback for key release events.

### Input Examples
```python
# Mouse callbacks
callback = lambda button: print(button.get_name())
sketch.get_mouse().on_button_press(callback)

# Keyboard callbacks
callback = lambda button: print(button.get_name())
sketch.get_keyboard().on_key_press(callback)

# Check pressed keys
buttons = sketch.get_keyboard().get_keys_pressed()
if len(buttons) > 0:
    print(buttons[0].get_name())
```

## System Functions
Core system operations and sketch management.

### Sketch Control

#### show()
Display sketch and start draw loop.

#### show_and_quit()
Show sketch then quit immediately.

#### quit()
Stop sketch execution.

#### on_quit(callback)
Set callback for when sketch ends.

#### print(message)
Print message to console/terminal.

#### get_native()
Get underlying renderer object for advanced operations.

#### get_millis_shown()
Get milliseconds since sketch was shown.

### Sketch Configuration

#### set_fps(rate)
Set target frames per second for animation.

#### set_title(title)
Set window title (desktop) or document title (web); no-op on static renderer.

### System Examples
```python
# Callbacks
def callback(sketch_drawing):
    print('Drawing')
sketch.on_step(callback)

# Frame rate and display
sketch.set_fps(10)
sketch.show()
```

## Advanced Text
Text rendering with fonts and alignment.

### Text Functions

#### set_text_font(font, size)
Set font file and size for text rendering.

#### set_text_align(horizontal, vertical='baseline')
Set text alignment - horizontal: 'left', 'center', 'right'; vertical: 'top', 'center', 'baseline', 'bottom'.

### Text Examples
```python
# Font and text
sketch.set_text_font('./IBMPlexMono-Regular.ttf', 12)
sketch.set_text_align('left', 'baseline')
sketch.draw_text(50, 100, 'Hello World')
```

## Transform System
Advanced coordinate system manipulation.

### Transform Functions

See Coordinate System section above for transformation functions.

### Transform Examples
```python
# Transformation matrix
sketch.push_transform()  # Save state
sketch.translate(50, 0)  # Move right 50 pixels
sketch.rotate(90)  # Rotate 90 degrees
sketch.pop_transform()  # Restore state
```

## Renderer Types
Different rendering backends for various platforms.

### Renderer Classes

#### Sketch2D
Auto-select renderer based on environment. `Sketch2D` is a type alias resolved at import time: Jupyter notebook environment -> `Sketch2DStatic`; desktop (Pygame available) -> `Sketch2DApp`; PyScript/web -> `Sketch2DWeb`. Use the constructor of the resolved class.

#### Sketch2DApp(width, height, title=None, loading_src=None)
Desktop renderer using Pygame backend.

#### Sketch2DStatic(width, height, title=None, loading_src=None)
Static image renderer using Pillow backend.

#### Sketch2DWeb(width, height, element_id='sketch-canvas', loading_id='sketch-load-message')
Web browser renderer.

### Renderer Examples
```python
# Different renderers
sketch_auto = sketchingpy.Sketch2D(500, 500)
sketch_desktop = sketchingpy.Sketch2DApp(500, 500, 'Window Title')
sketch_static = sketchingpy.Sketch2DStatic(500, 500)
sketch_web = sketchingpy.Sketch2DWeb(500, 500, element_id='canvas-id')
```

## Future Features
Planned functionality for upcoming releases.

### Sound System (Future)

#### get_sound_layer()
Access to sound system.

#### get_sound(path)
Load sound file.

#### play_once(), play_in_loop()
Play sound once or in loop.

#### stop_playing()
Stop sound playback.

### Joystick System (Future)

#### get_joysticks()
Get available joystick devices.

#### get_input_axis(name)
Get joystick axis input.

#### get_triggers_available()
Get available buttons/triggers.

#### on_state_change(callback)
Set joystick callback.

## Common Patterns

### Animation Loop
```python
import sketchingpy

sketch = sketchingpy.Sketch2D(400, 400)
angle = 0

def animate(sketch):
    global angle
    sketch.clear('#FFFFFF')
    sketch.push_transform()
    sketch.translate(200, 200)
    sketch.rotate(angle)
    sketch.set_fill('#FF0000')
    sketch.draw_rect(0, 0, 50, 50)
    sketch.pop_transform()
    angle += 0.1

sketch.on_step(animate)
sketch.show()
```

### Interactive Drawing
```python
import sketchingpy

sketch = sketchingpy.Sketch2D(600, 400)
sketch.clear('#FFFFFF')

def draw(sketch):
    mouse = sketch.get_mouse()
    if len(list(mouse.get_buttons_pressed())) > 0:
        sketch.set_fill('#0000FF')
        sketch.draw_ellipse(mouse.get_pointer_x(), mouse.get_pointer_y(), 10, 10)

sketch.on_step(draw)
sketch.show()
```

## Platform Notes

- **Desktop**: Full features, requires pygame-ce for interactivity
- **Web**: Pure Python, no external dependencies, works in browsers
- **Jupyter**: Inline display, good for data visualization
- **Static**: Headless operation, PIL/Pillow backend for image generation

Source: https://sketchingpy.org/llms-full.txt
