pyttd 1.2.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. pyttd-2.0.0/.gitignore +5 -0
  2. {pyttd-1.2.0 → pyttd-2.0.0}/LICENSE +2 -2
  3. pyttd-2.0.0/PKG-INFO +87 -0
  4. pyttd-2.0.0/README.md +67 -0
  5. pyttd-2.0.0/engine/README.md +16 -0
  6. pyttd-2.0.0/examples/bus_line.py +32 -0
  7. pyttd-2.0.0/examples/bus_route.py +147 -0
  8. pyttd-2.0.0/examples/join_server.py +24 -0
  9. pyttd-2.0.0/pyproject.toml +37 -0
  10. pyttd-2.0.0/src/pyttd/__init__.py +32 -0
  11. pyttd-2.0.0/src/pyttd/_engine.py +74 -0
  12. pyttd-2.0.0/src/pyttd/api.py +459 -0
  13. pyttd-2.0.0/src/pyttd/content.py +77 -0
  14. pyttd-2.0.0/src/pyttd/crossings.py +68 -0
  15. pyttd-2.0.0/src/pyttd/engines.py +173 -0
  16. pyttd-2.0.0/src/pyttd/game.py +219 -0
  17. pyttd-2.0.0/src/pyttd/observe.py +112 -0
  18. pyttd-2.0.0/src/pyttd/rails.py +189 -0
  19. pyttd-2.0.0/src/pyttd/record.py +97 -0
  20. pyttd-2.0.0/src/pyttd/roads.py +163 -0
  21. pyttd-2.0.0/src/pyttd/server.py +127 -0
  22. pyttd-2.0.0/tests/conftest.py +63 -0
  23. pyttd-2.0.0/tests/test_api.py +134 -0
  24. pyttd-2.0.0/tests/test_client.py +81 -0
  25. pyttd-2.0.0/tests/test_engines.py +64 -0
  26. pyttd-2.0.0/tests/test_game.py +67 -0
  27. pyttd-2.0.0/tests/test_observe.py +25 -0
  28. pyttd-2.0.0/tests/test_record.py +89 -0
  29. pyttd-1.2.0/.github/workflows/ci.yml +0 -55
  30. pyttd-1.2.0/.github/workflows/docs.yml +0 -41
  31. pyttd-1.2.0/.github/workflows/publish.yml +0 -33
  32. pyttd-1.2.0/MANIFEST.in +0 -22
  33. pyttd-1.2.0/PKG-INFO +0 -244
  34. pyttd-1.2.0/README.md +0 -204
  35. pyttd-1.2.0/examples/README.md +0 -31
  36. pyttd-1.2.0/examples/chat_bot.py +0 -150
  37. pyttd-1.2.0/examples/data_display.py +0 -113
  38. pyttd-1.2.0/examples/finance_bot.py +0 -236
  39. pyttd-1.2.0/examples/manager_bot.py +0 -354
  40. pyttd-1.2.0/examples/save_parser.py +0 -191
  41. pyttd-1.2.0/pyproject.toml +0 -97
  42. pyttd-1.2.0/pyttd/__init__.py +0 -63
  43. pyttd-1.2.0/pyttd/client.py +0 -1155
  44. pyttd-1.2.0/pyttd/game/__init__.py +0 -16
  45. pyttd-1.2.0/pyttd/game/commands.py +0 -415
  46. pyttd-1.2.0/pyttd/game/game_state.py +0 -344
  47. pyttd-1.2.0/pyttd/network/__init__.py +0 -5
  48. pyttd-1.2.0/pyttd/network/protocol.py +0 -330
  49. pyttd-1.2.0/pyttd/py.typed +0 -0
  50. pyttd-1.2.0/pyttd/saveload/__init__.py +0 -101
  51. pyttd-1.2.0/pyttd/saveload/company_names.py +0 -300
  52. pyttd-1.2.0/pyttd/saveload/exporter.py +0 -338
  53. pyttd-1.2.0/pyttd/saveload/formatter.py +0 -384
  54. pyttd-1.2.0/pyttd/saveload/models.py +0 -743
  55. pyttd-1.2.0/pyttd/saveload/parser.py +0 -901
  56. pyttd-1.2.0/pyttd/saveload/reader.py +0 -225
  57. pyttd-1.2.0/pyttd.egg-info/PKG-INFO +0 -244
  58. pyttd-1.2.0/pyttd.egg-info/SOURCES.txt +0 -36
  59. pyttd-1.2.0/pyttd.egg-info/dependency_links.txt +0 -1
  60. pyttd-1.2.0/pyttd.egg-info/entry_points.txt +0 -2
  61. pyttd-1.2.0/pyttd.egg-info/not-zip-safe +0 -1
  62. pyttd-1.2.0/pyttd.egg-info/requires.txt +0 -10
  63. pyttd-1.2.0/pyttd.egg-info/top_level.txt +0 -1
  64. pyttd-1.2.0/setup.cfg +0 -4
  65. pyttd-1.2.0/setup.py +0 -102
pyttd-2.0.0/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ /.venv/
4
+ /dist/
5
+ .pytest_cache/
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 PyTTD Contributors
3
+ Copyright (c) 2026 pyttd contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
pyttd-2.0.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyttd
3
+ Version: 2.0.0
4
+ Summary: Play OpenTTD from Python: a real OpenTTD engine, driven through the AI Script API
5
+ Project-URL: Source, https://github.com/mssc89/pyttd
6
+ Project-URL: AI API, https://docs.openttd.org/ai-api/
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Games/Entertainment :: Simulation
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: numpy>=1.26
17
+ Requires-Dist: packaging>=23
18
+ Requires-Dist: pyttd-engine>=15.3
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pyttd
22
+
23
+ Finally, a way to play [OpenTTD](https://www.openttd.org) from Python. A real OpenTTD engine runs inside your Python process, and your code controls companies through OpenTTD own [AI Script API](https://docs.openttd.org/ai-api/) - the same functions, rules, costs and command rate as any Squirrel AI. Test host-paced local games, or join multiplayer servers as an ordinary player.
24
+
25
+ ```
26
+ pip install pyttd
27
+ ```
28
+
29
+ Linux (x86_64, aarch64), macOS (Apple silicon, Intel) and Windows (x64); Python 3.12+.
30
+
31
+ ```python
32
+ import pyttd
33
+
34
+ game = pyttd.Game(seed=42) # a local game, advancing only when you step it
35
+ agent = game.create_agent() # a new company, controlled from Python
36
+ api = agent.api # the AI Script API, acting for this company
37
+
38
+ town = max(api.AITownList(), key=api.AITown.GetPopulation)
39
+ print(api.AITown.GetName(town), api.AITown.GetPopulation(town))
40
+
41
+ api.AIRoad.SetCurrentRoadType(api.AIRoad.ROADTYPE_ROAD)
42
+ with api.AITestMode(), api.AIAccounting() as cost:
43
+ api.AIRoad.BuildRoad(a, b) # estimate only: cost.GetCosts()
44
+ api.AIRoad.BuildRoad(a, b) # build; waits for the command slot like an AI
45
+ game.step(30 * pyttd.TICKS_PER_DAY) # let a month pass
46
+ ```
47
+
48
+ ## How it works
49
+
50
+ ![One command, from Python through OpenTTD to a multiplayer server and back](assets/command-flow.svg)
51
+
52
+ The engine is OpenTTD compiled as a Python extension module. Calls go through its own Script API in the agent's script context, so a command behaves exactly as it would for a Squirrel AI. For multiplayer servers, if a command is issued too early, it waits (or raises `BlockingIOError` with `create_agent(auto_wait=False)`).
53
+
54
+ ## Multiplayer
55
+
56
+ ```python
57
+ game = pyttd.Game.join("example.org:3979", name="bot") # create a company
58
+ me = game.create_agent()
59
+ ```
60
+
61
+ The client is an ordinary player - no admin port access, or server-side AI slot are needed, and the game runs at the server's pace (`step()` waits). `pyttd.server.query(address)` reads a server's name, version, map and player counts without joining.
62
+
63
+ ## OpenTTD versions
64
+
65
+ A server only accepts clients of its exact OpenTTD version, and pyttd handles that for you. `pip install pyttd` brings the engine of the newest OpenTTD release. `Game.join` asks the server for its version first and, if it differs, downloads the matching engine once into pyttd's data directory. To run a given version locally, pass `Game(version="15.3")`, call `pyttd.engines.use("15.3")`, or set `$PYTTD_ENGINE`. One process runs one engine - you can start several processes for several games or versions.
66
+
67
+ ## More
68
+
69
+ - `pyttd.observe`: the map as numpy arrays, and tables of towns, industries, vehicles, stations and finances.
70
+ - `pyttd.roads`, `pyttd.rails`: A\* pathfinders with bridges and tunnels, and builders for their paths.
71
+ - `pyttd.record`: every command scripts execute, with decoded arguments and results; `Agent.do_command` issues them again.
72
+ - `pyttd.content`: download Squirrel AIs from BaNaNaS and start them as opponents.
73
+ - `Game`: `new_game`, `load`, `save`, `console`, and `observe_company` (a read-only view of any company).
74
+
75
+ See [`examples/`](examples).
76
+
77
+ ## Building
78
+
79
+ ```
80
+ python engine/tools/build.py [--version 15.3] [--server] # wheel -> engine/dist/
81
+ ```
82
+
83
+ Supported OpenTTD versions are listed in `engine/versions.toml`.
84
+
85
+ ## Licence
86
+
87
+ pyttd is MIT licensed. The engine, `pyttd-engine`, contains OpenTTD and OpenGFX and follows them with GPL-2.0 licensing.
pyttd-2.0.0/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # pyttd
2
+
3
+ Finally, a way to play [OpenTTD](https://www.openttd.org) from Python. A real OpenTTD engine runs inside your Python process, and your code controls companies through OpenTTD own [AI Script API](https://docs.openttd.org/ai-api/) - the same functions, rules, costs and command rate as any Squirrel AI. Test host-paced local games, or join multiplayer servers as an ordinary player.
4
+
5
+ ```
6
+ pip install pyttd
7
+ ```
8
+
9
+ Linux (x86_64, aarch64), macOS (Apple silicon, Intel) and Windows (x64); Python 3.12+.
10
+
11
+ ```python
12
+ import pyttd
13
+
14
+ game = pyttd.Game(seed=42) # a local game, advancing only when you step it
15
+ agent = game.create_agent() # a new company, controlled from Python
16
+ api = agent.api # the AI Script API, acting for this company
17
+
18
+ town = max(api.AITownList(), key=api.AITown.GetPopulation)
19
+ print(api.AITown.GetName(town), api.AITown.GetPopulation(town))
20
+
21
+ api.AIRoad.SetCurrentRoadType(api.AIRoad.ROADTYPE_ROAD)
22
+ with api.AITestMode(), api.AIAccounting() as cost:
23
+ api.AIRoad.BuildRoad(a, b) # estimate only: cost.GetCosts()
24
+ api.AIRoad.BuildRoad(a, b) # build; waits for the command slot like an AI
25
+ game.step(30 * pyttd.TICKS_PER_DAY) # let a month pass
26
+ ```
27
+
28
+ ## How it works
29
+
30
+ ![One command, from Python through OpenTTD to a multiplayer server and back](assets/command-flow.svg)
31
+
32
+ The engine is OpenTTD compiled as a Python extension module. Calls go through its own Script API in the agent's script context, so a command behaves exactly as it would for a Squirrel AI. For multiplayer servers, if a command is issued too early, it waits (or raises `BlockingIOError` with `create_agent(auto_wait=False)`).
33
+
34
+ ## Multiplayer
35
+
36
+ ```python
37
+ game = pyttd.Game.join("example.org:3979", name="bot") # create a company
38
+ me = game.create_agent()
39
+ ```
40
+
41
+ The client is an ordinary player - no admin port access, or server-side AI slot are needed, and the game runs at the server's pace (`step()` waits). `pyttd.server.query(address)` reads a server's name, version, map and player counts without joining.
42
+
43
+ ## OpenTTD versions
44
+
45
+ A server only accepts clients of its exact OpenTTD version, and pyttd handles that for you. `pip install pyttd` brings the engine of the newest OpenTTD release. `Game.join` asks the server for its version first and, if it differs, downloads the matching engine once into pyttd's data directory. To run a given version locally, pass `Game(version="15.3")`, call `pyttd.engines.use("15.3")`, or set `$PYTTD_ENGINE`. One process runs one engine - you can start several processes for several games or versions.
46
+
47
+ ## More
48
+
49
+ - `pyttd.observe`: the map as numpy arrays, and tables of towns, industries, vehicles, stations and finances.
50
+ - `pyttd.roads`, `pyttd.rails`: A\* pathfinders with bridges and tunnels, and builders for their paths.
51
+ - `pyttd.record`: every command scripts execute, with decoded arguments and results; `Agent.do_command` issues them again.
52
+ - `pyttd.content`: download Squirrel AIs from BaNaNaS and start them as opponents.
53
+ - `Game`: `new_game`, `load`, `save`, `console`, and `observe_company` (a read-only view of any company).
54
+
55
+ See [`examples/`](examples).
56
+
57
+ ## Building
58
+
59
+ ```
60
+ python engine/tools/build.py [--version 15.3] [--server] # wheel -> engine/dist/
61
+ ```
62
+
63
+ Supported OpenTTD versions are listed in `engine/versions.toml`.
64
+
65
+ ## Licence
66
+
67
+ pyttd is MIT licensed. The engine, `pyttd-engine`, contains OpenTTD and OpenGFX and follows them with GPL-2.0 licensing.
@@ -0,0 +1,16 @@
1
+ # pyttd-engine
2
+
3
+ [OpenTTD](https://www.openttd.org) built as a Python extension module, for [pyttd](https://pypi.org/project/pyttd/). It contains the engine, the OpenGFX base set, the English language file, OpenTTD's AI/GS API compatibility scripts and the PyAgent stub AI. Install `pyttd`, which depends on this package, rather than using it directly.
4
+
5
+ The version follows OpenTTD's: `15.3.x` are builds of OpenTTD 15.3. Joining a multiplayer server needs the server's exact OpenTTD version, so pin it with `pip install "pyttd-engine==15.3.*"`.
6
+
7
+ ## License
8
+
9
+ GPL-2.0-only, as OpenTTD. The source distribution contains the complete OpenTTD source with our patches (`patches/`) and the bridge (`bridge/`). OpenGFX is GPL-2.0 as well.
10
+
11
+ ## Building from a checkout
12
+
13
+ ```
14
+ python tools/prepare.py # fetch OpenTTD + OpenGFX, verify, patch -> openttd/
15
+ pip wheel . -w dist/ # or: pip install .
16
+ ```
@@ -0,0 +1,32 @@
1
+ """connect the biggest town to a neighbour by bus and watch the route for a year"""
2
+
3
+ import pyttd
4
+ from pyttd import observe
5
+
6
+ from bus_route import build_bus_route
7
+
8
+ game = pyttd.Game(seed=42)
9
+ agent = game.create_agent()
10
+ api = agent.api
11
+
12
+ towns = sorted(api.AITownList(), key=api.AITown.GetPopulation, reverse=True)
13
+ home = towns[0]
14
+
15
+
16
+ def distance(t: int) -> int:
17
+ return api.AIMap.DistanceManhattan(api.AITown.GetLocation(home), api.AITown.GetLocation(t))
18
+
19
+
20
+ other = min((t for t in towns[1:] if distance(t) >= 20), key=distance)
21
+ print(f"connecting {api.AITown.GetName(home)} and {api.AITown.GetName(other)} ({distance(other)} tiles)")
22
+
23
+ result = build_bus_route(agent, home, other, buses=3)
24
+ if not result.ok:
25
+ raise SystemExit(f"failed: {result.error}")
26
+ print(f"built for {result.cost:,}; buses {result.route.vehicles}")
27
+
28
+ for month in range(12):
29
+ game.step(30 * pyttd.TICKS_PER_DAY)
30
+ f = observe.finances(agent)
31
+ v = observe.vehicles(agent)
32
+ print(f"{game.date}: balance {f['balance']:>10,.0f} bus profit this year {v.col('profit_this_year').sum():>8,.0f}")
@@ -0,0 +1,147 @@
1
+ """a bus route between two towns, built from Script API calls and pyttd.roads
2
+
3
+ a small worked example of composing the API, as a Squirrel AI would: find stop sites, path-find and build the road, build a depot, buy buses and give them orders. The other examples and the tests import it (`from bus_route import build_bus_route`)
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+ from pyttd import Agent, roads
11
+
12
+
13
+ @dataclass
14
+ class Route:
15
+ town_a: int
16
+ town_b: int
17
+ station_a: int # station tiles
18
+ station_b: int
19
+ depot: int
20
+ vehicles: list[int] = field(default_factory=list)
21
+
22
+
23
+ @dataclass
24
+ class Result:
25
+ ok: bool
26
+ cost: int = 0
27
+ error: str = ""
28
+ route: Route | None = None
29
+
30
+
31
+ def _area(agent: Agent, center: int, radius: int):
32
+ """tiles around center, nearest first"""
33
+ Map = agent.api.AIMap
34
+ cx, cy = Map.GetTileX(center), Map.GetTileY(center)
35
+ tiles = []
36
+ for dy in range(-radius, radius + 1):
37
+ for dx in range(-radius, radius + 1):
38
+ tile = Map.GetTileIndex(cx + dx, cy + dy)
39
+ if Map.IsValidTile(tile):
40
+ tiles.append((abs(dx) + abs(dy), tile))
41
+ return [t for _, t in sorted(tiles)]
42
+
43
+
44
+ def build_town_bus_stop(agent: Agent, town: int, radius: int = 6) -> int | None:
45
+ """a drive-through bus stop on a straight town road near the centre; returns its tile"""
46
+ api = agent.api
47
+ Road, Map = api.AIRoad, api.AIMap
48
+ row = Map.GetTileIndex(0, 1)
49
+ for tile in _area(agent, api.AITown.GetLocation(town), radius):
50
+ if not Road.IsRoadTile(tile) or Road.IsDriveThroughRoadStationTile(tile):
51
+ continue
52
+ for axis in (1, row):
53
+ if not (Road.AreRoadTilesConnected(tile, tile + axis) and Road.AreRoadTilesConnected(tile, tile - axis)):
54
+ continue
55
+ with api.AITestMode():
56
+ if not Road.BuildDriveThroughRoadStation(tile, tile + axis, Road.ROADVEHTYPE_BUS, api.AIStation.STATION_NEW):
57
+ continue
58
+ if Road.BuildDriveThroughRoadStation(tile, tile + axis, Road.ROADVEHTYPE_BUS, api.AIStation.STATION_NEW):
59
+ return tile
60
+ return None
61
+
62
+
63
+ def build_depot_near(agent: Agent, tile: int, radius: int = 6) -> int | None:
64
+ """a road depot on a free tile next to connected road near `tile`; returns the depot tile"""
65
+ api = agent.api
66
+ Road, Tile, Map = api.AIRoad, api.AITile, api.AIMap
67
+ row = Map.GetTileIndex(0, 1)
68
+ for spot in _area(agent, tile, radius):
69
+ if not Tile.IsBuildable(spot):
70
+ continue
71
+ for front in (spot + 1, spot - 1, spot + row, spot - row):
72
+ if not Road.IsRoadTile(front) or Road.IsDriveThroughRoadStationTile(front):
73
+ continue
74
+ with api.AITestMode():
75
+ if not (Road.BuildRoadDepot(spot, front) and Road.BuildRoad(spot, front)):
76
+ continue
77
+ if Road.BuildRoadDepot(spot, front):
78
+ if Road.BuildRoad(spot, front) or api.AIError.GetLastError() == api.AIError.ERR_ALREADY_BUILT:
79
+ return spot
80
+ api.AITile.DemolishTile(spot)
81
+ return None
82
+
83
+
84
+ def best_bus(agent: Agent) -> int | None:
85
+ """the buildable road vehicle for passengers with the best capacity x speed"""
86
+ api = agent.api
87
+ Engine = api.AIEngine
88
+ buses = [e for e in api.AIEngineList(api.AIVehicle.VT_ROAD) if Engine.IsBuildable(e) and Engine.GetRoadType(e) == api.AIRoad.ROADTYPE_ROAD and api.AICargo.HasCargoClass(Engine.GetCargoType(e), api.AICargo.CC_PASSENGERS)]
89
+ return max(buses, key=lambda e: Engine.GetCapacity(e) * Engine.GetMaxSpeed(e), default=None)
90
+
91
+
92
+ def add_buses(agent: Agent, route: Route, count: int) -> int:
93
+ """buy `count` more buses for a route, sharing the orders of its first bus; returns how many were added"""
94
+ api = agent.api
95
+ Vehicle, Order = api.AIVehicle, api.AIOrder
96
+ engine = best_bus(agent)
97
+ if engine is None:
98
+ return 0
99
+ added = 0
100
+ for _ in range(count):
101
+ v = Vehicle.BuildVehicle(route.depot, engine)
102
+ if not Vehicle.IsValidVehicle(v):
103
+ break
104
+ if route.vehicles:
105
+ ok = Order.ShareOrders(v, route.vehicles[0])
106
+ else:
107
+ ok = Order.AppendOrder(v, route.station_a, Order.OF_NON_STOP_INTERMEDIATE) and Order.AppendOrder(v, route.station_b, Order.OF_NON_STOP_INTERMEDIATE)
108
+ if not ok:
109
+ Vehicle.SellVehicle(v)
110
+ break
111
+ Vehicle.StartStopVehicle(v)
112
+ route.vehicles.append(v)
113
+ added += 1
114
+ return added
115
+
116
+
117
+ def build_bus_route(agent: Agent, town_a: int, town_b: int, buses: int = 2) -> Result:
118
+ """connect two towns by road with a bus stop in each, a depot and `buses` buses"""
119
+ api = agent.api
120
+ api.AIRoad.SetCurrentRoadType(api.AIRoad.ROADTYPE_ROAD)
121
+ with api.AIAccounting() as acc:
122
+
123
+ def fail(error: str) -> Result:
124
+ return Result(ok=False, cost=acc.GetCosts(), error=error)
125
+
126
+ a = build_town_bus_stop(agent, town_a)
127
+ if a is None:
128
+ return fail(f"no bus stop site in {api.AITown.GetName(town_a)}")
129
+ b = build_town_bus_stop(agent, town_b)
130
+ if b is None:
131
+ return fail(f"no bus stop site in {api.AITown.GetName(town_b)}")
132
+
133
+ path = roads.find_path(agent, a, b)
134
+ if path is None:
135
+ return fail("no road path between the towns")
136
+ built = roads.build_path(agent, path)
137
+ if not built.ok:
138
+ return fail(f"building road failed: {built.error}")
139
+
140
+ depot = build_depot_near(agent, a)
141
+ if depot is None:
142
+ return fail("no depot site")
143
+
144
+ route = Route(town_a, town_b, a, b, depot)
145
+ if add_buses(agent, route, buses) == 0:
146
+ return fail(f"buying buses failed: {api.AIError.GetLastErrorString()}")
147
+ return Result(ok=True, cost=acc.GetCosts(), route=route)
@@ -0,0 +1,24 @@
1
+ """join a multiplayer server as an ordinary client, found a company and put up a sign
2
+
3
+ pyttd picks the engine matching the server's OpenTTD version, downloading it if needed. For example, against a dedicated server of an official OpenTTD build: openttd -D 127.0.0.1:3979 -g Usage: python examples/join_server.py [host:port]
4
+ """
5
+
6
+ import sys
7
+
8
+ import pyttd
9
+
10
+ server = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1:3979"
11
+ info = pyttd.server.query(server)
12
+ print(f"{info.name!r}: OpenTTD {info.revision}, {info.clients}/{info.clients_max} clients, map {info.map_size}")
13
+ game = pyttd.Game.join(server, name="pyttd-bot")
14
+ agent = game.create_agent()
15
+ api = agent.api
16
+ print(f"playing company {agent.company} on {server}, date {game.date}")
17
+
18
+ api.AICompany.SetName("Python Transport")
19
+ town = max(api.AITownList(), key=api.AITown.GetPopulation)
20
+ sign = api.AISign.BuildSign(api.AITown.GetLocation(town), "hello from Python")
21
+ print(f"sign {api.AISign.GetName(sign)!r} in {api.AITown.GetName(town)}")
22
+ game.step(10 * pyttd.TICKS_PER_DAY)
23
+ api.AISign.RemoveSign(sign)
24
+ game.quit()
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pyttd"
7
+ version = "2.0.0"
8
+ description = "Play OpenTTD from Python: a real OpenTTD engine, driven through the AI Script API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["pyttd-engine>=15.3", "numpy>=1.26", "packaging>=23"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Games/Entertainment :: Simulation",
17
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Operating System :: MacOS",
20
+ "Operating System :: Microsoft :: Windows",
21
+ ]
22
+
23
+ [project.urls]
24
+ Source = "https://github.com/mssc89/pyttd"
25
+ "AI API" = "https://docs.openttd.org/ai-api/"
26
+
27
+ [dependency-groups]
28
+ dev = ["pytest>=8"]
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/pyttd"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["src/pyttd", "tests", "examples", "README.md", "LICENSE"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
@@ -0,0 +1,32 @@
1
+ """pyttd: play OpenTTD from Python through the AI Script API
2
+
3
+ game = pyttd.Game(seed=42) # the process's OpenTTD engine
4
+ agent = game.create_agent() # a company controlled from Python
5
+ api = agent.api # the AI Script API, acting for this agent
6
+
7
+ submodules: api, engines, server, observe, record, content, roads, rails, crossings
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from importlib.metadata import PackageNotFoundError, version as _version
13
+
14
+ from . import engines, server
15
+ from ._engine import home
16
+ from .game import TICKS_PER_DAY, Agent, Game
17
+
18
+ try:
19
+ __version__ = _version("pyttd")
20
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
21
+ __version__ = "0+unknown"
22
+
23
+ __all__ = ["OPENTTD_VERSION", "TICKS_PER_DAY", "Agent", "Game", "engines", "home", "server"]
24
+
25
+
26
+ def __getattr__(name: str):
27
+ if name == "OPENTTD_VERSION":
28
+ # the OpenTTD version this process runs; reading it loads the engine
29
+ from ._engine import load
30
+
31
+ return load().OPENTTD_VERSION
32
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,74 @@
1
+ """the OpenTTD engine this process runs, and pyttd's private data directory
2
+
3
+ the engine (the `_openttd` extension module of a pyttd-engine build) is imported lazily, on first use, so that the OpenTTD version can still be chosen before then: by `pyttd.engines.use()`, by `Game(version=...)`, by `Game.join()` (which asks the server), or by $PYTTD_ENGINE. Without a choice, the pip-installed pyttd-engine is used
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+ from types import ModuleType
13
+
14
+ __all__ = ["home", "load", "loaded", "_openttd"]
15
+
16
+
17
+ def home() -> Path:
18
+ """pyttd's own OpenTTD personal directory: config, saves, downloaded content and engines
19
+
20
+ $PYTTD_HOME if set, otherwise the platform's user data directory. The user's own OpenTTD config is never read or written
21
+ """
22
+ if env := os.environ.get("PYTTD_HOME"):
23
+ return Path(env)
24
+ if sys.platform == "win32":
25
+ base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
26
+ elif sys.platform == "darwin":
27
+ base = Path.home() / "Library" / "Application Support"
28
+ else:
29
+ base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
30
+ return base / "pyttd"
31
+
32
+
33
+ _package: ModuleType | None = None # the imported pyttd_engine package
34
+
35
+
36
+ def loaded() -> ModuleType | None:
37
+ """the imported pyttd_engine package, or None while no engine is loaded"""
38
+ return _package
39
+
40
+
41
+ def load(site: Path | None = None) -> ModuleType:
42
+ """import the engine; `site` is a directory holding a pyttd_engine package (default: the one $PYTTD_ENGINE selects, else the pip-installed one). Returns the pyttd_engine package"""
43
+ global _package
44
+ if _package is not None:
45
+ if site is not None and Path(_package.__file__).resolve().parent.parent != site.resolve():
46
+ raise RuntimeError(f"OpenTTD {_package.OPENTTD_VERSION} is already loaded; one engine per process")
47
+ return _package
48
+ if site is None and (wanted := os.environ.get("PYTTD_ENGINE")):
49
+ from .engines import locate
50
+
51
+ site = locate(wanted, fetch=True)
52
+ if site is not None:
53
+ sys.path.insert(0, str(site))
54
+ try:
55
+ _package = importlib.import_module("pyttd_engine")
56
+ except ImportError as e: # pragma: no cover - depends on the installation
57
+ raise ImportError("pyttd needs an OpenTTD engine: pip install pyttd-engine") from e
58
+ finally:
59
+ if site is not None:
60
+ sys.path.remove(str(site))
61
+ return _package
62
+
63
+
64
+ class _LazyEngine:
65
+ """stands for the `_openttd` extension module, which is imported on first attribute access"""
66
+
67
+ def __getattr__(self, name: str):
68
+ return getattr(load()._openttd, name)
69
+
70
+ def __repr__(self) -> str:
71
+ return "<OpenTTD engine (not loaded yet)>" if _package is None else repr(_package._openttd)
72
+
73
+
74
+ _openttd = _LazyEngine()