# Tychos Python Language Reference

The following reference guide identifies the language syntax, built in variables, functions, and classes that are used to code your simulations using the Python Language. We have included documentation here for some of the helpful functions defined in the Python language. This is not a complete list of all functions available in Python, just ones that might be commonly used in Tychos for building scenarios as well as defining goals for those scenarios.

## Comments

Comments are statements that you can insert in your code that do not get interpreted and executed by Tychos. To create a comment, you simply indicate a comment by using a hashtag:

```python
# This is a comment.
```

## Variables

To define a variable in Tychos all you need to do is identify a name for the variable. You then type an `=` sign to assign a value to the variable. The following demonstrates various variable declarations

```python
# Assigns a variable called x the value of 10
x = 10
# Assign a new variable y the value of the x
y = x
# Assign x the value of itself plus 1
x = x + 1
```

## Built-in Scenario Variables

There are a few variables that are built into Tychos. These variables are:

* `t` — How many seconds has passed since this Scenario was started?
* `dt` — Time between frames as seconds, e.g. 0.1 is 1/10th of a second.
* `frame_count` — How many frames have passed? e.g. 1, 2, 3...

## Common Math Operators and Functions

These are some common mathematical operators and functions for performing various calculations.

### Mathematical Operators

Tychos uses the following operators to perform basic math calculations:

* `+` — Addition
* `-` — Subtraction
* `*` - Multiplication
* `/` - Division
* \*\* - Exponent
* `%` - Modulo

### Basic Math Functions

You can also use the following basic math functions:

#### **sqrt(positive\_number)**

The `sqrt(positive_number)` function takes a single non negative number and returns the real square root of the number.

```python
# returns number 2
sqrt(4)
```

#### **exp(power)**

The `exp(power)` function calculates Euler's number (e) to the given power.

```python
# returns 54.59815
exp(4)
```

#### **log(x)**

The `log(x)` returns the natural log (base e) of x.&#x20;

```python
# returns number 2
abs(-2)
```

#### **ceil(x)**

The `ceil(x)` function rounds a number *up* to the nearest integer.

```python
# returns 5
exp(4.1)
```

#### **floor(x)**

The `floor(x)` function rounds a number *down* to the nearest integer.

```python
# returns 4
exp(4.9)
```

#### **sign(x)**

The `sign(x)` function returns +1 if x is less than 0, -1 if x is greater than 0, and 0 if x is equal to 0.

```python
# returns -1
sign(-42)
# returns 1
sign(42)
# returns 0
sign(0)
```

#### **abs(x)**

The `abs(x)` function returns the absolute value of a number.

```python
# returns number 2
abs(-2)
```

#### **random()**

The `random()` function returns a *semi random* number between 0 and 1.

```python
x = random()
```

**randrange(a, b)**

The `randrange(a,b)` function returns a *semi random* number between `a` and `b`.

```python
x = randrange(10, 100)
```

#### **factorial(x)**

The `factorial(x)` function calculates the product of all positive integers less than or equal to the given positive integer.

```python
# x! = x*(x-1)*(x-2)....(1)
# returns 120
factorial(5)
```

#### **combin(n, r)**

The `combin(x,y)` function calculates the number of ways to choose a sample of r elements from a set of n distinct objects where order does not matter and replacements are not allowed.

```python
# x!/(y!*(x-y)!)
# returns 10
combin(5,2)
```

### Trigonometric Functions

The following functions all use radians as the angle measurement. You can use `pi` to represent PI.

#### **sin(angle)**

The `sin(angle)` function is used to evaluate the trigonometric sine value for a given input angle. The input angle must be provided in radians.

```python
# returns number 1
sin(pi/2)
```

#### **cos(angle)**

The `cos(angle)` function is used to evaluate the trigonometric cosine value for a given input angle. The input angle must be provided in radians.

```python
# returns number 1
cos(0)
```

#### **tan(angle)**

The `tan(angle)` function is used to evaluate the trigonometric tangent value for a given input angle. The input angle must be provided in radians.

```python
# returns number 1
tan(pi/4)
```

#### **asin(value)**

The `asin(value)` function is used to evaluate the trigonometric arcsine value (inverse sine) for a given input. The output angle is given in radians.

```python
# returns number 1.57
asin(1)
```

#### **acos(value)**

The `acos(value)` function is used to evaluate the trigonometric arccosine value (inverse cosine) for a given input. The output angle is given in radians.

```python
# returns number 0
acos(1)
```

#### **atan2(x, y)**

The `atan2(value)` function is used to evaluate the trigonometric arctangent value (inverse tangent) for a given x and y input. The output angle is given in radians.

```python
# returns number -0.785
atan2(-1, 1)
# returns 2.36
atan2(1, -1)
```

**radians(angle)**

The input is an angle measurement in degrees and the output is the angle measurement in radians.

```python
# returns number .785
radians(45)
```

**degrees(angle)**

The input is an angle measurement in radians and the output is the angle measurement in degrees.

```python
# returns number 180
degrees(pi)
```

## Vector and Vector Functions

The following functions provide operations for creating and using vectors in calculations.

#### **vec(x, y), or vec(x,y,z)**

Creates a **Vector** object representing a 3d vector with components identified as x, y, and z.

```python
# Create a vector with components x=2, y=2, z=0
v1 = vec(2,2)

# Create a vector with components x=2, y=2, z=2
v2 = vec(2,2,2)

# Change a component of the vector:
v1.x = 3
```

#### **Adding and Subtracting Vectors**

Vectors can be added or subtracted from one another using standard +, - operators:

```python
v1 = vec(2,2)
v2 = vec(1,1)

# Add the two vectors together:
v3 = v1 + v2 # Returns vec(3,3,0)
```

#### **Multiplying and Dividing By A Scalar**

Vectors can also by scaled using the standard \*, / operators:

```python
v1 = vec(2,2)

# Multiply by a scalar
v2 = 2 * v1 # Returns vec(4,4,0)

# Divide by a scalar
v3 = v1 / 2 # Returns vec(1,1,0)
```

#### **dot(v1, v2)**

Calculates the dot product of two Vector objects.

```python
# Work is the dot product of Force (F) and displacement (r)
F = vec(2, 2)
r = vec(3, 3)
# returns 12
Work = dot(F, r)
```

#### **cross(v1, v2)**

Calculates the cross product for two vectors in three dimensional space.

```python
# Torque is the cross product of Force and moment arm (r)
F = vec(2, 0, 0)
r = vec(0, 2, 0)
# returns Vector vec(0, 0, 4)
cross(F, r)
```

#### **norm(vec)**&#x20;

Same as `hat`. See below.

#### **hat(vec)**&#x20;

This function returns a unit vector representation of the given input vector. Its magnitude is 1 and the direction matches the direction of the input vector. This can be useful if you need just the direction of a vector, but not its magnitude.

* `vec` - any two or three dimensional vector.

Example:

```python
u = hat(vec(3, 4))  # returns vec(0.6, 0.8, 0)
mag(u)             # returns 1
```

#### **mag(vec)**

This function returns the scaler magnitude of any given vector. This is helpful when you want to know the length of a vector, for example, if you want the magnitude of a vector, but not the direction.

* `vec` - any two or three dimensional vector.

Example:

```python
mag(vec(3, 4))             # returns 5
```

**mag2(vec)**

This function returns the scaler squared magnitude of any given vector.

* `vec` - any two or three dimensional vector.

Example:

```python
mag2(vec(3, 4))             # returns 25
```

#### **diff\_angle(vec1, vec2)**

This function returns the angle between two vectors. The angle value is returned in radians.

* `vec1` - any two or three dimensional vector.
* `vec2` - any two or three dimensional vector.

Example:

```python
# returns 0.7853981633974484
diff_angle(vec(4, 4), vec(4, 0))
```

#### **proj(vec1, vec2)**

This function returns the vector projection of `vec1` along `vec2`.

* `vec1` - any two or three dimensional vector.
* `vec2` - any two or three dimensional vector.

#### **comp(vec1, vec2)**

This function returns the scalar projection of `vec1` along `vec2`.

* `vec1` - any two or three dimensional vector.
* `vec2` - any two or three dimensional vector.

#### **distance**(point1, point2)

This function returns a scalar quantity representing the distance between two points.

* `point1` - any two or three dimensional vector representing a point in space.
* `point2` - any two or three dimensional vector representing a point in space.

Example:

```
distance(vec(5,5), vec(3,3))            # returns 2.8284271247461903
```

#### **direction(vec)**

This function returns a scalar angle measurement. This is helpful when you want to know the direction of a vector, like the direction of a velocity vector, or the direction of a force vector. The returned angle is given in radians, measured from the positive x axis.

* `vec` - any two or three dimensional vector.

Example:

```
direction(vec(4, 4))             # returns 0.7853981633974483
```

#### polar(radius, angle)

This function returns a two-dimensional vector representing the cartesian components of a polar coordinate corresponding to the magnitude of the radius and the radial angle.

* `radius` - scalar quantity representing the scalar distance of the radius of the&#x20;
* `angle` - scalar quantity representing the angle measurement of the polar coordinate.

Example:

```
polar(10, pi/4)            # returns vec(7.07, 7.07, 0)
```

#### get\_rotated\_position(position, angle, axis)

This function is simply used for finding a point that has been rotated a given angle about a specific axis. It is just a utility function that could be performed by doing some simple trigonometry calculations, but hey, why not make it easier for you?

* `position` - A vector representing the point that is rotated.&#x20;
* `angle` - scalar quantity representing the angle measurement of rotation.
* `axis` - A 2D vector that identifies the axis point about which the position has been rotated.

Example:

```
get_rotated_position(vec(10, 0), pi, vec(0, 0))            # returns vec(-10, 0, 0)
```

## Other Useful Functions

Some other useful functions...\_

#### rgb(r, g, b)

This function returns a hexadecimal value for the red, green, and blue input values. This can be useful for setting the color of an object based on the RGB color model.

* `r` - a value between 0 and 255 representing the RED of RGB.
* `g` - a value between 0 and 255 representing the GREEN of RGB.
* `b`- a value between 0 and 255 representing the BLUE of RGB.

Example:

<pre class="language-python"><code class="lang-python"><strong>color = rgb(100, 100, 0)            # returns '#646400'
</strong></code></pre>

#### stop()

This function interrupts the simulation and stops it at the current frame.

`stop()` -> stops the simulation.

Example:

{% code lineNumbers="true" %}

```python
if buggy.pos.x > 100:
    stop()             # simulation stops
```

{% endcode %}

### Collision Functions

{% hint style="info" %}
Currently `circle` ,`rectangle` , and `line` objects work with any of the collision functions. We are working to add other objects soon.
{% endhint %}

The following functions are meant to help users model collisions more easily. These functions could be used for other purposes rather than modeling collisions as Tychos is not a physics engine. These functions could be thought of as "overlap" functions. They return information about the *overlap* of objects.

#### has\_collided(source, target)

This function returns a boolean true/false value when two objects are given as the source and target. It returns false if the two objects are not determined to be *overlapping.*

* `source` - `circle` or `rectangle` or `line` object
* `target` - `circle` or `rectangle` or `line` object

Example:

![](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-M1Gz_JkgHeb2qElY8fn%2F-M1H2ldqYMhdQkM2Jgls%2FhasCollided_example.png?alt=media\&token=85865cc7-cb6a-4641-99e9-dbf613a90e41)

{% code lineNumbers="true" %}

```python
# Setup Code
p1 = circle(pos=vec(15, 0), radius=10, color=rgb(0, 200, 200), opacity=.6)
b1 = rectangle(pos=vec(0, 0), size=vec(15, 15), color=rgb(200, 0, 200), opacity=.6)
b1.rotate(radians(45))
p3 = circle(pos=vec(-15, 0), radius=10, color=rgb(0, 0, 200), opacity=.6)
```

{% endcode %}

{% code lineNumbers="true" %}

```python
# Loop Code
has_collided(p1, b1)            # returns True
has_collided(b1, p3)            # returns True
has_collided(p1, p3)            # returns False
```

{% endcode %}

#### get\_mtv(source, target)

This function returns a two dimensional vector representing the *minimum translation vector* (MTV) that would be needed to separate two objects when they overlap. This can be used to simulate collision forces or to move objects apart based on the magnitude and direction of the MTV.

* `source` - `circle` or `rectangle` or `line` object
* `target` - `circle` or `rectangle` or `line` object

Example:

![](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-M1Gz_JkgHeb2qElY8fn%2F-M1H6tG9DYavjNO3G2O5%2FgetIntersect_example.png?alt=media\&token=3872a6a6-6dbc-4ecf-831f-0891a9ca540b)

{% code lineNumbers="true" %}

```python
# Setup Code
p1 = circle(pos=vec(0, 0), radius=10, color=rgb(200, 200, 200), opacity=.6)
p2 = circle(pos=vec(12, 10), radius=10, color=rgb(0, 200, 0), opacity=.6)
b1 = rectangle(pos=vec(-12, 0), size=vec(15, 15), color=rgb(200, 0, 0), opacity=.6)
mtv1 = arrow(pos=p1.pos, color="green")
mtv2 = arrow(pos=p1.pos, color="red")
```

{% endcode %}

{% code lineNumbers="true" %}

```python
# Loop Code
mtv1.size = get_mtv(p1, p2)
mtv2.size = get_mtv(p1, b1)
```

{% endcode %}

#### get\_intersections(source, target)

This function returns a list containing all the points where the object boundaries intersect. The points are vectors corresponding with the coordinates of those intersection locations. This can be used to identify exactly where the overlap is occurring in your scenarios.

* `source` - `circle` or `rectangle` or `line` object
* `target` - `circle` or `rectangle` or `line` object

The image below shows an example of the points of intersection between a rectangle and a line, but note, those points are being showed for demonstration only, and would not be visible unless you assign them to a visible object, in this case the position of two small circle objects.

![](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FamaLa1f73BGYsCPQwceI%2FScreen%20Shot%202023-04-29%20at%209.00.28%20AM.png?alt=media\&token=8fdd3ccd-35e1-4eaa-a657-e7d7e87a8d4c)

Example:

{% code lineNumbers="true" %}

```python
# Setup Code
r = rectangle(pos=vec(-4, 0), size=vec(10,15), color="orange", opacity=.5)
r.rotate(.1)
l = line(pos=vec(0,10), pos2=vec(-10, -20))
```

{% endcode %}

{% code lineNumbers="true" %}

```python
# Loop Code
points = get_intersections(r, ln)
```

{% endcode %}

### Logical Operators

The following operators are used to execute logical AND and OR comparisons for the use of evaluating logical statements.

#### **and**

This is used for performing a logical AND conjunction. For example, "A and B" is true only if A is true and B is true. "A and B" is false if either A or B is false.

{% code lineNumbers="true" %}

```python
A = True
B = True
A and B         # returns true
B = False
A and B         # returns false
```

{% endcode %}

You can use the `and` operator to test if two comparisons are both true:

{% code lineNumbers="true" %}

```python
x = 2
(x < 3) and (x == 2)  # returns True
(x < 3) and (x != 2)  # returns False
```

{% endcode %}

#### **or**

This is used for performing a logical OR conjunction. For example, "A or B" is true if A or B is true. "A or B" is false only if A and B are both false.

```
A = True
B = False
A or B # returns True
A = False
A or B # returns False
```

You can use the `or` operator to test if one of two comparisons are true:

```
x = 2
(x < 3) or (x == 3)    # one is true, so returns True
(x < 1) or (x == 3)             # both are false, so returns False
```

## Built-in Classes

Tychos has only a few classes that are used to create the basic simulated objects in the Tychos universe as well as a few tools for analyzing those objects in the simulated world. The graphical  objects in Tychos that can be used are:

* &#x20;[`circle`](#circle)&#x20;
* &#x20;[`rectangle`](#rectangle)&#x20;
* &#x20;[`ellipse`](#ellipse)&#x20;
* &#x20;[`arc`](#arc)&#x20;
* &#x20;[`arrow`](#arrow)&#x20;
* &#x20;[`line`](#line)&#x20;
* &#x20;[`label`](#label)&#x20;
* &#x20;[`spring`](#spring)&#x20;
* &#x20;[`poly_line`](#poly_line)&#x20;
* &#x20;[`sprite`](#sprite)&#x20;

There are also two gradient fill objects that can be added to some of the above graphical objects (circle, rectangle, ellipse, arc, poly\_line)

* &#x20;[`radial_gradient`](#radial_gradient)&#x20;
* &#x20;[`linear_gradient`](#linear_gradient)&#x20;

### Common Attributes

The following attributes are shared by most of the graphical objects listed above. Exceptions are noted below.

#### `pos` - vector

The position of of the graphic object scaled to the world. This is not a pixel position, but rather a position in the World as a vector with `x,y,z` coordinates. Currently the z coordinate value does not affect the position of the object in the World. The `linear_gradient` and `radial_gradient` do not have these attributes

#### `color` - string

Objects will be drawn in this color. Use HTML colors e.g. "#ff3300", "blue", or the [`rgb`](#rgb-r-g-b) function.

#### `opacity` - float

Objects can be drawn with an opacity between 1 and 0, representing 100% opaque to 100% transparent.

#### `image` - string

Certain objects (**circle, rectangle, ellipse, arc**) can also be represented with an image by setting the image attribute of the object. The text can either be a URI link or an [asset reference](https://docs.tychos.org/docs/interface-overview#assets) to a graphic file that can be a PNG, SVG, GIF, or JPEG image.

Here is an example of using a URI for displaying a circle as an image:

```python
rocket = circle(pos=vec(0, 0), radius=10)
rocket.image = "https://upload.wikimedia.org/wikipedia/commons/3/3d/Spacecraft.png"
```

![A circle that looks like a rocket.](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-LEM5y6qSZGv3tkY5pGN%2F-LEMDYX74SDR4RTOlWVn%2Fdirection.png?alt=media\&token=f771875f-6b02-4758-aa44-a5ea880f035f)

{% hint style="info" %}
The above image also demonstrates the use of the `direction` function as well as the `rotate` method:

`rocket.rotate(direction(rocket.v))`
{% endhint %}

#### `no_fill` - boolean

If set to `True`, the area inside the object will be transparent.

#### `fill` - object

Optional argument for rendering the filled area with either a `linear_gradient` or `radial_gradient`

#### `visible`  - boolean

All objects can be hidden from view by setting this flag to `False`.&#x20;

#### `motion_map` - boolean

This flag tells Tychos to attach a series of strobe images called a motion map.

This is excellent! This event-driven model where the `target` (the object itself) is passed to the handler is very powerful and clean.

Here is the updated documentation section. I have listed all the event hooks you provided and updated the example to show the `target` parameter pattern correctly.

***

### Mouse Interaction

All graphical objects in Tychos (`circle`, `rectangle`, `sprite`, `line`, `label`, etc.) are capable of detecting mouse events. You can make your simulation interactive by defining a Python function and assigning it to one of the object's event handlers.

**Event Attributes**

* `on_click` : *Function*

  Triggered when the mouse button is pressed and released on the object.
* `on_dbl_click` : *Function*

  Triggered when the mouse button is double-clicked on the object.
* `on_mouse_down` : *Function*

  Triggered when the mouse button is pressed down while over the object.
* `on_mouse_up` : *Function*

  Triggered when the mouse button is released while over the object.
* `on_mouse_move` : *Function*

  Triggered repeatedly when the mouse pointer is moving while over the object.
* `on_mouse_enter` : *Function*

  Triggered once when the mouse pointer enters the object's boundary.
* `on_mouse_leave` : *Function*

  Triggered once when the mouse pointer leaves the object's boundary.
* `on_mouse_over` : *Function*

  Triggered repeatedly while the mouse pointer is over the object (similar to `on_mouse_move`, but can fire even if the mouse is stationary).
* `on_mouse_out` : *Function*

  Triggered when the mouse pointer moves off the object (alias for `on_mouse_leave`).
* `on_context_menu` : *Function*

  Triggered when the right mouse button is clicked on the object (often used for custom menus).

**How to Use**

1. Define a function that accepts a single argument (commonly named `target` or `obj`). When the event fires, Tychos will call your function and pass the object that was clicked (the source of the event) as this argument.
2. Assign that function (without parentheses) to the object's event attribute.

**Examples**

1\. Click to Change Color

This example shows how the `target` argument allows you to write a generic handler that can be reused for multiple objects.

Python

```python
# 1. Define a generic handler
def change_color(target):
    # 'target' is the object that was clicked
    target.color = "green"

# 2. Create objects
c1 = circle(pos=vec(0, 0), radius=5, color="red")
c2 = circle(pos=vec(20, 0), radius=5, color="blue")

# 3. Attach the SAME handler to both
c1.on_click = change_color
c2.on_click = change_color
```

2\. Mouse Hover Effects

Use `on_mouse_enter` and `on_mouse_leave` to create highlight effects.

Python

```python
button = rectangle(size=vec(40, 20), color="gray")

def highlight(target):
    target.color = "white"

def unhighlight(target):
    target.color = "gray"

button.on_mouse_enter = highlight
button.on_mouse_leave = unhighlight
```

3\. Dragging an Object

Python

```python
box = rectangle(pos=vec(0, 0), size=vec(10,10))
box.is_dragging = False

def start_drag(target):
    target.is_dragging = True

def stop_drag(target):
    target.is_dragging = False

def drag_move(target):
    if target.is_dragging:
        # Move the target to the mouse position
        target.pos = mouse.pos

# Wire up the events
box.on_mouse_down = start_drag
box.on_mouse_up = stop_drag
box.on_mouse_move = drag_move
```

***

### Labels

The circle, rectangle, ellipse and arc objects can display a text label within their bounded areas. The text will scale with the object.

#### `label_text` - string

The text of an attached label.&#x20;

#### `label_color` - string

The color of the attached label text.

#### `label_font` - string

The font family of the attached label text.

#### `label_style` - dictionary

A dictionary whose key-value pairs match CSS font styling attributes of the attached label text.

### Borders

You can add a border to the circle, rectangle, ellipse, arc, and poly\_line objects:

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FODBSIIOXQFz2n0eYtgkf%2FScreen%20Shot%202022-03-09%20at%203.48.57%20PM.png?alt=media&#x26;token=8a347500-bd01-464e-94c1-4b775ce8610e" alt="" width="375"><figcaption><p>Borders with different sizes, colors, and styles.</p></figcaption></figure>

#### `border_size` - int

The border thickness in pixels.

#### `border_color`  - string

The border will be drawn in this color. Use HTML colors e.g. `"#ff3300"`, `"blue"`.

#### `border_style` - string

Sets the border as either solid (`default = "none"`) or `"dash"` for a dashed border, or `"dot"` for a dotted border.

### Effects

Objects can also be visually altered by setting the following attributes:

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FADc2GLFggP67YB0Axvrg%2Fskew-flip-blur.png?alt=media&#x26;token=6b4b6c20-23b7-412e-be5f-9ff55a2db18b" alt="" width="375"><figcaption></figcaption></figure>

#### `skew_x` - float

The value represents the radian angle value that the object's coordinate map is transformed about  its x axis.

#### `skew_y`  - float

The value represents the radian angle value that the object's coordinate map is transformed about  its y axis.

#### `flip_x` - boolean

Mirrors the object about its x axis.

#### `flip_y` - boolean

Mirrors the object about its y axis.

#### `blur` - float

Sets the standard deviation value of a Gaussian blur.

### Common Methods

#### `remove()`

All Tychos objects can be removed from the scenario world scope. Once this done, you will not be able to reference the object as it will be removed from your scenario's collection of viewable objects.

#### `rotate()`

`object.rotate(angle=0, axis=vec(0, 0))` — Rotates the object by a given angle value in radian units. You can also provide an optional vector that identifies the axis of rotation.&#x20;

{% hint style="info" %}
Lines, arrows and springs can't be rotated. Instead, you can just change the second position `pos2` to a different position in order for these objects to effectively rotate.
{% endhint %}

![Three different rectangle objects rotated at different angles](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-LELhdkS9qf1eni8epq-%2F-LELi7zhujAo60I3ZA_9%2Fblock_rotate.png?alt=media\&token=a89fa3a6-3ac8-4d9c-8d30-4c85d6b60d62)

Example:

```python
# Loop Code editor
r_green.rotate(-pi/4)
r_blue.rotate(radians(90))
r_orange.rotate(radians(45))
```

#### `clone()`

All objects can be cloned. This creates and returns a duplicate object that can be modified independently.

### circle

A `circle`  is drawn as a colored circle in the World View. Circle objects can have borders, labels, or even image overlays (see below).

```python
c = circle()
c_big_red = circle(pos=vec(50, 0), radius=25, color="red")
c_green = circle(pos=vec(100, 0), color="green", opacity=.5)
c_green.border_size=5
c_green.border_color="blue"
c.label_text="hi"
c.label_color="white"
c.label_font="Courier"
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FgMZPAh6Sl0IlNlKwigVx%2FTychos%20Circles.png?alt=media&#x26;token=b385fb96-00a7-4281-81aa-f465f4b3c05c" alt="" width="375"><figcaption></figcaption></figure>

Below is the constructor for the `circle` object that shows its default values:

```python
circle(
   pos=vec(0,0), 
   radius=10, 
   color="black",
   no_fill=False,
   fill=None,
   image="",   
   opacity=1,
   visible=True, 
   motion_map=False,
   label_text="",
   label_color="black"
   label_font="default",
   label_style={},
   border_size=0,
   border_color="black",
   border_style="none"
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `radius` — The radius of the `circle`.

### ellipse

An `ellipse`  is drawn as a colored ellipse in the World View.

```python
e1 = ellipse(pos=vec(0, 0), size=vec(10,5), color="green", opacity=.6)
e2 = ellipse(pos=vec(10, 0), size=vec(5,10), color="blue", opacity=.6)
e3 = ellipse(pos=vec(0, -10), size=vec(5,5), color="red", opacity=.6)
```

![Three ellipses with different sizes](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2Fg38FRD9PG15NsxaRQpiG%2FScreen%20Shot%202022-02-18%20at%206.30.14%20AM.png?alt=media\&token=a3b8e79c-7fc4-4c2b-af27-e5ac86c834fc)

Below is the constructor for the `ellipse` class that shows its default values:

```python
ellipse(
   pos=vec(0,0), 
   size=vec(10,5), 
   color=default_color, 
   no_fill=False,
   fill=None,
   border_size=0,
   border_color=default_color,
   border_style="none",
   image="",   
   opacity=1, 
   visible=True, 
   motion_map=False,
   label_text=""
   label_color="black",
   label_font="",
   label_style={},
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
) 
```

* `size` — The size of the `ellipse` given as a vector with `x,y,z` coordinates.&#x20;

These attributes may also be modified on the `ellipse` after it is created, just like the `circle`.&#x20;

### rectangle

A `rectangle` is very similar to a `circle` but it is represented as a colored rectangle in the World View.

```python
# Initial State editor
r = rectangle(size=vec(20,10))
r_big_red = rectangle(pos=vec(25, 0), size=vec(25, 25), color="red")
r_green = rectangle(pos=vec(50, 0), color="green", opacity=.5)
r_green.border_size=5
r_green.border_color="blue"
r.label_text="hi"
r.label_color="white"
r.label_font="Courier"
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FjrfcGPnbTssc7mWmnhdc%2FTychos%20Rectangles2.png?alt=media&#x26;token=ea93272e-f79d-45b5-bd11-1272d6add8e8" alt="" width="375"><figcaption></figcaption></figure>

Below is the constructor for the `rectangle` object that shows its default values:

```python
rectangle( 
   pos=vec(0,0), 
   size=vec(10,5), 
   color=default_color,
   no_fill=False,
   fill=None, 
   border_size=0,
   border_color=default_color,
   border_style="none",
   image="",   
   opacity=1, 
   visible=True, 
   motion_map=False,
   label_text="",
   label_color=default_color,
   label_font="default",
   label_style={},
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `size` — The size of the `rectangle` given as a vector with `x,y,z` coordinates.&#x20;

### arc

The `arc` object represents a graphical elliptical arc that sweeps out from a starting angular position to an ending angular position.

{% code overflow="wrap" lineNumbers="true" %}

```python
# Different arc objects
a1 = arc(pos=vec(10, 10), size=vec(10, 10), start=0, end=pi/2, mode="chord",     color="green", border_color="purple", border_size=3)
a2 = arc(pos=vec(-10, 10), size=vec(10, 5), start=0, end=5*pi/4, mode="open",     color="red", border_color="purple", border_size=3)
a3 = arc(pos=vec(-10, -10), size=vec(10, 10), start=0, end=pi/2, mode="pie",     color="orange", border_color="purple", border_size=3)
a4 = arc(pos=vec(-10, 20), size=vec(10, 10), start=pi, end=6*pi/5, mode="pie",     no_fill=True, border_color="purple", border_size=3)
```

{% endcode %}

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2F8LJFFNZQ6DtpRfqw5AsR%2Ftychos_arcs.png?alt=media&#x26;token=a65779fc-94e0-43c4-b959-4c2d6f39dd7e" alt="" width="375"><figcaption><p>Different arc objects.</p></figcaption></figure>

Below is the constructor for the `arc` object that shows its default values:

```python
arc(
   pos=vec(0,0), 
   size=vec(10,5), 
   start=0,
   end=pi,
   mode="chord",
   no_fill=False,
   fill=None,
   color=default_color, 
   border_size=0,
   border_color=default_color,
   border_style="none"
   opacity=1, 
   visible=True, 
   motion_map=False,
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
) 
```

* `size` — The size of the `arc` ellipse given as a vector with `x,y,z` coordinates.&#x20;
* `start` — The starting angular value for the arc sweep.
* `end` — The ending angular value of the arc sweep.
* `mode` — The render mode which can be "`chord`", "`open`", or "`pie`".&#x20;

### arrow

The `arrow` object represents a graphical arrow and is commonly used to illustrate vectors, but can be used for representing anything in your simulations.

```python
# Setup Code editor
c = circle(pos=vec(0,0), color="green")
a = arrow(pos=c.pos, size=vec(20, 20), color="purple")
a.show_components = True
```

Below is the constructor for the `arrow` object that shows its default values:

```python
arrow(
   pos=vec(0,0), 
   size=vec(0,1), 
   color=default_color, 
   stroke=0,
   style="none"
   opacity=1,
   show_components=False, 
   visible=True, 
   motion_map=False,
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
) 
```

* `pos` — The initial position of your `arrow` tail as a vector with `x,y,z` coordinates.
* `size` — The size of the `arrow` given as a vector with `x,y,z` coordinates.&#x20;
* `stroke` — The `arrow` thickness in pixels.
* `style` — An `arrow` can have a "dash" style, or a "dot" style, or "none" which is the default.&#x20;
* `show_components` — This flag tells Tychos to attach additional x and y component arrows.

### line

The `line` class draws a line and is commonly used to illustrate some connecting member like a string or cable, but could really represent anything you like.

```python
myLine = line(pos=vec(0, 0), pos2=vec(20, 20), color="purple", stroke=2)
anotherLine = line(pos=vec(0, 0), pos2=vec(10, 20), color="green", stroke=10)
```

![](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-LR327haq9kuj6IHN0S3%2F-LR32TDaeXVYokKRK4u5%2FLine-Example.png?alt=media\&token=3c786959-3ffb-4468-9859-f070e9d9afc1)

Below is the constructor for the `line` class that shows its default values:

```python
line(
   pos=vec(0,0), 
   pos2=vec(1,0), 
   color=default_color,
   stroke=1,
   style="none", 
   opacity=1, 
   visible=True, 
   motion_map=False,
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `pos` — coordinates for the starting point of the `line` as vector
* `pos2` — coordinates of the termination point of the `line` as a vector.
* `stroke` — Stroke value that determines the visual thickness of the `line`. This is measured in pixels.
* `style` — Sets the `line` as either solid (default = "none") or "dash" for a dashed line, or "dot" for a dotted line.

### poly\_line

The `poly_line` class draws a series of connected lines between a given set of points. This object can be used to represent a complex path or a shape other than a circle or rectangle.

![Three poly\_line objects showing different styles and fills.](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2F6uyTaRmtQB5tHWWlU3oY%2FScreen%20Shot%202022-01-12%20at%203.38.47%20PM.png?alt=media\&token=115ddbe0-9024-41bd-b65c-db0918283b7c)

Below is the constructor for the `poly_line` class that shows its default values:

```python
poly_line(
   pos=vec(0,0), 
   color=default_color,
   stroke=1,
   style="none",
   fill=None, 
   no_fill=True,
   opacity=1, 
   visible=True, 
   motion_map=False,
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `stroke` — Stroke value that determines the visual thickness of the `poly_line`. This is measured in pixels.
* `style` — Can be `"none"` for solid segments, `"dash"` for dashed line segments or `"dot"` for dotted line segments.

`poly_line` objects have a number of methods for manipulating the `poly_line` points, like adding new points, changing existing points, removing points, etc:

* `set_points: (points)` -> Set the points for the `poly_line` given a `List` of points.&#x20;
* `translate: (delta_position)` -> Move all the points according to a vector.
* `rotate: (angle, axis)` -> Transform the points a certain angle measurement about an axis. This axis is relative to the first point in the `poly_line`.
* `npoints():` -> Returns the number of points in the `poly_line`.
* `append: (*points)` -> Add a point (or many points) to the end of the `poly_line`.
* `unshift: (*points)` -> Add a point (or many points) at the beginning of the `poly_line`.
* `shift: ()` -> Remove the first point in the `poly_line` object.
* `splice: (start, how_many, *points)` -> Insert a point or several points anywhere at the specific index position. You can also identify how many points you would like to remove from the `poly_line` as well.
* `pop: (n)` -> Get the vector for point number n and remove it. Can use negative values, where -1 is the last point, -2 the next to the last, etc.
* `clear: ()` -> Remove all the points in the `poly_line`.
* `modify: (n, point)` -> Modify the point at the specified n position, replacing it with the given vector.
* `slice: (start, end)` -> Returns the set of points (but does not remove them) from the `poly_line` object beginning at the `start` value and ending at the `end` index position.

### spring

A `spring` is a visual representation of a common elastic connector that displays a given number of coils that dynamically change shape once the dimensions of the  `spring` are changed in the **Calculations Pane**.

The code below shows the three different `spring` objects above that have different lengths, widths and coil numbers. The `circle` objects are shown just for reference.

```python
# Setup Code editor
c1 = circle(pos=vec(0, 0), radius=2, color="green")
spring1 = spring(pos=vec(0, 20), pos2=c1.pos, color="black", coils=20, width=2)
c2 = circle(pos=vec(10, 0), radius=2, color="green")
spring2 = spring(pos=vec(10, 20), pos2=c2.pos, color="black", coils=10, width=4)
c3 = circle(pos=vec(20, 0), radius=2, color="green")
spring3 = spring(pos=vec(20, 20), pos2=c3.pos, color="black", coils=20, width=2)
```

![Three different Spring objects](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-LR2PRNhbNu_czjzZWhW%2F-LR2SQrF1kfAATmvdVEs%2FSprings.png?alt=media\&token=c3f345aa-7072-48b5-8312-d862557bd5b0)

Below is the constructor for the `spring` class that shows its default values:

```python
spring(
   pos=vec(0,0), 
   pos2=vec(1,0), 
   color=default_color,
   coils=5,
   width=10,
   stroke=1, 
   opacity=1, 
   visible=True, 
   motion_map=False,
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `pos` — coordinates for the starting point of the `spring` as a 2D vector.
* `pos2` — coordinates of the termination point of the `spring` as 2D vector
* `coils` — The number "coil" zig-zags.
* `width` — The width of the "coil" zig-zags.
* `stroke` — Stroke value that determines the visual thickness of the `spring`. This is measured in pixels.

These attributes may also be modified after the `spring` is created.

### label

You can add text labels to any scenario using the `label` object.

```python
lbl_dog = label(pos=vec(0,0), size=vec(20,20), text="dog", color="green")
lbl_cat = label(pos=vec(0,-15), size=vec(10,10), text="cat", color="red")
lbl_mouse = label(pos=vec(0,15), size=vec(10,10), text="mouse", color="blue")
lbl_dog.font="Impact"
lbl_cat.font="Times"
lbl_mouse.font="monospace"
lbl_dog.style = {"text-shadow":"3px 3px 3px black"}
lbl_cat.style = {"font-style":"oblique"}
lbl_mouse.style = {"text-decoration":"underline"}// Some code
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FnQerV5YHaVzCApoPpLHE%2FTychos%20Labels.png?alt=media&#x26;token=8cd74315-23d5-49d8-afb8-1f9c5a774f21" alt="" width="142"><figcaption></figcaption></figure>

Below is the constructor for the `label` class that shows its default values:

```python
label(
   pos=vec(0,0), 
   size=vec(10,10), 
   text="",
   color=default_color, 
   font="default",
   style={},
   opacity=1, 
   visible=True, 
   motion_map=False
   skew_x = 0,
   skew_y = 0,
   flip_x = False,
   flip_y = False,
   blur = 0
)
```

* `size` — The width and height of the `label` as a 2D vector.
* `text` — The text of the `label` as a string.
* `font` — CSS font family identifier, e.g. "Times", or "Courier"
* `style` — A dictionary with key value pairs that represent CSS font styling rules.

These attributes may also be modified after the `label` object is created.

***

### sprite

A Sprite is a graphical object displayed using an image. It behaves similarly to other simulation objects but supports sprite-sheet animations. It shares most of the common attributes that all objects do in Tyhcos, but has some specific attributes that are used to define and control sprite animations.

```python
sprite(pos=vec(0,0), image="", width=32, height=32, ...)
```

**Parameters**

* `pos` — *Vector* (default: `vec(0, 0)`)

  The position vector of the sprite's center in the simulation world. This is no different than setting the position of any other object in Tychos.
* `image` — *String* (default: `""`)

  The name of the image asset to display. This must match the name of an uploaded asset. The part of image that is actually shown will match only the current frame based on how the image has been divided into rows and columns, and how large the width and size of that animation cell is defined (see below).
* `size` — *Vector* (default: `vec(10, 10)`)

  The dimensions of the sprite in simulation units. This determines how large the object appears in the world and its collision boundaries.
* `width` — *Number* (default: 32)

  The width of the source image in pixels. This is used to calculate frame sizes for animations (e.g., `frame_width = width / n_cols`).
* `height` — *Number* (default: 32)

  The height of the source image in pixels. This is used to calculate frame sizes for animations (e.g., `frame_height = height / n_rows`).
* `n_rows` — *Number* (default: 1)

  The number of rows in the sprite sheet.
* `n_cols` — *Number* (default: 1)

  The number of columns in the sprite sheet.
* `border_width` —  *Number* (default: 0)

  The thickness of the border drawn around the sprite frames.
* `spacing_width` — *Number* (default: 0)

  The spacing (padding) in pixels between frames in the sprite sheet.
* `scale` — *Number* (default: 1)

  A visual scaling factor applied to the sprite (does not affect collision `size`).
* `current_animation_name` —  *String* (default: `"idle"`)

  The name of the animation sequence currently playing.
* `animations` —  *Dictionary* (default: `None`)

  A dictionary defining animation sequences. See *Defining Animations* below.

#### Animation Structure

The `animations` parameter is a dictionary where keys are animation names and values are animation definitions:

```python
animations = {
    "idle": {
        "frame_indices": [0],
        "time_per_frame": 250,
        "on_end": "stop"
    },
    "walk": {
        "frame_indices": [0, 1, 2, 3],
        "time_per_frame": 100,
        "on_end": "repeat"
    },
    "blink": {
        "frame_indices": [0, 1, 0],
        "time_per_frame": 50,
        "on_end": "ping-pong"
    }
}
```

#### Animation Keys

* **frame\_indices** (list of int): Which frames from the sprite sheet to use. References cells in row-major order starting at 0
* **time\_per\_frame** (int): Milliseconds each frame displays. Default: `250`
* **on\_end** (str): What to do when animation reaches the last frame:
  * `"repeat"` — Loop back to first frame (default)
  * `"stop"` — Hold on last frame (use `is_animation_finished()` to detect)
  * `"ping-pong"` — Reverse direction and bounce back and forth

#### Animation Control Methods

**`play_animation(name)`**

Switch to a different animation by name.

**Parameters:**

* **name** (str): Name of the animation to play (must exist in animations dict)

**Example:**

```python
sprite.play_animation("walk")
sprite.play_animation("jump")
```

**`is_animation_finished()`**

Check if the current non-repeating animation has completed.

**Returns:**

* **bool**: `True` if animation reached its last frame, `False` otherwise
  * Always returns `False` for animations with `"on_end": "repeat"`
  * Returns `False` if no animation is playing

**Example:**

```python
if sprite.is_animation_finished():
    sprite.play_animation("idle")
```

**`reset_animation()`**

Reset the current animation to its first frame.

Resets:

* Frame index to 0
* Elapsed time within current frame to 0
* Direction to forward (useful for ping-pong mode)

**Example:**

```python
sprite.reset_animation()
```

**`get_animation_frame_index()`**

Get the current frame index of the active animation.

**Returns:**

* **int**: 0-based frame index in the current animation

**Example:**

```python
frame = sprite.get_animation_frame_index()
print(f"Playing frame {frame}")
```

#### Example:

You just need to have a sprite sheet of "frames" like this:

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FofRdsezaS3ykzITcl8KG%2FMORGIX-Sheet.png?alt=media&#x26;token=8c98b738-de36-4167-8d60-3b08c1f5d36a" alt=""><figcaption></figcaption></figure>

Upload the sprite sheet into your **Assets**, and then write the following code:

```python
# Here is a sprite object
hero = sprite(image="hero_sprites.png", n_rows=1, n_cols=25, width=30, height=50)
```

And then in your scenario, define some animation cycles based on the index of the frame in the sprite sheet:

```python
hero. animations = {
    "jump" : {
      "frame_indices": [0,1,2,3,5,6],
      "time_per_frame": 100,
      "on_end": None
    },
    "walk": {
      "frame_indices": [10,11,12,13],
      "time_per_frame": 100,
      "on_end": "repeat"
    },
    "idle": {
      "frame_indices": [7,8,9],
      "time_per_frame": 100,
      "on_end": "repeat"
    }
}
    
hero.play_animation("jump")
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FsSr5hK2B6dpl2IjMJlWC%2FMORGIX_jump.gif?alt=media&#x26;token=1683eb85-dccb-455f-8ab8-6e874036b4d3" alt=""><figcaption><p>The "jump" animation.</p></figcaption></figure>

And the above animation will be displayed.

***

### tilemap

The `tilemap()` function creates a grid-based map from a sprite sheet. This allows you to easily place  graphic tiles on the screen so that you can build platforms, mazes and more!

#### basic syntax

```python
tm = tilemap(
    image="tileset.png",      # Your sprite sheet image
    cols=4,                            # Columns in the tileset
    rows=4,                            # Rows in the tileset
    size=vec(200, 200),               # Size in world coordinates
    tiles=[[0, 1], [2, 3]],          # Which tiles to show where
    pos=vec(0, 0)                     # Position in world
)
```

#### parameters

| Parameter | Type    | Description                                                      |
| --------- | ------- | ---------------------------------------------------------------- |
| `image`   | string  | URL or path to your sprite sheet PNG                             |
| `cols`    | int     | How many tile columns are in your sprite sheet                   |
| `rows`    | int     | How many tile rows are in your sprite sheet                      |
| `size`    | Vector  | Total size of the rendered tilemap in world units                |
| `tiles`   | 2D list | Which tiles to display (indices 0 to cols×rows-1)                |
| `pos`     | Vector  | Center position in the world                                     |
| `visible` | bool    | Show/hide the tilemap (default: True)                            |
| `color`   | string  | Fallback color (usually not visible)                             |
| Other     |         | Standard SimThing options: opacity, blur, flip\_x, flip\_y, etc. |

#### Example 1: Simple 2×2 Tilemap

```python
# Create a 2x2 tilemap using a 4x4 sprite sheet
tm = tilemap(
    image="https://example.com/tileset.png",
    cols=4,
    rows=4,
    size=vec(100, 100),
    tiles=[
        [0, 1],
        [2, 3]
    ]
)
```

This creates a 100×100 unit tilemap displaying 4 tiles in a 2×2 grid.

#### Example 2: Larger Map with Blank Spaces

Use `-1` to create blank/empty spaces:

```python
tm = tilemap(
    image="grass_tileset.png",
    cols=4,
    rows=4,
    size=vec(200, 160),
    tiles=[
        [0, 1, 2, 3],
        [4, 5, -1, 6],    # Blank space in middle
        [7, 8, 9, 10],
        [11, -1, 12, 13]  # Another blank
    ]
)
```

#### Example 3: Positioned Tilemap

```python
tm = tilemap(
    image="dungeon.png",
    cols=3,
    rows=3,
    size=vec(150, 150),
    pos=vec(50, 50),           # Position at (50, 50)
    tiles=[
        [0, 1, 0],
        [2, 3, 2],
        [0, 1, 0]
    ]
)
```

#### Example 4: With Visual Effects

```python
tm = tilemap(
    image="lava_tileset.png",
    cols=2,
    rows=2,
    size=vec(100, 100),
    tiles=[[0, 1], [2, 3]],
    opacity=0.8,              # Semi-transparent
    blur=2,                   # Blurred edges
    flip_x=True               # Flipped horizontally
)
```

#### Important Notes

1. **Tile Indices**: Tiles are numbered left-to-right, top-to-bottom starting at 0
   * For a 4×4 tileset: tiles 0-3 are top row, 4-7 are second row, etc.
2. **Blank Spaces**: Use `-1` to skip a tile
3. **Size vs. Tile Count**:
   * `size` = total rendered size
   * `tiles` = how many tiles you're displaying (doesn't have to match cols×rows)
4. **Resizing Tiles**: If your tilemap is 200×200 with 2×2 tiles, each tile renders at 100×100 units
5. **Common Gotcha**: Make sure your tileset image URL is accessible and the image loads properly!

Would you like me to explain the tile indexing system in more detail, or show how to animate tilemaps?

### compound

Compound objects allow you to group any of the above graphical objects together so that they can all be animated as a single object. Compound objects can even be added to other compound objects to make some complex object compositions.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FH62Ckc9KlWcl89bWuZ6U%2Ftychos_compound.png?alt=media&#x26;token=49221512-9459-4e35-a748-0dd74363dfb8" alt=""><figcaption><p>These are made up of several objects that are grouped in compounds that can then be moved together.</p></figcaption></figure>

Below is the constructor for the `compound` class that shows its default values:

```python
compound(
   pos=vec(0,0), 
   opacity=1, 
   visible=True,
)
```

* `pos` — coordinates for the center point of the `compound` as a 2D vector.
* `opacity` — The objects in the `compound` will be drawn with an opacity between 1 and 0, representing 100% opaque to 100% transparent.
* `visible` — The objects in the `compound` can be hidden from view by setting this flag to `False`.

These attributes may also be modified after the `compound` object is created.

#### compound.add(\*objects)

To add an object to a compound, you simply call the add method with the object variable that you want to add. You can add as many objects as you want in one call.

```python
# Make some graphic objects.
c1 = circle(pos=vec(-5, 0), radius=1, color="orange")
c2 = circle(pos=vec(5, 0), radius=1, color="orange")
r1 = rectangle(pos=vec(0,0), size=vec(11, 1), color="orange")

# Add them to a compound
cmp1 = compound(pos=vec(0,0))
cmp1.add(c1, c2, r1)
```

#### compound.remove()

`compound` objects, like all Tychos objects can be removed from the scenario world scope. Once this is done, you will not be able to reference the objects as they will all be removed from your scenario's collection of viewable objects.

#### compound.clone()

As is the case with all other Tychos objects, compounds can be cloned, the only difference is that all the objects in the compound are also cloned.

## World

The world object represents the viewable area of the scenario.&#x20;

#### world.set\_extents

You can set the viewable extents of the world in the Settings Pane, or by calling the following method on the world object:

```python
world.set_extents(pos=vec(0,0), size=vec(10,10))
```

The inputs are two vector objects representing the center position of the view of the world, and secondly the size of the viewable world.

## Scenario

The `scenario` object manages simulation settings, device connections, and scenario transitions in Tychos. The `scenario` object is a global instance available in all Tychos simulations. Use it to configure simulation behavior and load different scenarios.

***

#### Method Reference

<table><thead><tr><th width="256.9296875">Setter/Getter</th><th width="448.0087890625">Description</th></tr></thead><tbody><tr><td><code>set_background_color()</code></td><td>Sets the simulation background color</td></tr><tr><td><code>get_background_color()</code></td><td>Gets the background color; returns <code>None</code> if using default</td></tr><tr><td><code>set_grid_visible()</code></td><td>Shows/hides the grid overlay</td></tr><tr><td><code>get_grid_visible()</code></td><td>Gets grid visibility; returns <code>None</code> if using default</td></tr><tr><td><code>set_grid_color()</code></td><td>Sets the grid line color</td></tr><tr><td><code>get_grid_color()</code></td><td>Gets the grid color; returns <code>None</code> if using default</td></tr><tr><td><code>set_strobe_count()</code></td><td>Sets max number of motion trail images (20-50 typical)</td></tr><tr><td><code>get_strobe_count()</code></td><td>Gets the strobe count; returns <code>None</code> if using default</td></tr><tr><td><code>set_tick_rate()</code></td><td>Sets simulation step size (e.g., 0.02 for 50 ticks/sec)</td></tr><tr><td><code>get_tick_rate()</code></td><td>Gets tick rate in seconds; returns <code>None</code> if using default</td></tr><tr><td><code>set_graph_strobe_rate()</code></td><td>Sets how often graph data is recorded (in seconds)</td></tr><tr><td><code>get_graph_strobe_rate()</code></td><td>Gets graph sample rate; returns <code>None</code> if using default</td></tr><tr><td><code>set_table_strobe_rate()</code></td><td>Sets how often table data is recorded (in seconds)</td></tr><tr><td><code>get_table_strobe_rate()</code></td><td>Gets table sample rate; returns <code>None</code> if using default</td></tr><tr><td><code>set_motion_map_rate()</code></td><td>Sets how often motion trails update (in seconds)</td></tr><tr><td><code>get_motion_map_rate()</code></td><td>Gets motion map rate; returns <code>None</code> if using default</td></tr><tr><td><code>load()</code></td><td>Requests loading a different scenario by URL key</td></tr><tr><td><code>get_device()</code></td><td>Gets connected hardware device by index</td></tr></tbody></table>

#### Scenario Navigation

Using the `load()` function, you can load a different scenario into the Tychos interface. This allows you to connect scenarios together, jumping from one to another.

This function can only be used in the **Loop Code** and cannot be called from the **Setup Code**.

**Parameters:**

* `url_key` (str): Non-empty string identifying the scenario to load

**Example:**

```python
scenario.load('ABCDEF')
```

**Behavior:**

* Requests a scenario transition
* The application will fetch and load the specified scenario
* All objects and variables will be reset on load
* Current scenario's code continues running until reset happens

***

#### Complete Example

```python
# Configure simulation environment
scenario.set_background_color('#f0f0f0')
scenario.set_grid_visible(True)
scenario.set_grid_color('lightgray')

# Adjust simulation speed
scenario.set_tick_rate(1/60)         # 60 FPS
scenario.set_motion_map_rate(0.05)   # Frequent strobe updates

# Configure data collection
scenario.set_graph_strobe_rate(0.1)  # Record graphs every 100ms
scenario.set_table_strobe_rate(0.1)  # Record tables every 100ms

# Set motion map quality
scenario.set_strobe_count(40)        # 40 trailing images

# Create your simulation objects
ball = circle(pos=vec(0, 0), radius=5, color='blue')
ground = rectangle(pos=vec(0, -50), size=vec(200, 10), color='brown')

# Later, load a different scenario
if some_condition:
    scenario.load('XXXXXX')
```

***

## Gradient Fills

The `radial_gradient` and `linear_gradient` objects are used as fill parameters for the following objects:

* circle
* rectangle
* ellipse
* arc
* poly\_line

### radial\_gradient

Below is the constructor for the `radial_gradient` object that shows its default values:

```python
radial_gradient(
   start_x=50, 
   start_y=50, 
   end_x=50,
   end_y=50, 
   colors=[]
   offsets=[]
)
```

* `start_x` — This attribute defines the relative x position (as a percentage) of the start the radial gradient.
* `start_y` — This attribute defines the relative y position (as a percentage) of the start the radial gradient.
* `end_x` — This attribute defines the relative x position (as a percentage) of the end the radial gradient.
* `end_y` — This attribute defines the relative y position (as a percentage) of the end the radial gradient.
* `colors` — A list of HTML color values for your `radial_gradient`, e.g. "red" or "#ff0000".
* `offsets` — A list of corresponding numerical values defining where the associated gradient stop is placed along the gradient.

Example:

```python
c1 = circle(pos=vec(-50,0), radius=10)
c1.fill = radial_gradient(start_x=10, start_y=10, end_x=30, end_y=30, colors=["white", "red", "black"], offsets=[0,50,100])
r1 = rectangle(size=vec(20,20), pos=vec(0,50))
r1.fill = radial_gradient(start_x=10, start_y=10, end_x=30, end_y=30, colors=["white", "purple", "black"], offsets=[0,40,100])
e1 = ellipse(pos=vec(50,50), size=vec(20, 10))
e1.fill = radial_gradient(start_x=10, start_y=10, end_x=30, end_y=30, colors=["white", "purple", "black"], offsets=[0,40,100])
a1 = arc(pos=vec(-50, 50))
a1.fill = radial_gradient(start_x=10, start_y=10, end_x=30, end_y=30, colors=["white", "purple", "black"], offsets=[0,40,100])
p1 = poly_line(pos=vec(0, 0), stroke=1, color="red")
p1.append(vec(0,0))
p1.append(vec(25,0))
p1.append(vec(0,25))
p1.append(vec(0,0))
p1.fill = linear_gradient(colors=["black", "red"])
c2 = circle(pos=vec(50,0), radius=10)
c2.fill = linear_gradient(colors=["black", "red"])
r2 = rectangle(size=vec(20, 20), pos=vec(0,-50))
r2.fill =linear_gradient(colors=["yellow", "red"])
e2 = ellipse(pos=vec(50,-50), size=vec(20, 10))
e2.fill = linear_gradient(colors=["orange", "red", "black"], offsets=[0,30,100])
a2 = arc(pos=vec(-50, -50))
a2.fill = linear_gradient(colors=["red", "black"], offsets=[30, 100], angle=pi/2)
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2F2kGL0uw8fjrqHfA2mavl%2Ftychos_gradients.png?alt=media&#x26;token=97565f0c-8367-45d5-b924-b56d50a355fe" alt="" width="375"><figcaption><p>Different gradients on different objects</p></figcaption></figure>

### linear\_gradient

Below is the constructor for the `linear_gradient` object that shows its default values:

```coffeescript
linear_gradient(
   angle=0, 
   colors=[]
   offsets=[]
)
```

* `angle` — This attribute transforms the linear gradient by rotating the gradient from the relative center position of the filled object. The value is defined in radians.
* `colors` — A list of HTML color values for your `radial_gradient`, e.g. "red" or "#ff0000".
* `offsets` — A list of corresponding numerical values defining where the associated gradient stop is placed along the gradient.

## Interface Widgets

Tychos also provides several "widgets" for displaying data in different ways as well as adding user interactivity so that your simulations can respond to input.

### graph

A `graph` is a 2-dimensional chart of data that you specify in the **Setup Code** editor. Each `graph` that is created will appear by default on the right side of the World View, but can be aligned to the left instead. Your program needs to add points to the graph with the `plot`command.

```python
g1 = graph(title="Line Graph", align="left", width="50%", height=200)
g1.plot(color="purple", mode="line", x=[0,1,2,3], y=[0, 10, 10, 0], fill=True)
g1.plot(color="green", mode="line", x=[0,1,2,3], y=[0, 2, 4, 9], fill=False)
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FSTPrT2cjHX418NOj6VZD%2FTychos%20Line%20Graph.png?alt=media&#x26;token=af39b665-4e97-4ad0-9e8c-c4f320ab6bc9" alt=""><figcaption><p>A line graph with two different colored plots.</p></figcaption></figure>

```python
g2 = graph(title="Scatter Graph", align="right", width="50%", height=400)
x_vals = random.sample(range(-50, 50), 100)
y_vals = random.sample(range(0, 100), 100) 
g2.plot(color="orange", mode="scatter", x=x_vals, y=y_vals)
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2Fn60g2sKee31DUuNYUqU5%2FTychos%20Scatter%20Graph.png?alt=media&#x26;token=fa47647f-9fb8-402d-b87c-958baae05856" alt=""><figcaption><p>A scatter graph</p></figcaption></figure>

Here is the constructor for creating a `graph` object

```python
graph(
    title="Graph", 
    align="right", 
    y_axis="Y", 
    x_axis="X",
    width=500,
    height=350,
    plot_rate=None
)
```

* `title` = Optional text that will appear at the top of the graph.
* `align` = Optional value of "`left`" or "`right`" to align the graph to the corresponding side of the view window.
* `y_axis` = Optional text that will appear on the left side of the graph as the vertical axis label.
* `x_axis` = Optional text that will appear at the bottom of the graph as the horizontal axis label.
* `width` = Optional numeric value in pixels for setting the width, or a text value percentage e.g. "50%" or "90%".
* `height` = Optional numeric value in pixels for setting the height, or a text value percentage e.g. "50%" or "90%".
* `plot_rate` = Optional numerical value greater than 0 that sets the individual graph's plotting schedule. This over rides the default ***Graph Strobe Rate*** value set in the **Settings** tab.

#### **Plotting Values**

To plot values for the graph, the `plot` method is used. You can either plot points by calling the plot method with the x and y arguments set to single numerical inputs, or to plot more than a single point, you can instead set the x and y arguments to be lists of numerical values.

When plotting, Tychos will plot the points you specify when the simulation plot timer has expired. This is called "strobing" the graph. There is a default plot timer set in the **Settings** tab called ***Graph Strobe Rate*** for the scenario, but this can be over ridden by setting the graph's plot rate.

{% hint style="info" %}
Note that depending on the simulation step time and the graph plot rate, graph plots may not appear on the graph at the exact time specified by the graph plot rate. For example, if the plot rate is actually faster than the animation step rate, the plotting of the points will not appear to be in sync because the animation is actually running slower than rate at which points should be plotted.
{% endhint %}

The arguments for the plot method are shown below:

```python
graph.plot(
    x=0, 
    y=0, 
    color=default_color,
    mode="line",
    fill=False
)
```

* `x` = This is either a single numerical value or a list of numerical values.
* `y` = This is either a single numerical value or a list of numerical values.
* `color` = Optional "line" or "scatter" that will either display the points as connected with lines, or not. The default is to connect the plotted points with lines.
* `mode` = Optional "line" or "scatter" that will either display the points as connected with lines, or not. The default is to connect the plotted points with lines.
* `fill` = Optional boolean value for filling in the plotted area.

#### **Clearing Values**

To clear values for the graph, the `clear` method is used. Clearing the plotted values occurs immediately when the method is called, clearing all the plotted values from the graph:

```
graph.clear()
```

### bar\_chart

A `bar_chart` is a chart of data that is displayed as a set of bars representing an array of data values. Each `bar_chart` that is created will appear on the right side of the World View.

```python
bc_energy = bar_chart(title="Energy Bar Chart", min=0, max=500)
bc_energy.data = [150, 250, 200, 500]
bc_energy.colors = ["red", "blue", "green", "black"]
bc_energy.labels = ["KE", "Ue", "Ug", "TE"]
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FElutZHIVf7qgXtbMxUVQ%2FTychos%20bar%20Chart.png?alt=media&#x26;token=42a4b2c0-d953-4c91-8e1b-eda480cd9114" alt=""><figcaption><p>A <code>bar_chart</code> with four bars.</p></figcaption></figure>

* `title` = Optional text that will appear at the top of the `bar_chart.`
* `align` = Optional value of "`left`" or "`right`" to align the bar chart to the corresponding side of the view window.
* `min` = Optional minimum value whose default is 0. If any bar data value is less than this minimum, the bar will be truncated.
* `max` = Optional maximum value whose default is 1. This sets the maximum viewable bar height. If any bar data value is greater than this maximum, the bar will be truncated.
* `width` = Optional numeric value in pixels for setting the width, or a text value percentage e.g. "50%" or "90%".
* `height` = Optional numeric value in pixels for setting the height, or a text value percentage e.g. "50%" or "90%".

#### **bar\_chart.data**

`bar_chart.data` — Sets the data values for the bars in the bar chart.

```python
# Set the data for the bars
bc_energy.data =[x,y,z,w] # Where x, y, z, and w are numerical data values
```

#### **bar\_chart.labels**

`bar_chart.labels` — Defines a set of labels - one label corresponding to each data bar in the chart. If the number of labels does not match the number of bars set by the number of data values, then a numbered label will be assigned to the extra data value.

```python
# Set the labels for the bars
bc_energy.labels = ["KE", "Ue", "Ug", "TE"]
```

#### **bar\_chart.colors**

`bar_chart.colors` — List of colors, one color corresponding to each data bar in the chart. If the number of colors does not match the number of bars set by the number of data values, then any extra bars will be given the default HTML color of `#aaa`.

```python
# Set the colors for the bars
bc_energy.colors = ["red", "blue", "green", "black"]
```

### pie\_chart

A `pie_chart` is a chart of data that is displayed as circle that is "sliced" into different pieces of a "pie" representing the relative proportion to the sum of all the values in the chart's data. Each `pie_chart` that is created will appear on the right side of the World View by default, but can be aligned to the left.

```python
pc = pie_chart(title="Pie Chart", data=[10,20, 30], width=300, height=200)
pc.labels = ["yes", "no", "maybe"]
pc.colors = ["lightgreen", "red", "gold"]
```

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FSabPIwRZu914HdD6sWfl%2FTychos%20Pie%20Chart.png?alt=media&#x26;token=fac9fca2-c0b9-4738-b5c0-61987cac4470" alt="" width="563"><figcaption><p>A <code>pie_chart</code>.</p></figcaption></figure>

The constructor options for adding a `pie_chart` to your scenario are the following:

* `title` = Optional text that will appear at the top of the `pie_chart.`
* `align` = Optional value of "`left`" or "`right`" to align the `pie_chart` to the corresponding side of the view window.
* `width` = Optional numeric value in pixels for setting the width, or a text value percentage e.g. "50%" or "90%".
* `height` = Optional numeric value in pixels for setting the height, or a text value percentage e.g. "50%" or "90%".

#### **pie\_chart.data**

`pie_chart.data` — Sets the data values for the pie slices in the pie chart.

```python
# Set the data for the bars
pc.data =[x,y,z] # Where x, y, z, are numerical data values
```

#### **pie\_chart.labels**

`pie_chart.labels` — Defines a set of labels - one label corresponding to each data slice in the chart. If the number of labels does not match the number of data values, then a numbered label will be assigned to the extra data value.

```python
# Set the labels for the pie chart slices
pc.labels = ["yes", "no", "maybe"]
```

#### **pie\_chart.colors**

`pie_chart.colors` — List of colors, one color corresponding to data value in the chart. If the number of colors does not match the number  of data values, then any extra values will be given the default colors.

```python
# Set the colors for the data values
pc.colors = ["lightgreen", "red", "gold"]
```

### table

A `table` displays data organized in columns and rows.&#x20;

Each `table` that is created will appear on the right side of the World View. When creating a `table` you can give it a title, and will need to define the column names for the `table`. You can also optionally define the precision for the numerical values being displayed in the table.

Below is the constructor for the `table` widget and default values:

`table(title="Table", align="right", columns=[], precision=4)`

* `title` = Optional text that will appear at the top of the `table` widget.
* `align` = Optional value of "`left`" or "`right`" to align the table to the corresponding side of the view window.
* `columns` — A list of strings representing the column names that will appear in the table.
* `precision` —  Optional precision level for representing numerical values.

#### **table.add\_row(\[value1, value2, ...])**

`table.add_row([values])` — This adds a row of data to the table. Keep in mind that you must supply a list of values whose length is equal to that of the columns in the table.

* `values` = A list of values corresponding to the columns in the table.

<div align="center"><figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FzpcSDKDECbIEEUshSUgv%2Ftychos_table.png?alt=media&#x26;token=6f43e9f2-fa28-4fcc-9ff3-a9b2fe8e7a94" alt=""><figcaption><p>Table of data</p></figcaption></figure></div>

Example:

```python
# Initial State editor
table1 = table(title="example")

table1.columns = ["Time", "X Pos", "Y Pos"]

table1.precision = 6
```

```python
# Calculations editor
# c is a circle object that is moving
table1.add_row([t, c.pos.x, c.pos.y])
```

### meter

A `meter` is a numeric display of data. Each `meter` that is created will appear on the left side of the World View. Your program needs to tell the `meter` what value it needs to display by using the `display` command.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJxEU1OZTQWkBNkGuwf%2F-MJxWiXWbOGE-MzAgPUd%2FScreen%20Shot%202020-10-18%20at%202.03.33%20PM.png?alt=media&#x26;token=e02c782f-bc42-48ec-b355-5929cfd592d8" alt=""><figcaption></figcaption></figure>

Below is the constructor for the `meter` widget and default values:

`meter(title="Meter", align="left", color="black", suffix="")`

* `title` = Optional text that will appear at the top of the `meter` widget.
* `align` = Optional value of "`left`" or "`right`" to align the meter to the corresponding side of the view window.
* `color` — HTML color value for your `meter`, e.g. "red" or "#ff0000".
* `suffix` —  text added at the end of the data value display.

#### **meter.display()**

`meter.display(value)` — Displays the value on the `meter`.

* `value` = Numeric value to be displayed.

Example:

```python
# Initial State editor
mt = meter(title="Time", color="red", suffix="s")
```

```python
# Calculations editor
mt.display(t)
```

### gauge

A `gauge` is an analog display of data that is very similar to a `meter` that you specify in the Initial Sate pane. Each `gauge` that is created will appear on the left side of the World View.  Gauges also need to to be set up with a specific minimum and maximum value for identifying the range of the `gauge`. Your scenario needs to tell the `gauge` what value it needs to display by using the `display` command.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJxEU1OZTQWkBNkGuwf%2F-MJxPa5QJ3BAJEdDpWxs%2FScreen%20Shot%202020-10-18%20at%201.32.00%20PM.png?alt=media&#x26;token=d0137c79-8694-4a68-88cb-4de0e9841c6f" alt=""><figcaption></figcaption></figure>

Below is the constructor for the `Gauge` widget and default values:

`gauge(title="Gauge", align="left", min=0, max=100, color="black")`

* `title` = Optional text that will appear at the top of the `gauge` widget.
* `align` = Optional value of "`left`" or "`right`" to align the gauge to the corresponding side of the view window.
* `min` = The minimum value of the `gauge`
* `max` = The maximum value of the `gauge`
* `color` — HTML color value for your `gauge`, e.g. "red" or "#ff0000".

#### **gauge.display()**

`gauge.display(value)` — Displays the value in the Gauge.

Example:

```python
# Setup Code editor
g1 = gauge(title="Value 1", min=0, max=200, color="orange")
g2 = gauge(title="Value 2", min=-100, max=100, color="purple")
g3 = gauge(title="Value 3", min=0, max=100, color="blue")
```

```python
# Loop Code editor
val = 44
g1.display(val)
g2.display(val)
g3.display(val)
```

### button

A `button` is a clickable widget that you can add to your scenarios that allows you to respond to the mouse in several ways.&#x20;

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FROMEz8pULPrA9ufCrReH%2Fbuttons.png?alt=media&#x26;token=cf7540ba-bfab-4969-85dd-e2797b642499" alt="" width="167"><figcaption><p>Three different buttons.</p></figcaption></figure>

To create a button,  you can supply all the following properties defined below:

```python
button(
    title = "Button",
    align = "left",
    color = "red",
    label_text = ""
    label_color = "black",
    label_font = "default",
    style = "normal",
    on_click = None
    on_mouse_over = None
    on_mouse_out = None
    on_mouse_down = None
    on_mouse_up = None
)
```

* `title` - Optional text that will appear at the top of the button widget.
* `align` = Optional value of "left" or "right" to align the button to the corresponding side of the view window.
* `color` — HTML color value for your button, e.g. "red" or "#ff0000".
* `label_text` - Text that you want to appear on the button itself.
* `label_color` - HTML color value for your label text, e.g. "red" or "#ff0000".
* `label_font` - A font family name for the label text, like "Courier" or "Times New Roman".
* `style` - This can be one of three options, "arcade", "normal", or "alert", but can also be a CSS style object, i.e. {text-decoration: "underline"}
* `on_click` — The name of a function that will be called whenever the button is clicked.
* `on_mouse_over` — The name of a function that will be called whenever the moves over the button.
* `on_mouse_out` — The name of a function that will be called whenever the mouse moves away from the button.
* `on_mouse_down` — The name of a function that will be called whenever the mouse button is pressed while on the button.
* `on_mouse_up` — The name of a function that will be called whenever the button is release while on the button.

Example

{% tabs %}
{% tab title="Tychos" %}
{% code lineNumbers="true" %}

```python
b1 = button(title="Arcade", style="arcade", color="green", label_text="YES")
b1.label_font = "Impact"
b1.label_color = "white"
b2 = button(title="Normal", style="normal", label_text="Hello!")
b2.style = {"text-decoration":"underline"}
b2.color = "lightblue"
b3 = button(title="Alert", style="alert", label_text="Danger!")
b3.label_font = "Courier"
```

{% endcode %}
{% endtab %}
{% endtabs %}

### toggle

A `toggle` is an interactive widget that allows you to associate a boolean value (`True` or `False`) with the state of the  `toggle` widget.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJxEU1OZTQWkBNkGuwf%2F-MJxMJXj3pP6HVQ2LwoE%2FScreen%20Shot%202020-10-18%20at%201.17.13%20PM.png?alt=media&#x26;token=82680694-401e-48a4-9c15-8dd16596104e" alt=""><figcaption><p>A toggle that is <code>False</code></p></figcaption></figure>

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJxEU1OZTQWkBNkGuwf%2F-MJxN8eOZiXofjhvwpLV%2FScreen%20Shot%202020-10-18%20at%201.21.55%20PM.png?alt=media&#x26;token=13fa0a2f-121b-4f8e-8a3c-b7be4a92358c" alt=""><figcaption><p>A toggle that is <code>True</code></p></figcaption></figure>

Below is the constructor for the `toggle` widget and default values:

```python
toggle(
    title="Toggle",
    align="left"
)
```

* `title` = Optional text that will appear at the top of the `toggle` widget.
* `align` = Optional value of "`left`" or "`right`" to align the toggle to the corresponding side of the view window.

#### Toggle.value

`x = toggle.value` — Returns the current value of the `toggle`. This is read/write.

Example:

```python
# Setup Code editor
t1 = toggle(title="Activate")
```

```python
# Loop Code editor
is_active = t1.value
```

### slider

A `slider` is an interactive widget that allows you to link a value in your scenario to the current value of a horizontal slider.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJxEU1OZTQWkBNkGuwf%2F-MJxKRckXSYUapXnRLtt%2FScreen%20Shot%202020-10-18%20at%2012.42.29%20PM.png?alt=media&#x26;token=b82693d0-c654-46e3-a0bb-f27a10fc6d95" alt=""><figcaption><p>A <code>slider</code> widget with a value of 0.</p></figcaption></figure>

Below is the constructor for the `slider` widget and default values:

```python
slider(
    title="Slider",
    align="left",
    min=0, 
    max=100,
    value=0, 
    step=1
)
```

* `title` = Optional text that will appear at the top of the `slider` widget.
* `align` = Optional value of "`left`" or "`right`" to align the slider to the corresponding side of the view window.
* `min` = The minimum value of the `slider`
* `max` = The maximum value of the `slider`
* `step` = The step increment of the `slider`

#### **slider.value**

`x = slider.value` — Returns the current value of the Slider. This is read/write.

Example:

```coffeescript
# Setup Code editor
s1 = slider(title="I'm A Slider", min=0, max=100, step=2)
```

```coffeescript
# Loop Code editor
x = s1.value
```

### Input

An `input` is an interactive widget that allows you to link a value in your scenario to the current value input into a text box.&#x20;

{% hint style="info" %}
Note: The input values are currently limited to numerical inputs.
{% endhint %}

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJwJRhhWOgviJhDOm5B%2F-MJwREDbAKH76quUSBfm%2FScreen%20Shot%202020-10-18%20at%209.00.01%20AM.png?alt=media&#x26;token=adb06121-207a-4b5d-b07f-b7843ecb933a" alt=""><figcaption><p>An <code>input</code> widget</p></figcaption></figure>

Below is the constructor for the `Input` widget:

`input(title="Input", align="left", min=0, max=100, step=1)`

* `title` — The text title of the `input`
* `align` = Optional value of "`left`" or "`right`" to align the input to the corresponding side of the view window.
* `min` = The minimum value that the user can enter in the `input`
* `max` = The maximum value that the user can enter in the `input`
* `step` = The step increment of the `input`

#### input.value

`x = input.value` — Returns the current value of the `Input`.

Example:

```python
# Setup Code editor
input_widget = input(title="Size", max=10, min=-10, step=.1)
```

```python
# Loop Code editor
x = input_widget.value
```

### menu

A `menu` is an interactive widget that allows you to link a value in your scenario to the current value selected from a drop-down menu.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCBQtB7AkKJtVQIbOdo%2F-MJwSbZ8SuvMe7T_flrR%2F-MJwUIXVbHC6fAt26-Jm%2FScreen%20Shot%202020-10-18%20at%209.13.35%20AM.png?alt=media&#x26;token=595f2842-baa5-419d-bd36-c67365821883" alt=""><figcaption><p>A <code>menu</code> widget</p></figcaption></figure>

Below is the constructor for the `menu` widget:

`menu(title="Menu", align="left", choices=[], values=[])`

* `title` — The text title of the `input`
* `align` = Optional value of "`left`" or "`right`" to align the menu to the corresponding side of the view window.
* `choices` — A `list` of menu choices.
* `values` — An optional `list` of corresponding menu values for each choice. If no values are given, the values are assumed to be the choices.

#### **menu.value**

`x = menu.value` — Returns the current value of the `menu`.

Example:

```python
# Setup Code editor
m = menu(title="Pick One", choices=["A","B","C"], values=[1,2,3])
```

```python
# Loop Code editor
x = menu.value
```

### control\_panel

A `control_panel` widget allows you to group other widgets together which better organizes your widgets. Once you create a `control_panel`, you simply add other UI widgets to it. You can can set the layput of the control\_panel to be either "row" or "column:.

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2F6oJNhSY9tfiDGeVZNuoj%2Ftychos_control_panel_2.png?alt=media&#x26;token=c1cd2af3-6e0b-42fc-adbf-5485b740c6ca" alt=""><figcaption><p>A control_panel with a "row" layout.</p></figcaption></figure>

Below is the constructor for the `control_panel` widget:

```coffeescript
control_panel(
  title="Control Panel", 
  align="left",
  layout="row")
```

* `title` — The text title of the `control_panel`
* `align` = Optional value of "`left`" or "`right`" to align the control panel to the corresponding side of the view window.
* `layout` — Either "row" to arrange the contained widgets horizontally, or "column" to arrang them vertically.

#### **control\_panel.add(\*widgets)**

To add widgets to a control panel, you simply supply the widgets' variable names to the add function, like this::

```python
# Define the Sliders
s_width = slider(title="Width", min=1, max=100, step=1)
s_height = slider(title="Height", min=1, max=100, step=1)
s_shade = slider(title="Shade", min=0, max=255, step=1)
s_opacity = slider(title="Opacity", min=0, max=1, step=.01, value=1)

cp = control_panel(title="Change the Rectangle", layout="column", align="left")
cp.add(s_width, s_height, s_shade, s_opacity)
```

The above would create a control\_panel that looks like this:

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FSI8uCMLkT86geCNwYuON%2Ftychos_control_panel_4.png?alt=media&#x26;token=b62a82c7-9406-4780-99d6-ef554889ef27" alt="" width="267"><figcaption><p>Conrol panel with four sliders added to it.</p></figcaption></figure>

## Interactivity

The following section describes additional interactivity that you can add through the use of `keyboard` and `mouse` objects.

### keyboard

The `keyboard` object represents your computers keyboard and has commands to see if any keys are pressed during a simulation.

#### **keyboard.is\_down**

`keyboard.is_down(key)` -> `boolean` — Return 1/0 whether `key` is currently down

#### **keyboard.last\_pressed**

`keyboard.last_pressed(key)` -> `boolean` — was `key` typed? i.e. key was pushed down then released.

#### **keyboard.keys**

`keyboard.keys` -> `list` — returns a list of string values representing all keys currently being pressed.

### mouse

The `mouse` object represents your compute&#x72;**'**&#x73; mouse.

#### **mouse.pos**

`mouse.pos` -> `vec` — Returns two dimensional vector representing the position of the mouse in the simulation space.

#### **mouse.is\_down**

`mouse.is_down(button_num=0)` -> `boolean` — Returns whether the mouse button is pressed. `button_num` — Which button to check? 0 = primary button, 1 = secondary, etc.

## Audio

The `audio` object can be used to add sound to your scenarios. This can be done by creating an `oscillator` that plays a continuous frequency using a specified wave type, or by creating a `sound` object that plays an audio file given a URL, or finally by just playing a specified tone for a specified amount of time.

### audio.sound

To create a sound object, you need to specify a URL for the location of the .wav, .ogg, or .mp3 file

`my_sound = audio.sound("https://www.example.com/my_cool_sound.wav")`

<pre class="language-python"><code class="lang-python"># Create a sound from a URL or an asset name
my_sound = audio.sound("https://www.example.com/my_cool_sound.wav")
my_sound2 = audio.sound("cool_sound2.mp3")

# Change the volume
my_sound.volume = 1.5 # 150% volume
my_sound2.volume = .5 # 50% volume

# Change the playback rate
<strong>my_sound1.playback_rate = 5.0 # 5 time faster
</strong>my_sound2.playback_rate = 0.5 # Half playback rate.

# Play it, or if playing already, don't play it
if not my_sound.is_playing:
    my_sound.play()
if my_sound2.is_playing:
    my_sound2.stop()
</code></pre>

The sound object has these methods and attributes:

* `play()` - Plays the sound file.
* `stop()` - If the sound file is currently playing, it stops the sound file.
* `volume` - (*read/write*) A numeric value that determines the volume that the sound file will play at. Value must be larger than 0 to hear the sound.
* `playback_rate` - (*read/write*) A numeric value that determines the playback speed of the file. If a negative value is given, the file plays backwards.
* `is_playing` - (*read only*) A boolean value that indicates whether the sound is currently playing.

### audio.oscillator

An oscillator object is created using this constructor method:

`my_oscillator = audio.oscillator(freq=400, volume=1, type="sine")`

The oscillator object has these methods and attributes:

* `oscillator.start()` - Starts the oscillation.
* `oscillator.stop()` - Stops the oscillation.
* `oscillator.freq` - A numeric value that determines the frequency of the sound wave that the oscillator will generate.
* `oscillator.volume` - A numeric value that determines the volume of the sound wave that the oscillator will generate. Value must be larger than 0 to hear the sound.
* `oscillator.type` - A string value of "sine", "square", "sawtooth", or "triangle" that determines the type of oscillation.

Finally, you can also call a method directly on the `audio` object for generating a tone for a specified amount of time:

#### audio.play\_tone

`audio.play_tone(freq, volume, time)` — Produces an audio tone for the specified time at the specified frequency (`freq`) and volume.

## CSV Files

Comma separated files can be loaded into the current session of Tychos, and then the data can be read into your scenarios.

You need to upload the file through the interface, found in the Settings Tab of the Hack Panel:

![](https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FOCCSRgg9q7Dx08TMRXYK%2Fcsv_data_upload.png?alt=media\&token=bc94c261-be83-4fde-a620-24584c1903af)

Once this has been done, you can access the data in the file using the `csv_files` object.

### csv\_files

This object is a list of Python dictionaries representing the data contained in each file.

You access each file as you would any list in Python:

```python
my_file = csv_files[0]
```

### CSV file

For example, let's say your CSV file has the name `"my_data.csv"` and looks like this:

{% code lineNumbers="true" %}

```csv
Time, X, Y
0, 10, -10
1, 11, -9
2, 12, -8
```

{% endcode %}

The dictionary has two keys, one representing the name of the file, and the other representing the data in the file:

{% code lineNumbers="true" %}

```python
name = my_file["name"] # Returns string "my_data.csv"
data = my_file["data"] # Returns list of dictionary objects
```

{% endcode %}

The data is itself a list, representing the rows of the data in the file. Each row is a dictionary whose keys correspond to the column headers in the CSV file:

```python
my_file.data[1] # Returns {"Time":"0", "X":"10", "Y":"-10"}
```

Then to access the *X* value in the file located at row 2 of the data (line #3 above), then you would type:

```python
x = float(data[1]["X"] # Returns 11.0
```

{% hint style="info" %}
It is important to note that the values stored in the dictionary objects are all string values. You will need to cast them to the appropriate data type when using them in your code.
{% endhint %}
