group¶
- class Group(
- id: str | None =
None, - *,
- extra_keys: dict[str, Any] | None =
None, - entities: EntityList =
NOTHING, - tiles: TileList =
NOTHING, - groups: CollectionList =
NOTHING, - schedules: ScheduleList =
NOTHING, - wires=
NOTHING, - parameters: list[IDParameter | NumberParameter] =
NOTHING, - stock_connections: list[StockConnection] =
NOTHING, - name: str =
'group', - type: str =
'group', - position=
NOTHING, - collision_mask=
NOTHING, Bases:
Transformable,Collection,EntityLike,ExportableGroup entities together, so you can manipulate them all as one unit.
Allows for the creation of “blocks” that can be added multiple times very easily to a blueprint. This allows you to create a complex portion of your desired blueprint only once, and then add that
Groupmultiple times to the final blueprint.Groups can also be used to organize Blueprints at the structure level. You can give entities the same name in a Blueprint as long as they exist in different groups. For example, the following is a perfectly valid structure for a Blueprint to have:
Blueprint().groups = [ Group("1").entities = [Entity(id="A"), Entity(id="B"), Entity(id="C")], Group("2").entities = [Entity(id="A"), Entity(id="B"), Entity(id="C")], ]This is particularly useful if each group has a similar function, but just exists as a different “part” of the overall blueprint.
EntityLikeinstances in a Group are considered to be in “group-space”; meaning their positions are offset by the position of the Group they reside in. If a Group is located at position(5, 5), and an entity inside of it is located at(5, 5), when the group is added to a parent Blueprint the contained entity will be located at the position(10, 10). This effect continues if Groups nest inside of other Groups, which is also perfectly legal.- property circuit_connectable : bool¶
Whether or not this EntityLike can be connected using circuit wires.
- Example:
>>> from draftsman.entity import * >>> Beacon().circuit_connectable False >>> Inserter().circuit_connectable True >>> DeciderCombinator().circuit_connectable True
- collision_mask : set[str]¶
The set of all collision layers that this group collides with, specified as strings. Defaults to an empty
set.
- property collision_set : CollisionSet | None¶
TODO: is this even a good idea to have in the first place? It seems like having this set be the union of all entities it contains would make the most sense, but that would be slow to compute instead of using a spatial map for that. The user could specify a custom collision set, but how is that supposed to interact with the hashmap? no idea
- property double_grid_aligned : bool¶
Whether or not this EntityLike is “double-grid-aligned”, which applies to entities which need to align with the rail grid.
- property dual_circuit_connectable : bool¶
Whether or not this EntityLike has two circuit connection points.
- Example:
>>> from draftsman.entity import * >>> Beacon().dual_circuit_connectable False >>> Inserter().dual_circuit_connectable False >>> DeciderCombinator().dual_circuit_connectable True
- property dual_power_connectable : bool¶
Whether or not this EntityLike has two power connection points.
- Example:
>>> from draftsman.entity import * >>> Beacon().dual_power_connectable False >>> ElectricPole().dual_power_connectable False >>> PowerSwitch().dual_power_connectable True
- entities : EntityList¶
Serialized
This attribute is imported/exported from blueprint strings.
The list containing this collection’s entities.
Supports inserting/appending new entities via a string name, as well as any keyword arguments to pass to that entity’s constructor:
blueprint.entities.append("wooden-chest", bar=10) assert type(blueprint.entities[-1]) is Container assert blueprint.entities[-1].name == "wooden-chest" assert blueprint.entities[-1].bar == 10In addition to indexing by integer location,
EntityListalso supports indexing via string, corresponding to theidof the entity:blueprint.entities.insert(0, "wooden-chest", id="example") assert blueprint.entities["example"] is blueprint.entities[0]
- extra_keys : dict[str, Any] | None¶
Serialized
This attribute is imported/exported from blueprint strings.
Any additional keys that are not recognized by Draftsman when loading from a raw JSON dictionary end up as keys in this attribute. Under normal circumstances, this field should always remain
None, indicating that all fields provided were properly translated into the internal Python format.If there are any values in
extra_keysafter being imported from a raw JSON dictionary, then (left alone) these values will also be exported back into an output JSON dictionary in order to keep import-export cycles stable. A side effect of this is that users can use this attribute to add additional fields that will end up in the output string, primarily for custom metadata that can be read by other tools:>>> input_dict = { ... "name": "wooden-chest", ... "position": {"x": 0.5, "y": 0.5}, ... "unknown_key": "blah" ... } >>> container = Container.from_dict(input_dict) >>> container.extra_keys {"unknown_key": "blah"} >>> container.extra_keys["custom"] = "data" >>> container.to_dict() { "name": "wooden-chest", "position": {"x": 0.5, "y": 0.5}, "unknown_key": "blah", "custom": "data" }The structure of input keys are preserved, meaning you may have to recurse through keys to find the unknown data:
>>> input_dict = { ... "name": "wooden-chest", ... "position": {"x": 0.5, "y": 0.5}, ... "nested": { ... "dictionary": "value" ... } ... } >>> container = Container.from_dict(input_dict) >>> container.extra_keys {"nested": {"dictionary": "value"}}Note
While Draftsman makes an effort to preserve keys that it doesn’t recognize, Factorio itself makes no such effort - so if you create a blueprint string with custom metadata and then import it into the game, that additional data will be stripped and cannot be retrieved when exporting a new string from the game.
- property flags : set[str]¶
The set of flags associated with this EntityLike. Returns
Noneif the entitylike is not recognized by Draftsman.
- property flippable : bool¶
Whether or not this collection can be flipped or not. This is determined by whether or not any of the entities contained can be flipped or not. Read only.
- property global_position : Vector¶
The “global”, or root-most position of the Group. This value is always equivalent to
position, unless the group exists inside anotherCollection. If it does, then it’s global position is equivalent to the sum of all parent positions plus it’s own position. Used when recursing the position of any sub-entity contained within theGroup. Read only.
- groups : CollectionList¶
A list of child
Groupobjects that this collection contains.Like
EntityList, Groups added to this list with populated IDs can be accessed via those IDs:>>> from draftsman.blueprintable import Blueprint, Group >>> blueprint = Blueprint() >>> new_group = Group(id="something") >>> blueprint.groups.append(new_group) Group(...) >>> assert blueprint.groups["something"] == new_groupThis attribute is not exported. Instead, all entities/tiles that are contained within it are “flattened” to the root-most entity/tile lists, with their positions and associations preserved.
Added in version 3.0.0.
- id : str | None¶
The ID of the Group. The most local form of identification between Groups.
- name : str¶
The name of the Group. Defaults to
"group". Can be specified to any string to aid in organization and querying.
- parameters : list[IDParameter | NumberParameter]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of all
Parameters that this blueprint implements.Parameters are evaluated sequentially from the beginning of the list to the end.
Added in version 3.1.0: (Factorio 2.0)
- property parent : Collection | None¶
The parent
Collectionobject that contains the entity, orNoneif the entity does not currently exist within anCollection.
- position : Vector¶
The position of the Group. Acts as the origin of all the entities contained within, and offsets them on export.
- property power_connectable : bool¶
Whether or not this EntityLike can be connected using power wires.
- Example:
>>> from draftsman.entity import * >>> Beacon().power_connectable False >>> ElectricPole().power_connectable True >>> PowerSwitch().power_connectable True
- property rotatable : bool¶
Whether or not this collection can be rotated or not. Included for posterity; always returns True, even when containing entities that have no direction component. Read only.
- schedules : ScheduleList¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of the Collections’s
Schedules.
- stock_connections : list[StockConnection]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of connections between train cars, documenting exactly which ones are connected to what. Prior to Factorio 2.0, train car connections were inferred and automatically generated on blueprint import; this field allows for manual control over this behavior.
Added in version 3.0.0: (Factorio 2.0)
- tiles : TileList¶
Serialized
This attribute is imported/exported from blueprint strings.
The list containing this collection’s tiles.
Supports inserting/appending new tiles via a string name, as well as any keyword arguments to pass to that entity’s constructor:
blueprint.tiles.append("landfill") assert type(blueprint.tiles[-1]) is Tile assert blueprint.tiles[-1].name == "landfill"
- type : str¶
The type of the Group. Defaults to
"group". Can be specified to any string to aid in organization and querying.
- wires : list[list[Association, WireConnectorID, Association, WireConnectorID]]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of all the wire connections in this blueprint.
Wires are specified as two pairs of
AssociationandWireConnectorID; the first pair represents the first entity, and the second pair represents the second entity. The association points to the corresponding entity in this collection, and the wire type enum indicates what type of connection it is.When exported to JSON, the associations and enums in each wire are resolved to integers corresponding to the given
entity_numberin the resultingentitieslist.Added in version 3.0.0: (Factorio 2.0)
- add_circuit_connection(
- color: 'red' | 'green',
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Adds a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID. Color specifies the color of the wire to make the connection with, and is either"red"or"green".side1specifies which side of the first entity to connect to (if applicable), andside2specifies which side of the second entity to connect to (if applicable). Does nothing if the connection already exists.Raises
ConnectionSideWarningif the side of either of the entities is2when the entity is not dual-circuit-connectable.Raises
ConnectionRangeWarningif the distance between the two entities exceeds the maximum wire distance between the two.- Parameters:
- color: 'red' | 'green'¶
Color of the wire to make the connection with. Must be either
"red"or"green".- entity_1: EntityLike | int | str | Sequence[int | str]¶
ID or index of the first entity to join.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
ID or index of the second entity to join.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to connect to. Only necessary to specify for entities that areEntity.dual_circuit_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to connect to. Only necessary to specify for entities that areEntity.dual_circuit_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.InvalidWireTypeError – If
coloris neither"red"nor"green".InvalidConnectionSideError – If
side_1orside_2are neither"input"nor"output".EntityNotCircuitConnectableError – If either entity_1 or entity_2 do not have the capability to be circuit wire connected.
- add_power_connection(
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Adds a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID. Tuples of strings and ints mean to recursively search through theCollection‘sgroupsfor an entity at that tree “path”. For example:blueprint.entities.append("small-electric-pole") group = Group("group") # A type of `Collection` group.entities.append("small-electric-pole", tile_position=(5, 0)) blueprint.groups.append(group) # Add a connection between the first power pole and the first entity # in the group blueprint.add_power_connection(blueprint.entities[0], ("group", 0))Side specifies which side to connect to when establishing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the connection already exists.
Raises
ConnectionRangeWarningif the distance between the two entities exceeds the maximum wire distance between the two.Raises
TooManyConnectionsWarningif either of the power poles exceed 5 connections when this connection is added.- Parameters:
- entity_1: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID, or index of the first entity to join.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the second entity to join.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to connect power to. Only necessary to specify for entities that areEntity.dual_power_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to connect power to. Only necessary to specify for entities that areEntity.dual_power_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.EntityNotPowerConnectableError – If either entity_1 or entity_2 do not have the capability to be copper wire connected.
DraftsmanError – If both entity_1 and entity_2 are dual-power-connectable, of which a connection is forbidden.
- add_train_at_position(
- config: TrainConfiguration,
- position: Vector | tuple[int | float, int | float],
- direction: Direction,
- schedule: Schedule | None =
None, Adds a train with a specified configuration and schedule at a position facing a particular direction. Allows you to place a fully configured train in a single function call.
If schedule is
specified, then it’s checked if that schedule already exists within the collection’sschedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.- Parameters:
- config: TrainConfiguration¶
The
TrainConfigurationto use as a template for the created train, or a str that will be converted into one.- position: Vector | tuple[int | float, int | float]¶
A
Vectorspecifying the center of the starting wagon.- direction: Direction¶
A
Directionenum orintspecifying which direction the train is “facing”.- schedule: Schedule | None =
None¶ A
Scheduleobject specifying the schedule that the newly created train should inherit.
- add_train_at_station(
- config: TrainConfiguration,
- station: EntityLike | str | int,
- schedule: Schedule | None =
None, Adds a train with a specified configuration and schedule behind a specified train stop.
If schedule is
specified, then it’s checked if that schedule already exists within the collection’sschedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.- Parameters:
- config: TrainConfiguration¶
The
TrainConfigurationto use as a template for the created train, or a str that will be converted into one.- station: EntityLike | str | int¶
The ID or index of the train entity stop to spawn behind. Note that station names cannot be used; if you want to place a train behind a stop with a specific station name use
find_entities_filtered()to find candidates and then pick ones from there.- schedule: Schedule | None =
None¶ A
Scheduleobject specifying the schedule that the newly created train should inherit.
- find_entities( ) list[EntityLike]¶
Returns a
listof all entities within the areaaabb. Works similiarly to LuaSurface.find_entities. If noaabbis provided then the method simply returns all the entities in the blueprint.
- find_entities_filtered(
- position: Vector | None =
None, - radius: float | None =
None, - area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None, - name: str | set[str] | None =
None, - type: str | set[str] | None =
None, - direction: Direction | None =
None, - invert: bool =
False, - limit: int | None =
None, Returns a filtered list of entities within the
Collection. Works similarly to LuaSurface.find_entities_filtered.Keywords are organized into two main categrories: region and criteria:
Region keywords¶ Name
Type
Description
positionVectororPrimitiveVectorGrid position to search.
radiusfloatRadius of the circle around position to search.
areaAABBorPrimitiveAABBAABB to search in.
If none of the above are specified, then the search area becomes the entire Collection. If
radiusis specified butpositionis not, the search area also becomes the entire Collection.Criteria keywords¶ Name
Type
Description
namestrorset{str}The name(s) of the entities that you want to search for.
typestrorset{str}The type(s) of the entities that you want to search for.
directionDirectionorset{Direction}The direction(s) of the entities that you want to search for.Excludes entities that have no direction.limitintLimit the maximum size of the returned list to this amount.Unlimited by default.invertboolWhether or not to return the inverse of the search.False by default.- Parameters:
- position: Vector | None =
None¶ The global position to search the source Collection. Can be used in conjunction with
radiusto search a circle instead of a single point. Takes precedence overarea.- radius: float | None =
None¶ The radius of the circle centered around
positionto search. Must be defined alongsidepositionin order to search in a circular area.- area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None¶ The
AABBorPrimitiveAABBto search in.- name: str | set[str] | None =
None¶ Either a
str, or aset[str]where each entry is a name of an entity to be returned.- type: str | set[str] | None =
None¶ Either a
str, or aset[str]where each entry is a type of an entity to be returned.- direction: Direction | None =
None¶ Either a
Directionenum (or correspondingint), or aset[Direction]where each entry is a valid direction for each returned entity to match. Excludes entities that have no direction attribute.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ The total number of matching entities to return. Unlimited by default.
- position: Vector | None =
- Returns:
A list of Entity references inside the searched collection that satisfy the search criteria.
- find_entity( ) EntityLike¶
Finds an entity with
nameat a positionposition. If multiple entities exist at the queried position, the one that was first placed is returned.
- find_entity_at_position( ) EntityLike¶
Finds any entity at the position
position. If multiple entities exist at the queried position, the one that was first placed is returned.
- find_tile( ) list[Tile]¶
Returns a list containing all the tiles at the tile coordinate
position. If there are no tiles at that position, an empty list is returned.
- find_tiles_filtered(
- position: Vector | tuple[int | float, int | float] | None =
None, - radius: float | None =
None, - area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None, - name: str | None =
None, - invert: bool =
False, - limit: int | None =
None, Returns a filtered list of tiles within the blueprint. Works similarly to LuaSurface.find_tiles_filtered.
Keywords are organized into two main categrories: region and criteria:
Region keywords¶ Name
Type
Description
positionVectororPrimitiveVectorGrid position to search.
radiusfloatRadius of the circle around position to search.
areaAABBorPrimitiveAABBAABB to search in.
Criteria keywords¶ Name
Type
Description
namestrorset{str}The name(s) of the entities that you want to search for.
limitintLimit the maximum size of the returned list to this amount.Unlimited by default.invertboolWhether or not to return the inverse of the search.Falseby default.- Parameters:
- position: Vector | tuple[int | float, int | float] | None =
None¶ The global position to search the source Collection. Can be used in conjunction with
radiusto search a circle instead of a single point. Takes precedence overarea.- radius: float | None =
None¶ The radius of the circle centered around
positionto search. Must be defined alongsidepositionin order to search in a circular area.- area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None¶ The
AABBorPrimitiveAABBto search in.- name: str | None =
None¶ Either a
str, or aset[str]where each entry is a name of an entity to be returned.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ The total number of matching entities to return. Unlimited by default.
- position: Vector | tuple[int | float, int | float] | None =
- Returns:
A list of Tile references inside the searched collection that match the specified criteria.
- find_train_from_wagon( ) list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]¶
Returns a list of rolling stock connected together. Allows you to grab all connected cars to a particular wagon if you know where one is, such as when iterating through the locomotives in a particular
Scheduleobject, cargo wagons with a particular item filter returned fromfind_entities_filtered(), etc.Note that this function may return a working train (rolling stock with at least one connected locomotive), but it also may not, since it’s only criteria is connection.
Warning
This function might also return false positives if rolling stock is located right next to each other in a fully-compresssed rail setups. PR’s to mitigate this are welcome.
- Parameters:
- wagon: Locomotive | CargoWagon | FluidWagon | ArtilleryWagon¶
The ID of the wagon or the wagon itself to search for neighbours.
- Returns:
A
listof references to all connected wagons in theCollection, includingwagonitself. The order of wagons is listed from end to end, where the first entry in the list is the outermost car in the direction thatwagonpoints.
- find_trains_filtered(
- train_length: int | tuple | None =
None, - orientation: Orientation | None =
None, - at_station: bool | set =
False, - num_type: dict | None =
None, - num_name: dict | None =
None, - config: TrainConfiguration | None =
None, - schedule: Schedule | None =
None, - invert: bool =
False, - limit: int | None =
None, Finds a set of trains that match the passed in parameters. Formally, a “train” in this context is a connected set of wagons which may or may not contain a locomotive. This is done so that the user can search a blueprint for unconnected rolling stock if any exists, and can filter for regular trains more broadly.
Note
When using the
configparameter, equality is strictly checked; which means that if a returned train doesn’t _exactly_ match the specified argument, the train is filtered from the result. This includes things like fuel requests and cargo wagon item filters, so check these values in the blueprints you’re searching and adjustconfigaccordingly.- Parameters:
- train_length: int | tuple | None =
None¶ Can either be specified as an
intrepresenting the exact length of trains to return, or as aSequenceof 2int``s representing the minimum and maximum length of trains to return (inclusive). Either the min or the max can also be set to ``Nonewhich indicates no minimum length and no maxiumum length respectively.- orientation: Orientation | None =
None¶ A
Orientation(or equivalentfloat) that describes the orientation that every car in the returned train list should have. Note that trains placed on curved rails will not be returned by this parameter, as _all_ train cars must equalorientation.- at_station: bool | set =
False¶ Can be specified as a
boolvalue which will return all trains at any station, astrvalue where it will return all trains at any station with that name, or as aset[str]where all of the trains behind any station with one of those names is returned.- num_type: dict | None =
None¶ A
dictof wagon types where each key is thestrtype of the wagon and the value is anintrepresenting the desired number of those wagons in the returned train. Allows to search for trains of a particular composition without regards to contents, order, or orientation. Also supports swapping theintwith aSequenceof 2int``s representing the minimum and maximum tolerable value of a wagon of that type, along with ``Nonefor no particular min or max.- num_name: dict | None =
None¶ Identical to
num_type, except that instead of wagon type it’s wagon name, in case there happen to be more than one Locomotive, CargoWagon, FluidWagon, or ArtilleryWagon. Useful for blueprints with modded trains, where you might want to distinguish between them.- config: TrainConfiguration | None =
None¶ A
TrainConfigurationobject to filter against. Performs a equality check between each of the train configuration’s cars and the cars in the returned trains.- schedule: Schedule | None =
None¶ A
Schedulethat the returned trains should match. Only trains who’s schedules match this one exactly will be returned.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ A maximum number of unique trains to return.
- train_length: int | tuple | None =
- Returns:
A
listoflists, where each sub-list represents a contiguous train. Trains are ordered such that the first index is the “front” of the train, as chosen by the orientation of the first found wagon in that group.
-
flip(direction: 'horizontal' | 'vertical' =
'horizontal') None¶ Flip the blueprint across an axis, if possible. Flipping is done over the x or y axis, depeding on the input
direction.- Parameters:
- direction: 'horizontal' | 'vertical' =
'horizontal'¶ The direction to flip by; either
"horizontal"or"vertical"
- direction: 'horizontal' | 'vertical' =
- classmethod from_dict( ) Self¶
Attempts to construct a new instance of this class from a Python dictionary in JSON format.
- Parameters:
- d: dict¶
The dictionary to interpret.
- version: tuple[int, ...] | None =
None¶ The Factorio version that the input data is compliant with.
The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of
(1, 1, 96)will use the 1.0 converter, and a version of(2, 0, 32)will use the 2.0 converter.If no version is provided, it will default to current environment’s Factorio version, or to
draftsman.DEFAULT_FACTORIO_VERSIONif unable to read the current environment.
- classmethod from_string(string: str)¶
Creates a
Groupwith the contents of aBlueprintstring.Raises
UnknownKeywordWarningif there are any unrecognized keywords in the blueprint string for this particular blueprintable.- Parameters:
- string: str¶
Factorio-encoded blueprint string.
- Raises:
MalformedBlueprintStringError – If the input string is not decodable to a JSON object.
IncorrectBlueprintTypeError – If the input string is of a different type than the base class, such as trying to load the string of an upgrade planner into a
Blueprintobject.
- generate_power_connections(
- prefer_axis: bool =
True, - only_axis: bool =
False, Automatically create power connections between all electric poles.
The algorithm used is similar to demi-pixel’s generateElectricalConnections() function, but with some slight differences. Power poles are still prioritized closest first, but can be selected to prefer to connect neighbours on the same axis, as well as only connect to neighbours on the same axis. This function will only connect power poles that have less than 5 power connections already made, preserving power connections that were manually specified. This function does not generate connections between power-switches.
- Parameters:
- prefer_axis: bool =
True¶ Determines whether or not to rank power-poles on the same x or y coordinate higher than poles that are closer, but not on either axis. Used to prefer creating neat, regular grids when possible.
- only_axis: bool =
False¶ Removes any neighbour that does not lie on the same x or y axis from the candidate pool, preventing non-grid connections.
- prefer_axis: bool =
- get() list[Entity]¶
Gets all the child-most
Entityinstances in thisGroupand returns them as a “flattened” 1-dimensional list. Offsets all of their positions by the position of the parentGroup.- Returns:
A
listofEntityinstances associated with thisGroup.
- get_world_bounding_box() AABB | None¶
Gets the world-space coordinates AABB that completely encompasses the
collision_setof thisSpatialLike. ReturnsNoneif the collision set of the target object is unknown.
- get_world_collision_set() CollisionSet¶
Get’s the world-space coordinate
CollisionSetof the object, AKA the collection of all shapes that this EntityLike interacts with.- Returns:
A copy of this objects
CollisionSetwith the correct world-space location.
- mergable_with(other: EntityLike) bool¶
Checks to see if an entity is “mergable” with another entity. This means that if a certain set of criteria is met, the attributes of
otherwill be combined to the attributes of this entity. This is useful for mimicking cases where entities of the same name and type are placed on top of each other, merging them together into a single entity with shared attributes.For the full list of all merging rules, see (TODO).
Note
This function does not actually merge the two, it simply checks to see if such a merge is considered valid. To actually merge the two entities use
merge().- Parameters:
- other: EntityLike¶
The other
EntityLiketo check against.
- Returns:
Trueif they can be merged,Falseotherwise.
- merge(other: EntityLike)¶
Changes the attributes of the calling entity with the attributes of the passed in entity. The attributes of
othertake precedence over the attributes of the calling entity. They can be either copied or merged together, depending on the specific attribute being merged.For the full list of all merging rules, see (TODO).
- Parameters:
- other: EntityLike¶
The other
EntityLiketo merge with.
- remove_circuit_connection(
- color: 'red' | 'green',
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Removes a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID.side1specifies which side of the first entity to remove the connection from (if applicable), andside2specifies which side of the second entity to remove the connection from (if applicable). Does nothing if the specified connection doesn’t exist.- Parameters:
- color: 'red' | 'green'¶
Color of the wire to remove. Either
"red"or"green".- entity_1: EntityLike | int | str | Sequence[int | str]¶
ID or index of the first entity to remove the connection to.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
ID or index of the second entity to remove the connection to.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to remove the connection from. Only necessary to specify for entities that areEntity.dual_circuit_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to remove the connection from. Only necessary to specify for entities that areEntity.dual_circuit_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.
- remove_circuit_connections() None¶
Remove all circuit connections in the Collection. Recurses through all subgroups and removes circuit connections from them as well. Does nothing if there are no circuit connections in the Collection to remove.
- remove_power_connection(
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Removes a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID.sidespecifies which side to remove the connection from when removing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the specified connection does not exist.- Parameters:
- entity_1: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the first entity to remove the connection to.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the second entity to remove the connection to.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to remove a power connection from. Only necessary to specify for entities that areEntity.dual_power_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to remove a power connection from. Only necessary to specify for entities that areEntity.dual_power_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.
- remove_power_connections() None¶
Remove all power connections in the Collection, including any power connections between power switches. Recurses through any subgroups, and removes power connections from them as well. Does nothing if there are no power connections in the Collection.
- remove_train(cars: list[EntityLike]) None¶
Removes all of the rolling stock specified as the list
cars, and also takes care of removing any locomotive associations in any correspondingScheduleobject(s). Does nothing ifcarsis empty.- Parameters:
- cars: list[EntityLike]¶
A
listof references toEntityLikes within the collection.
- Raises:
KeyError – If the specified entities within the list do not exist within the collection being accessed.
- rotate(angle: int)¶
Rotate the blueprint by
angle, if possible. Operates the same as pressing ‘r’ with a blueprint selected.angleis specified in terms of Direction enum, meaning that a rotation of 4 is 90 degrees clockwise.Because eight-way rotatable entities exist in a weird gray area, this function behaves like the feature in-game and only rotates on 90 degree intervals. Attempting to rotate the blueprint an odd amount raises an
RotationError.- Parameters:
- angle: int¶
The angle to rotate the blueprint by.
- Raises:
RotationError – If the rotation is attempted with an odd value.
- set_train_schedule(
- train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon],
- schedule: Schedule | None,
Sets the schedule of a particular locomotive, or an entire list of RollingStock. The list of rolling stock can include non-locomotive cars, they will just be skipped when setting schedules. The list of rolling stock can also include locomotives across multiple trains; in this case all connected train cars from every touched train will be given the new schedule. If
scheduleis set toNone, then any touched locomotive will have their schedule cleared instead of set.- Parameters:
- train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]¶
The single Locomotive, or a list of RollingStock.
- schedule: Schedule | None¶
The
Scheduleto give each connected train, orNoneto remove the schedule from each connected train.
- to_dict(
- version: tuple[int, ...] | None =
None, - exclude_none: bool =
True, - exclude_defaults: bool =
True, Export this object to a JSON dictionary, usually directly prior to encoding into the compressed blueprint string format.
- Parameters:
- version: tuple[int, ...] | None =
None¶ Which Factorio version format this entity should be exported with. The same Draftsman object can be converted to many version-specific output dictionaries, each of which may have different structures.
The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of
(1, 1, 96)will use the 1.0 converter, and a version of(2, 0, 32)will use the 2.0 converter.If no version is provided, it will default to current environment’s Factorio version, or to
draftsman.DEFAULT_FACTORIO_VERSIONif unable to read the current environment.- exclude_none: bool =
True¶ Whether or not
Noneproperties should be omitted from the output string. For certain properties this option has no effect, as they either must always be present or never be present ifNone.- exclude_defaults: bool =
True¶ Whether or not to exclude properties that are equivalent to their default values. Including these values in the generated output is redundant as Factorio will populate them automatically, but it is useful to disable for debug/illustation purposes.
- version: tuple[int, ...] | None =
- translate(x: int, y: int) None¶
Translates all entities and tiles in the blueprint by
xandy. RaisesRailAlignmentWarningif the parent class contains double-grid-aligned entities and the translation amount is an odd value on either x or y.
- validate(
- mode: ValidationMode =
ValidationMode.STRICT, Validates the called object against it’s known format.
- Example:
>>> import draftsman >>> from draftsman.constants import ValidationMode >>> from draftsman.entity import Container >>> from draftsman.error import DataFormatError >>> c = Container("wooden-chest") >>> with draftsman.validators.set_mode(ValidationMode.DISABLED): ... c.bar = "incorrect" >>> try: ... c.validate().reissue_all() ... except DataFormatError as e: ... print("wrong!") wrong!- Parameters:
- mode: ValidationMode =
ValidationMode.STRICT¶ How strict to be when valiating the object, corresponding to the number and type of errors and warnings returned.
- mode: ValidationMode =
- Returns:
A
ValidationResultobject, which contains all errors and warnings from the validation pass.