Skip to content

Commit e80527c

Browse files
committed
more python code
1 parent 722108d commit e80527c

File tree

14 files changed

+371
-129
lines changed

14 files changed

+371
-129
lines changed

python/bot/bot.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,47 @@
11
from uwapi import *
22

33
class Bot:
4-
isConfigured = False
5-
workStep = 0 # save some cpu cycles by splitting work over multiple steps
4+
is_configured: bool = False
5+
work_step: int = 0 # save some cpu cycles by splitting work over multiple steps
66

7-
def AttackNearestEnemies(self):
7+
def __init__(self):
8+
uw_events.on_update(self.on_update)
9+
10+
def attack_nearest_enemies(self):
811
pass # todo
912

10-
def AssignRandomRecipes(self):
13+
def assign_random_recipes(self):
1114
pass # todo
1215

13-
def Configure(self):
14-
if self.isConfigured:
16+
def configure(self):
17+
if self.is_configured:
1518
return
16-
self.isConfigured = True
19+
self.is_configured = True
1720

18-
game.SetPlayerName("bot-cs")
19-
game.PlayerJoinForce(0) # create new force
20-
game.SetForceColor(1, 0, 0)
21+
uw_game.set_player_name("bot-cs")
22+
uw_game.player_join_force(0) # create new force
23+
uw_game.set_force_color(1, 0, 0)
2124
# todo choose race
2225

23-
def Updating(self, stepping: bool):
24-
if game.GameState() == GameState.Session:
25-
self.Configure()
26+
def on_update(self, tick: int, stepping: bool):
27+
if uw_game.game_state() == GameState.Session:
28+
self.configure()
2629
return
2730

2831
if not stepping:
2932
return
3033

31-
self.workStep += 1
32-
match self.workStep % 10: # save some cpu cycles by splitting work over multiple steps
34+
self.work_step += 1
35+
match self.work_step % 10: # save some cpu cycles by splitting work over multiple steps
3336
case 1:
34-
self.AttackNearestEnemies()
37+
self.attack_nearest_enemies()
3538
case 5:
36-
self.AssignRandomRecipes()
37-
38-
def Run(self):
39-
game.LogInfo("bot-py start")
40-
if not game.TryReconnect():
41-
game.SetConnectStartGui(True)
42-
if not game.ConnectEnvironment():
43-
game.ConnectNewServer()
44-
game.LogInfo("bot-py done")
39+
self.assign_random_recipes()
40+
41+
def run(self):
42+
uw_game.log_info("bot-py start")
43+
if not uw_game.try_reconnect():
44+
uw_game.set_connect_start_gui(True)
45+
if not uw_game.connect_environment():
46+
uw_game.connect_new_server()
47+
uw_game.log_info("bot-py done")

python/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33

44
if __name__ == "__main__":
55
with UwapiLibrary():
6-
Bot().Run()
6+
Bot().run()

python/uwapi/__init__.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
# THIS FILE IS GENERATED BY SCRIPT
33
# DO NOT MODIFY
44

5-
from .admin import admin
6-
from .commands import commands
5+
from .interop import *
6+
from .admin import uw_admin
7+
from .commands import uw_commands
78
from .entity import Entity
8-
from .game import game
9+
from .events import uw_events
10+
from .game import uw_game
911
from .library import UwapiLibrary
10-
from .map import map_
11-
from .prototypes import prototypes
12-
from .world import world
13-
from .interop import *
12+
from .map import uw_map
13+
from .prototypes import uw_prototypes
14+
from .world import uw_world
1415

15-
__all__ = ["admin","commands","Entity","game","UwapiLibrary","map_","prototypes","world","Severity","LogCallback","ConnectionState","MyPlayer","AssistConfig","PerformanceStatistics","OrderType","OrderPriority","Order","Orders","Ids","Priority","Ping","PathState","ForeignPolicy","ChatTarget","ProtoComponent","OwnerComponent","ControllerComponent","PositionComponent","UnitState","UnitComponent","LifeComponent","ManaComponent","MoveComponent","AimComponent","RecipeComponent","RecipeStatisticsComponent","LogisticsTimestampComponent","PriorityComponent","AmountComponent","AttachmentComponent","PingComponent","PlayerState","PlayerConnectionClass","PlayerComponent","PlayerAiConfigComponent","ForceState","ForceComponent","ForceDetailsComponent","ForeignPolicyComponent","DiplomacyProposalComponent","GameState","ShootingUnit","ShootingData","ShootingArray","ExplosionData","ExplosionsArray","TaskType","MapState","MapInfo","MapStartingPosition","MapStartingPositionsArray","Tile","Cluster","ClustersDistancesQuery","ClustersDistancesResult","PrototypeType","MyForceStatistics","UnitUpgrades","Overview","OverviewExtract","UnitPathfindingQuery","UnitPathfindingResult"]
16+
__all__ = ["uw_admin","uw_commands","Entity","uw_events","uw_game","UwapiLibrary","uw_map","uw_prototypes","uw_world","Severity","LogCallback","ConnectionState","MyPlayer","AssistConfig","PerformanceStatistics","OrderType","OrderPriority","Order","Orders","Ids","Priority","Ping","PathState","ForeignPolicy","ChatTarget","ProtoComponent","OwnerComponent","ControllerComponent","PositionComponent","UnitState","UnitComponent","LifeComponent","ManaComponent","MoveComponent","AimComponent","RecipeComponent","RecipeStatisticsComponent","LogisticsTimestampComponent","PriorityComponent","AmountComponent","AttachmentComponent","PingComponent","PlayerState","PlayerConnectionClass","PlayerComponent","PlayerAiConfigComponent","ForceState","ForceComponent","ForceDetailsComponent","ForeignPolicyComponent","DiplomacyProposalComponent","GameState","ShootingUnit","ShootingData","ShootingArray","ExplosionData","ExplosionsArray","TaskType","MapState","MapInfo","MapStartingPosition","MapStartingPositionsArray","Tile","Cluster","ClustersDistancesQuery","ClustersDistancesResult","PrototypeType","MyForceStatistics","UnitUpgrades","Overview","OverviewExtract","UnitPathfindingQuery","UnitPathfindingResult"]

python/uwapi/admin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ def __new__(cls):
88
cls._instance = super().__new__(cls)
99
return cls._instance
1010

11-
admin = Admin()
11+
uw_admin = Admin()

python/uwapi/commands.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ def __new__(cls):
88
cls._instance = super().__new__(cls)
99
return cls._instance
1010

11-
commands = Commands()
11+
uw_commands = Commands()

python/uwapi/entity.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,30 @@
1+
from dataclasses import dataclass
2+
from typing import Optional
13
from .interop import *
24

5+
@dataclass
36
class Entity:
4-
def __init__(self):
5-
pass
7+
id: int
8+
9+
Proto: Optional[UwProtoComponent] = None
10+
Owner: Optional[UwOwnerComponent] = None
11+
Controller: Optional[UwControllerComponent] = None
12+
Position: Optional[UwPositionComponent] = None
13+
Unit: Optional[UwUnitComponent] = None
14+
Life: Optional[UwLifeComponent] = None
15+
Mana: Optional[UwManaComponent] = None
16+
Move: Optional[UwMoveComponent] = None
17+
Aim: Optional[UwAimComponent] = None
18+
Recipe: Optional[UwRecipeComponent] = None
19+
RecipeStatistics: Optional[UwRecipeStatisticsComponent] = None
20+
LogisticsTimestamp: Optional[UwLogisticsTimestampComponent] = None
21+
Priority: Optional[UwPriorityComponent] = None
22+
Amount: Optional[UwAmountComponent] = None
23+
Attachment: Optional[UwAttachmentComponent] = None
24+
Ping: Optional[UwPingComponent] = None
25+
Player: Optional[UwPlayerComponent] = None
26+
PlayerAiConfig: Optional[UwPlayerAiConfigComponent] = None
27+
Force: Optional[UwForceComponent] = None
28+
ForceDetails: Optional[UwForceDetailsComponent] = None
29+
ForeignPolicy: Optional[UwForeignPolicyComponent] = None
30+
DiplomacyProposal: Optional[UwDiplomacyProposalComponent] = None
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
2+
# THIS FILE IS GENERATED BY SCRIPT
3+
# DO NOT MODIFY
4+
5+
from .interop import *
6+
from .entity import Entity
7+
8+
def entity_update_components(e: Entity):
9+
ptr = uw_interop.uwEntityPointer(e.id)
10+
11+
c_Proto = uw_interop.uwFetchProtoComponent(ptr)
12+
if c_Proto[0]:
13+
e.Proto = c_Proto[1]
14+
else:
15+
e.Proto = None
16+
17+
c_Owner = uw_interop.uwFetchOwnerComponent(ptr)
18+
if c_Owner[0]:
19+
e.Owner = c_Owner[1]
20+
else:
21+
e.Owner = None
22+
23+
c_Controller = uw_interop.uwFetchControllerComponent(ptr)
24+
if c_Controller[0]:
25+
e.Controller = c_Controller[1]
26+
else:
27+
e.Controller = None
28+
29+
c_Position = uw_interop.uwFetchPositionComponent(ptr)
30+
if c_Position[0]:
31+
e.Position = c_Position[1]
32+
else:
33+
e.Position = None
34+
35+
c_Unit = uw_interop.uwFetchUnitComponent(ptr)
36+
if c_Unit[0]:
37+
e.Unit = c_Unit[1]
38+
else:
39+
e.Unit = None
40+
41+
c_Life = uw_interop.uwFetchLifeComponent(ptr)
42+
if c_Life[0]:
43+
e.Life = c_Life[1]
44+
else:
45+
e.Life = None
46+
47+
c_Mana = uw_interop.uwFetchManaComponent(ptr)
48+
if c_Mana[0]:
49+
e.Mana = c_Mana[1]
50+
else:
51+
e.Mana = None
52+
53+
c_Move = uw_interop.uwFetchMoveComponent(ptr)
54+
if c_Move[0]:
55+
e.Move = c_Move[1]
56+
else:
57+
e.Move = None
58+
59+
c_Aim = uw_interop.uwFetchAimComponent(ptr)
60+
if c_Aim[0]:
61+
e.Aim = c_Aim[1]
62+
else:
63+
e.Aim = None
64+
65+
c_Recipe = uw_interop.uwFetchRecipeComponent(ptr)
66+
if c_Recipe[0]:
67+
e.Recipe = c_Recipe[1]
68+
else:
69+
e.Recipe = None
70+
71+
c_RecipeStatistics = uw_interop.uwFetchRecipeStatisticsComponent(ptr)
72+
if c_RecipeStatistics[0]:
73+
e.RecipeStatistics = c_RecipeStatistics[1]
74+
else:
75+
e.RecipeStatistics = None
76+
77+
c_LogisticsTimestamp = uw_interop.uwFetchLogisticsTimestampComponent(ptr)
78+
if c_LogisticsTimestamp[0]:
79+
e.LogisticsTimestamp = c_LogisticsTimestamp[1]
80+
else:
81+
e.LogisticsTimestamp = None
82+
83+
c_Priority = uw_interop.uwFetchPriorityComponent(ptr)
84+
if c_Priority[0]:
85+
e.Priority = c_Priority[1]
86+
else:
87+
e.Priority = None
88+
89+
c_Amount = uw_interop.uwFetchAmountComponent(ptr)
90+
if c_Amount[0]:
91+
e.Amount = c_Amount[1]
92+
else:
93+
e.Amount = None
94+
95+
c_Attachment = uw_interop.uwFetchAttachmentComponent(ptr)
96+
if c_Attachment[0]:
97+
e.Attachment = c_Attachment[1]
98+
else:
99+
e.Attachment = None
100+
101+
c_Ping = uw_interop.uwFetchPingComponent(ptr)
102+
if c_Ping[0]:
103+
e.Ping = c_Ping[1]
104+
else:
105+
e.Ping = None
106+
107+
c_Player = uw_interop.uwFetchPlayerComponent(ptr)
108+
if c_Player[0]:
109+
e.Player = c_Player[1]
110+
else:
111+
e.Player = None
112+
113+
c_PlayerAiConfig = uw_interop.uwFetchPlayerAiConfigComponent(ptr)
114+
if c_PlayerAiConfig[0]:
115+
e.PlayerAiConfig = c_PlayerAiConfig[1]
116+
else:
117+
e.PlayerAiConfig = None
118+
119+
c_Force = uw_interop.uwFetchForceComponent(ptr)
120+
if c_Force[0]:
121+
e.Force = c_Force[1]
122+
else:
123+
e.Force = None
124+
125+
c_ForceDetails = uw_interop.uwFetchForceDetailsComponent(ptr)
126+
if c_ForceDetails[0]:
127+
e.ForceDetails = c_ForceDetails[1]
128+
else:
129+
e.ForceDetails = None
130+
131+
c_ForeignPolicy = uw_interop.uwFetchForeignPolicyComponent(ptr)
132+
if c_ForeignPolicy[0]:
133+
e.ForeignPolicy = c_ForeignPolicy[1]
134+
else:
135+
e.ForeignPolicy = None
136+
137+
c_DiplomacyProposal = uw_interop.uwFetchDiplomacyProposalComponent(ptr)
138+
if c_DiplomacyProposal[0]:
139+
e.DiplomacyProposal = c_DiplomacyProposal[1]
140+
else:
141+
e.DiplomacyProposal = None

python/uwapi/events.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
from typing import Callable, List
2+
from .interop import *
3+
4+
class Events:
5+
_instance = None
6+
7+
def __new__(cls):
8+
if cls._instance is None:
9+
cls._instance = super().__new__(cls)
10+
return cls._instance
11+
12+
def __init__(self):
13+
self._connection_state_listeners: List[Callable[[UwConnectionStateEnum], None]] = []
14+
self._game_state_listeners: List[Callable[[UwGameStateEnum], None]] = []
15+
self._update_listeners: List[Callable[[int, bool], None]] = []
16+
self._shooting_listeners: List[Callable[[UwShootingArray], None]] = []
17+
self._explosions_listeners: List[Callable[[UwExplosionsArray], None]] = []
18+
self._force_eliminated_listeners: List[Callable[[int], None]] = []
19+
self._chat_listeners: List[Callable[[str, int, UwChatTargetFlags], None]] = []
20+
self._map_state_listeners: List[Callable[[UwMapStateEnum], None]] = []
21+
22+
def initialize(self) -> None:
23+
uw_interop.uwSetExceptionCallback(self._exception_callback)
24+
# uw_interop.uwSetLogCallback(self._log_callback)
25+
uw_interop.uwSetConnectionStateCallback(self._connection_state_callback)
26+
uw_interop.uwSetGameStateCallback(self._game_state_callback)
27+
uw_interop.uwSetUpdateCallback(self._update_callback)
28+
uw_interop.uwSetShootingCallback(self._shooting_callback)
29+
uw_interop.uwSetExplosionsCallback(self._explosions_callback)
30+
uw_interop.uwSetForceEliminatedCallback(self._force_eliminated_callback)
31+
uw_interop.uwSetChatCallback(self._chat_callback)
32+
uw_interop.uwSetTaskCompletedCallback(self._task_completed_callback)
33+
uw_interop.uwSetMapStateCallback(self._map_state_callback)
34+
35+
# ---------------------
36+
37+
def on_connection_state(self, listener: Callable[[UwConnectionStateEnum], None]) -> None:
38+
self._connection_state_listeners.append(listener)
39+
40+
def on_game_state(self, listener: Callable[[UwGameStateEnum], None]) -> None:
41+
self._game_state_listeners.append(listener)
42+
43+
def on_update(self, listener: Callable[[int, bool], None]) -> None:
44+
self._update_listeners.append(listener)
45+
46+
def on_shooting(self, listener: Callable[[UwShootingArray], None]) -> None:
47+
self._shooting_listeners.append(listener)
48+
49+
def on_explosions(self, listener: Callable[[UwExplosionsArray], None]) -> None:
50+
self._explosions_listeners.append(listener)
51+
52+
def on_force_eliminated(self, listener: Callable[[int], None]) -> None:
53+
self._force_eliminated_listeners.append(listener)
54+
55+
def on_chat(self, listener: Callable[[str, int, UwChatTargetFlags], None]) -> None:
56+
self._chat_listeners.append(listener)
57+
58+
def on_map_state(self, listener: Callable[[UwMapStateEnum], None]) -> None:
59+
self._map_state_listeners.append(listener)
60+
61+
# ---------------------
62+
63+
def _exception_callback(self, message: str) -> None:
64+
print(f"exception: {message}")
65+
breakpoint()
66+
67+
def _connection_state_callback(self, state: UwConnectionStateEnum) -> None:
68+
for listener in self._connection_state_listeners:
69+
listener(state)
70+
71+
def _game_state_callback(self, state: UwGameStateEnum) -> None:
72+
for listener in self._game_state_listeners:
73+
listener(state)
74+
75+
def _update_callback(self, tick: int, stepping: bool) -> None:
76+
for listener in self._update_listeners:
77+
listener(tick, stepping)
78+
79+
def _shooting_callback(self, data: UwShootingArray) -> None:
80+
for listener in self._shooting_listeners:
81+
listener(data)
82+
83+
def _explosions_callback(self, data: UwExplosionsArray) -> None:
84+
for listener in self._explosions_listeners:
85+
listener(data)
86+
87+
def _force_eliminated_callback(self, force: int) -> None:
88+
for listener in self._force_eliminated_listeners:
89+
listener(force)
90+
91+
def _chat_callback(self, message: str, sender: int, flags: UwChatTargetFlags) -> None:
92+
for listener in self._chat_listeners:
93+
listener(message, sender, flags)
94+
95+
def _task_completed_callback(self, task_user_data: int, type: UwTaskTypeEnum) -> None:
96+
pass # todo
97+
98+
def _map_state_callback(self, state: UwMapStateEnum) -> None:
99+
for listener in self._map_state_listeners:
100+
listener(state)
101+
102+
uw_events = Events()

0 commit comments

Comments
 (0)