Some games need to know where things are, more precisely than “in this room”: a boat crossing an ocean, cars on a race track, spaceships in a sector, or simply rooms with coordinates so you can find every room within 50 steps. Pythelix gives you three building blocks for that, and leaves the rest (how boats steer, what happens when a car leaves the track) to your scripts:
- vectors: a position, a speed, a direction;
- segments: a line between two points, like a stretch of coast;
- layers: collections of points and segments you can ask questions about (“what does this boat hit if it moves there?”, “which ships are within 200 units?”).
None of this assumes a genre. A layer can be 2D or 3D, and you can have as many as you want.
Vectors
A vector has two components (x and y) or three (x, y and z):
> py Vector(3, 4)
Vector(3, 4)
> py Vector(3, 4).length
5.0
> py Vector(1, 2) + Vector(10, 20)
Vector(11, 22)
> py Vector(1, 2) * 3
Vector(3, 6)
You can add and subtract vectors, and multiply or divide them by a number. Multiplying two vectors is ambiguous, so it has names instead: dot, cross and scale (component by component).
| Attribute or method | What it gives |
|---|---|
x, y, z |
The components (z only on 3D vectors). |
dims |
2 or 3. |
length |
The length of the vector. |
angle, angle_rad |
The angle of a 2D vector, in degrees or radians. |
distance(other) |
The distance to another vector. |
normalized() |
A vector of length 1 in the same direction. |
rotate(degrees), rotate_rad(radians) |
The vector turned counterclockwise. 3D vectors need an axis: rotate(90, axis=Vector(0, 0, 1)). |
dot(other) |
The dot product: how much two vectors point the same way. |
cross(other) |
In 2D, a number: positive if other is counterclockwise from the vector. In 3D, a perpendicular vector. |
scale(other) |
Multiply component by component. |
Vector.from_angle(degrees, length) |
Build a 2D vector from an angle (from_angle_rad for radians). |
Vectors are immutable: methods and operators always return a new vector. That’s what makes this safe:
ship.position += ship.velocity
The += creates a new vector and assigns it to the attribute, so the change is saved like any other.
Angles
Angles are in degrees by default, and follow the mathematical convention: 0 points east (+x), and angles turn counterclockwise, so 90 points north (+y). Every function that takes or returns an angle has a _rad twin for radians.
Games often prefer compass headings (0 is north, turning clockwise). The conversion is a single line, which you can put on your own parent entity:
!generic/ship!
def heading():
return (90 - self.velocity.angle) % 360
def set_heading(degrees):
self.velocity = Vector.from_angle(90 - degrees, self.velocity.length)
Segments
A segment joins two vectors. Any keyword argument is kept as its data, which Pythelix never reads: it’s yours.
> py Segment(Vector(0, 0), Vector(100, 100), coast="marsh")
Segment(Vector(0, 0), Vector(100, 100), coast="marsh")
> py Segment(Vector(0, 0), Vector(100, 100), coast="marsh").data["coast"]
"marsh"
| Attribute or method | What it gives |
|---|---|
start, end |
The two vectors. |
data |
A dict of the keyword arguments given when creating the segment. |
length, direction |
The length, and the vector from start to end. |
closest_point(point) |
The point of the segment closest to a vector. |
distance(other) |
The distance to a vector or to another segment. |
intersection(other) |
Where two segments meet, or None. |
Segment.chain(points, closed=False) |
The segments joining a list of vectors. With closed=True, the last point is joined to the first, which forms a closed shape. Keyword arguments become the data of every segment. |
Like vectors, segments are immutable. To change a segment’s data, replace the segment.
Layers
A layer is an entity inheriting from generic/layer. Other entities take part in it through three attributes:
layer: the layer they belong to;coordinates: a vector, which adds a point to the layer;segments: a list of segments, which are added to the layer.
Only layer puts an entity in a layer, and only if it names an entity inheriting from generic/layer. Without one, coordinates and segments are attributes like any other: Pythelix doesn’t look at them.
Here’s an ocean with an island, and boats:
!layer/obstacle!
parent = "generic/layer"
!ocean/great!
layer = !layer/obstacle!
segments = Segment.chain([Vector(0, 0), Vector(1000, 0), Vector(1000, 1000), Vector(0, 1000)], closed=True, coast="cliff")
!island/turtle!
layer = !layer/obstacle!
segments = Segment.chain([Vector(400, 400), Vector(600, 400), Vector(600, 600), Vector(400, 600)], closed=True, coast="beach")
!layer/boat!
parent = "generic/layer"
!generic/boat!
layer = !layer/boat!
!boat/swift!
parent = "generic/boat"
coordinates = Vector(100, 500)
A few things to notice:
- The ocean and the island are in the same layer. A boat collides with both the same way: a layer doesn’t know what an “island” is, only segments.
- Data is per segment. Here every segment of a shape shares its data, but you can build the list yourself and give each segment its own (a marsh here, a cliff there).
layeris inherited. Every boat whose parent isgeneric/boatis inlayer/boat, including the boats you create in game.- Winds, rooms or ships can go in layers of their own. Queries are run on one layer at a time, so a storm doesn’t become a wall.
A layer with its own shapes
A layer’s own coordinates and segments are part of it. The ocean can then be the layer, and the islands are in it:
!ocean/great!
parent = "generic/layer"
segments = Segment.chain([Vector(0, 0), Vector(1000, 0), Vector(1000, 1000), Vector(0, 1000)], closed=True, coast="cliff")
!island/turtle!
layer = !ocean/great!
segments = Segment.chain([Vector(400, 400), Vector(600, 400), Vector(600, 600), Vector(400, 600)], closed=True, coast="beach")
Both ways work: a separate layer suits several oceans sharing one, this one reads more naturally for a single sea.
Coasts of several kinds
segments is a plain list: a layer doesn’t know which segments form which shape, and doesn’t need to. An island with a beach on one side and a marsh on the other joins two chains:
!island/turtle!
layer = !layer/obstacle!
segments = Segment.chain([Vector(400, 400), Vector(600, 400), Vector(600, 600)], coast="beach") + Segment.chain([Vector(600, 600), Vector(400, 600), Vector(400, 400)], coast="marsh")
Each chain stops where the next one starts, and the last one ends where the first began, which closes the island. For a coast that changes every few segments, build the list one Segment at a time.
Layers are only an index: they’re kept in memory, never stored. The shapes belong to the entities’ attributes, and the index follows them. When a boat’s coordinates change, it moves in its layer; when an island’s segments change, the layer changes with them. When the server restarts, layers are rebuilt from the worldlets and from the stored entities that have coordinates or segments.
Queries
Every query returns hits. A hit tells you what was found:
| Attribute | What it gives |
|---|---|
entity |
The entity the shape belongs to (the island, the boat). |
shape |
The vector or segment that was found. |
point |
The point found on it (the point of collision, the closest point). |
distance |
How far it is. |
The layer offers four queries:
| Method | What it does |
|---|---|
first_hit(path) |
The first segment a path (a segment) crosses, from its start, or None. Points can’t be crossed and are ignored. |
nearest(point, max_distance=None) |
The closest shape, or None. |
within(center, radius) |
Every shape within a radius, closest first. |
contains(point) |
Whether a point is inside the shapes formed by the layer’s segments (see below). |
first_hit, nearest and within also accept exclude=entity, which ignores the shapes of that entity: a boat looking for the nearest boat would otherwise find itself. The count attribute gives the number of shapes in the layer.
Moving without crossing the coast
The usual way to move something is to test the path rather than the destination: a fast boat could otherwise jump over a thin strip of land.
!generic/boat!
layer = !layer/boat!
def sail():
path = Segment(self.coordinates, self.coordinates + self.velocity)
hit = !layer/obstacle!.first_hit(path)
if hit:
self.coordinates = hit.point - self.velocity.normalized()
else:
self.coordinates = path.end
endif
return hit
hit.shape.data["coast"] then tells the caller what the boat ran into. What happens on a collision is up to you: stop, slide along the coast, take damage, offer to dock. The layer tells you where, and what was hit.
Inside or outside
contains draws a line from the point and counts how many segments it crosses. An odd number means inside. This works with shapes inside shapes without any extra work:
- in open water, the line crosses the coast once: inside;
- on the island, it crosses the island’s edge and the coast: outside;
- on a lake on the island, it crosses once more: inside again.
contains works on 2D layers, and only counts segments.
3D layers
A layer is 2D unless it says otherwise:
!layer/sector!
parent = "generic/layer"
dims = 3
Its shapes and queries then use 3D vectors. A shape with the wrong number of dimensions is left out of the layer, with a warning in the server log.
Rooms with coordinates
Rooms are entities like any other:
!layer/rooms!
parent = "generic/layer"
!room/bakery!
parent = "generic/room"
layer = !layer/rooms!
coordinates = Vector(12, 4)
!layer/rooms!.within(location.coordinates, 50) then gives every room within 50 units. This distance is as the crow flies, not by walking through exits: two rooms with a wall between them are close for the layer.
Performance
Queries go through every shape of the layer, natively, which is fast for layers of hundreds or a few thousand shapes. You’ll rarely need more than that: in a text game, a coast of a hundred well-placed segments reads just as well as one of ten thousand. What matters more is to call layer queries rather than looping over shapes in Pythello yourself.
Moving an entity only updates that entity in its layer, whatever the layer’s size: moving every room of every ship on each tick is fine for a few thousand rooms.