brawlgym 0.1.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 (46) hide show
  1. brawlgym-0.1.0/LICENSE +190 -0
  2. brawlgym-0.1.0/MANIFEST.in +1 -0
  3. brawlgym-0.1.0/PKG-INFO +52 -0
  4. brawlgym-0.1.0/README.md +21 -0
  5. brawlgym-0.1.0/brawlgym/__init__.py +81 -0
  6. brawlgym-0.1.0/brawlgym/core/__init__.py +3 -0
  7. brawlgym-0.1.0/brawlgym/core/brawlgym_core.cp311-win_amd64.pyd +0 -0
  8. brawlgym-0.1.0/brawlgym/envs/__init__.py +1 -0
  9. brawlgym-0.1.0/brawlgym/envs/match.py +216 -0
  10. brawlgym-0.1.0/brawlgym/gamelaunch/__init__.py +6 -0
  11. brawlgym-0.1.0/brawlgym/gamelaunch/_sevenzip.py +188 -0
  12. brawlgym-0.1.0/brawlgym/gamelaunch/gbe.py +147 -0
  13. brawlgym-0.1.0/brawlgym/gamelaunch/launch.py +159 -0
  14. brawlgym-0.1.0/brawlgym/gamelaunch/window.py +117 -0
  15. brawlgym-0.1.0/brawlgym/patcher.py +136 -0
  16. brawlgym-0.1.0/brawlgym/plugin/__init__.py +20 -0
  17. brawlgym-0.1.0/brawlgym/plugin/air_mutex_hook.dll +0 -0
  18. brawlgym-0.1.0/brawlgym/utils/__init__.py +0 -0
  19. brawlgym-0.1.0/brawlgym/utils/action_parsers/__init__.py +3 -0
  20. brawlgym-0.1.0/brawlgym/utils/action_parsers/action_parser.py +36 -0
  21. brawlgym-0.1.0/brawlgym/utils/action_parsers/default_act.py +50 -0
  22. brawlgym-0.1.0/brawlgym/utils/action_parsers/lookup_act.py +60 -0
  23. brawlgym-0.1.0/brawlgym/utils/gamestates/__init__.py +2 -0
  24. brawlgym-0.1.0/brawlgym/utils/gamestates/game_state.py +50 -0
  25. brawlgym-0.1.0/brawlgym/utils/gamestates/player_data.py +34 -0
  26. brawlgym-0.1.0/brawlgym/utils/obs_builders/__init__.py +2 -0
  27. brawlgym-0.1.0/brawlgym/utils/obs_builders/default_obs.py +52 -0
  28. brawlgym-0.1.0/brawlgym/utils/obs_builders/obs_builder.py +35 -0
  29. brawlgym-0.1.0/brawlgym/utils/reward_functions/__init__.py +2 -0
  30. brawlgym-0.1.0/brawlgym/utils/reward_functions/common_rewards.py +108 -0
  31. brawlgym-0.1.0/brawlgym/utils/reward_functions/reward_function.py +22 -0
  32. brawlgym-0.1.0/brawlgym/utils/state_setters/__init__.py +3 -0
  33. brawlgym-0.1.0/brawlgym/utils/state_setters/default_state.py +31 -0
  34. brawlgym-0.1.0/brawlgym/utils/state_setters/random_state.py +46 -0
  35. brawlgym-0.1.0/brawlgym/utils/state_setters/state_setter.py +49 -0
  36. brawlgym-0.1.0/brawlgym/utils/terminal_conditions/__init__.py +2 -0
  37. brawlgym-0.1.0/brawlgym/utils/terminal_conditions/common_conditions.py +43 -0
  38. brawlgym-0.1.0/brawlgym/utils/terminal_conditions/terminal_condition.py +21 -0
  39. brawlgym-0.1.0/brawlgym/version.py +26 -0
  40. brawlgym-0.1.0/brawlgym.egg-info/PKG-INFO +52 -0
  41. brawlgym-0.1.0/brawlgym.egg-info/SOURCES.txt +44 -0
  42. brawlgym-0.1.0/brawlgym.egg-info/dependency_links.txt +1 -0
  43. brawlgym-0.1.0/brawlgym.egg-info/requires.txt +3 -0
  44. brawlgym-0.1.0/brawlgym.egg-info/top_level.txt +1 -0
  45. brawlgym-0.1.0/setup.cfg +4 -0
  46. brawlgym-0.1.0/setup.py +54 -0
brawlgym-0.1.0/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 chrisrca
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ include LICENSE
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: brawlgym
3
+ Version: 0.1.0
4
+ Summary: A python API that can be used to treat the game Brawlhalla as an OpenAI Gym-like environment for Reinforcement Learning projects.
5
+ Home-page: https://github.com/chrisrca/brawlgym
6
+ Author: chrisrca
7
+ License: Apache 2.0
8
+ Keywords: brawlhalla,gym,reinforcement-learning
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Requires-Python: ==3.11.*
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.19
18
+ Requires-Dist: py7zr>=0.20
19
+ Requires-Dist: pycaw>=20220416
20
+ Dynamic: author
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: keywords
26
+ Dynamic: license
27
+ Dynamic: license-file
28
+ Dynamic: requires-dist
29
+ Dynamic: requires-python
30
+ Dynamic: summary
31
+
32
+ # The Brawlhalla Gym
33
+
34
+ This is a python API that can be used to treat the game [Brawlhalla](https://www.brawlhalla.com) as
35
+ though it were an [OpenAI Gym](https://gym.openai.com)-style environment for Reinforcement Learning
36
+ projects. It is heavily inspired by [RLGym](https://rlgym.org/), and the component model will be
37
+ familiar if you have used it.
38
+
39
+ ## Requirements
40
+ * A Windows 10 or 11 PC
41
+ * Brawlhalla (Steam)
42
+ * Python 3.9 or newer
43
+ * `brawlgym_core`, the engine bridge — **not yet available**
44
+
45
+ ## Installation
46
+ Install the library via pip:
47
+ ```
48
+ pip install brawlgym
49
+ ```
50
+
51
+ ## Usage
52
+ Wiki coming soon...
@@ -0,0 +1,21 @@
1
+ # The Brawlhalla Gym
2
+
3
+ This is a python API that can be used to treat the game [Brawlhalla](https://www.brawlhalla.com) as
4
+ though it were an [OpenAI Gym](https://gym.openai.com)-style environment for Reinforcement Learning
5
+ projects. It is heavily inspired by [RLGym](https://rlgym.org/), and the component model will be
6
+ familiar if you have used it.
7
+
8
+ ## Requirements
9
+ * A Windows 10 or 11 PC
10
+ * Brawlhalla (Steam)
11
+ * Python 3.9 or newer
12
+ * `brawlgym_core`, the engine bridge — **not yet available**
13
+
14
+ ## Installation
15
+ Install the library via pip:
16
+ ```
17
+ pip install brawlgym
18
+ ```
19
+
20
+ ## Usage
21
+ Wiki coming soon...
@@ -0,0 +1,81 @@
1
+ """
2
+ brawlgym - a reinforcement-learning environment for Brawlhalla.
3
+
4
+ Match drives a live game instance in deterministic lockstep, and you plug
5
+ in your own ObsBuilder / RewardFunction / TerminalCondition / ActionParser / StateSetter.
6
+
7
+ import brawlgym
8
+
9
+ env = brawlgym.make()
10
+ env.connect() # game running, match started
11
+ obs = env.reset()
12
+ while True:
13
+ obs, rewards, done, state = env.step(actions)
14
+ if done:
15
+ obs = env.reset()
16
+
17
+ Package layout:
18
+ brawlgym.envs Match
19
+ brawlgym.utils.gamestates GameState, PlayerData, ItemData
20
+ brawlgym.utils.obs_builders ObsBuilder, DefaultObs
21
+ brawlgym.utils.reward_functions RewardFunction, common rewards
22
+ brawlgym.utils.terminal_conditions TerminalCondition, TeamWipe/Timeout
23
+ brawlgym.utils.action_parsers ActionParser, DefaultAction, LookupAction
24
+ brawlgym.utils.state_setters StateSetter, Default/Random
25
+ """
26
+ from .envs import Match
27
+ from .utils.action_parsers import ActionParser, DefaultAction, LookupAction
28
+ from .utils.gamestates import GameState, ItemData, PlayerData
29
+ from .utils.obs_builders import DefaultObs, ObsBuilder
30
+ from .utils.reward_functions import CombinedReward, ConstantReward, DamageDealtReward, DamageTakenPenalty, KOReward, RewardFunction
31
+ from .utils.state_setters import DefaultStateSetter, RandomStateSetter, StateSetter
32
+ from .utils.terminal_conditions import TeamWipeCondition, TerminalCondition, TimeoutCondition
33
+ from .version import __version__
34
+
35
+
36
+ def make(**kwargs) -> Match:
37
+ """
38
+ Create a Match with default components (override any via kwargs).
39
+ """
40
+ return Match(**kwargs)
41
+
42
+
43
+ def inject(game_dir=None, refresh=False):
44
+ """
45
+ Patch the local Brawlhalla install with the hook built for its exact game build,
46
+ fetching it if not already cached. Run once before launching the game for training.
47
+ """
48
+ from . import patcher
49
+ return patcher.inject(game_dir=game_dir, refresh=refresh)
50
+
51
+
52
+ def set_map(name):
53
+ """
54
+ Lock the game to one map. Written to disk; takes effect at the next launch.
55
+ """
56
+ from .envs.match import brawlgym_core
57
+ return brawlgym_core.set_map(name)
58
+
59
+
60
+ def restore_maps():
61
+ """
62
+ Undo set_map and put the pristine map set back.
63
+ """
64
+ from .envs.match import brawlgym_core
65
+ return brawlgym_core.restore_maps()
66
+
67
+
68
+ def list_maps():
69
+ """
70
+ [(level_id, level_name)] - every map usable as make(map_name=...).
71
+ """
72
+ from .envs.match import brawlgym_core
73
+ return brawlgym_core.list_maps()
74
+
75
+
76
+ def list_legends():
77
+ """
78
+ [(hero_id, hero_name, bio_name)] - every legend usable in make(legends=[...]).
79
+ """
80
+ from .envs.match import brawlgym_core
81
+ return brawlgym_core.list_legends()
@@ -0,0 +1,3 @@
1
+ """
2
+ Compiled engine bridge (brawlgym_core). Closed-source binary from brawlgym-core.
3
+ """
@@ -0,0 +1 @@
1
+ from .match import Match
@@ -0,0 +1,216 @@
1
+ """
2
+ Drives a live Brawlhalla instance in deterministic lockstep: every `step()` advances the
3
+ simulation exactly `tick_skip` frames with inputs applied, then returns the resulting
4
+ state.
5
+
6
+ Requires the `brawlgym_core` engine module and a running, injected game instance.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any, List, Optional, Sequence
12
+
13
+ from ..utils.action_parsers import ActionParser, DefaultAction
14
+ from ..utils.gamestates import GameState
15
+ from ..utils.obs_builders import DefaultObs, ObsBuilder
16
+ from ..utils.reward_functions import CombinedReward, DamageDealtReward, KOReward, RewardFunction
17
+ from ..utils.state_setters import DefaultStateSetter, StateSetter
18
+ from ..utils.terminal_conditions import TeamWipeCondition, TerminalCondition, TimeoutCondition
19
+
20
+ try:
21
+ from ..core import brawlgym_core # engine bridge, shipped inside the package
22
+ except ImportError: # pragma: no cover
23
+ try:
24
+ import brawlgym_core # dev: built alongside, found on sys.path
25
+ except ImportError as _e:
26
+ brawlgym_core = None
27
+ _core_import_error = _e
28
+
29
+
30
+ # TODO: constants file
31
+ DEFAULT_MAP = "SmallBrawlhaven" # every match needs a locked map to start
32
+ DEFAULT_TURBO_FPS = 30.0 # render-frame rate used when realtime=False; steps run between
33
+ # frames, so a low rate leaves the most room for them
34
+
35
+
36
+ class Match:
37
+ """
38
+ Gym style match over a live game instance.
39
+ """
40
+
41
+ def __init__(self,
42
+ obs_builder: Optional[ObsBuilder] = None,
43
+ reward_function: Optional[RewardFunction] = None,
44
+ terminal_conditions: Optional[Sequence[TerminalCondition]] = None,
45
+ action_parser: Optional[ActionParser] = None,
46
+ state_setter: Optional[StateSetter] = None,
47
+ tick_skip: int = 8,
48
+ realtime: bool = False,
49
+ render_fps: Optional[float] = None,
50
+ fps: float = 60.0,
51
+ n_players: int = 2,
52
+ legends: Optional[Sequence[Any]] = None,
53
+ map_name: Optional[str] = None,
54
+ auto_minimize: bool = False,
55
+ auto_mute: bool = False,
56
+ host: str = "127.0.0.1",
57
+ port: int = 8790):
58
+ if brawlgym_core is None:
59
+ raise ImportError(
60
+ "brawlgym requires the brawlgym_core engine module; install it and ensure it is importable") from _core_import_error
61
+ self.obs_builder = obs_builder or DefaultObs()
62
+ self.reward_function = reward_function or CombinedReward(
63
+ [DamageDealtReward(), KOReward(ko_reward=200.0, death_penalty=200.0)])
64
+ self.terminal_conditions: List[TerminalCondition] = list(
65
+ terminal_conditions if terminal_conditions is not None
66
+ else [TeamWipeCondition(), TimeoutCondition(1200)])
67
+ self.action_parser = action_parser or DefaultAction()
68
+ self.state_setter = state_setter or DefaultStateSetter()
69
+ self.tick_skip = int(tick_skip)
70
+ self.realtime = bool(realtime)
71
+ self.render_fps = render_fps
72
+ self.fps = float(fps) # native sim rate for wall-clock pacing
73
+ self.n_players = int(n_players)
74
+ # per-slot legends (HeroIDs or names)
75
+ # team 1: 0,2,4,6
76
+ # team 2: 1,3,5,7
77
+ # None = the engine's default roster.
78
+ self.legends: Optional[List[int]] = self._resolve_legends(legends) if legends else None
79
+ # A match cannot start without a locked map
80
+ # map_name=None uses small brawlhaven
81
+ self.map_name = map_name or DEFAULT_MAP
82
+ self.auto_minimize = bool(auto_minimize)
83
+ self.auto_mute = bool(auto_mute)
84
+ self.map_info = brawlgym_core.get_map_geometry(self.map_name)
85
+ for comp in (self.obs_builder, self.state_setter):
86
+ if hasattr(comp, "set_map_info"):
87
+ comp.set_map_info(self.map_info)
88
+ # NOTE: the engine's internal `framems` stays at 25ms regardless of fps - it is the
89
+ # forced-step owed-time, chosen so exactly ONE 60fps frame runs per step (floor math
90
+ # needs it in [16.7, 33.3)); it does not affect game speed.
91
+
92
+ self._bridge = brawlgym_core.HookBridge(host, port)
93
+ self._state: Optional[GameState] = None
94
+ self._prev_actions: Optional[Sequence[Any]] = None
95
+
96
+ @staticmethod
97
+ def _resolve_legends(legends: Sequence[Any]) -> List[int]:
98
+ """
99
+ Resolve a mixed list of HeroIDs and legend names to HeroIDs.
100
+ """
101
+ ids: List[int] = []
102
+ table = None
103
+ for item in legends:
104
+ if isinstance(item, str):
105
+ if table is None:
106
+ if not hasattr(brawlgym_core, "list_legends"):
107
+ raise ValueError("cannot resolve legend names pass numeric HeroIDs instead")
108
+ table = {}
109
+ for hid, hero_name, bio_name in brawlgym_core.list_legends():
110
+ table[str(hero_name).lower()] = int(hid)
111
+ if bio_name:
112
+ table[str(bio_name).lower()] = int(hid)
113
+ key = item.lower()
114
+ if key not in table:
115
+ raise ValueError("unknown legend %r" % item)
116
+ ids.append(table[key])
117
+ else:
118
+ ids.append(int(item))
119
+ return ids
120
+
121
+ def connect(self, timeout: float = 300.0) -> GameState:
122
+ """
123
+ Wait for the game, then for a running match; enable sit-out-on-death.
124
+
125
+ The game must be launched and a match started. Returns the first observed state.
126
+ """
127
+ print("[brawlgym] waiting for the game ...", flush=True)
128
+ self._bridge.wait_for_hook(timeout)
129
+ # roster size + legends for the auto-started match specified before the party forms
130
+ self._bridge.set_player_count(self.n_players)
131
+ if self.legends:
132
+ self._bridge.set_legends(self.legends)
133
+ st = self._wait_for_match(timeout)
134
+ if self.realtime:
135
+ self._bridge.configure(1, 25.0) # 1x speed, rendered (native 60fps free-run)
136
+ else:
137
+ self._bridge.configure(max(16, self.tick_skip * 2), 25.0)
138
+ target = self.render_fps
139
+ if target is None and not self.realtime:
140
+ target = DEFAULT_TURBO_FPS
141
+ if target:
142
+ self._bridge.set_render_fps(float(target))
143
+ print("[brawlgym] render fps -> %g" % target, flush=True)
144
+ self._bridge.set_sitout(True) # deaths sit out until reset()
145
+ self._state = st
146
+ print("[brawlgym] match up: %d fighters" % len(st.players), flush=True)
147
+ from ..gamelaunch import window # matches by window title / process name (single instance)
148
+ if self.auto_minimize:
149
+ window.minimize_title("Brawlhalla")
150
+ if window.pycaw_available():
151
+ window.mute_name("Brawlhalla.exe", mute=self.auto_mute)
152
+ elif self.auto_mute:
153
+ print("[brawlgym] pycaw not installed - cannot mute (pip install pycaw)")
154
+ return st
155
+
156
+ def _wait_for_match(self, timeout: float) -> GameState:
157
+ """
158
+ Poll until fighters exist.
159
+ """
160
+ t_end = time.time() + timeout
161
+ while time.time() < t_end:
162
+ try:
163
+ st = GameState(self._bridge.get_state())
164
+ players = st.players
165
+ if len(players) >= 2 and all(p.x > -5000 for p in players):
166
+ return st
167
+ except Exception:
168
+ try:
169
+ self._bridge.wait_for_hook(30)
170
+ except Exception:
171
+ pass
172
+ time.sleep(1.0)
173
+ raise TimeoutError("no running match detected - start a match in the game")
174
+
175
+ def close(self) -> None:
176
+ self._bridge.close()
177
+
178
+ @property
179
+ def n_agents(self) -> int:
180
+ return len(self._state.players) if self._state else 0
181
+
182
+ def reset(self) -> List[Any]:
183
+ """
184
+ Revive + reposition every fighter, reset all components, return initial obs.
185
+ """
186
+ if self._state is None:
187
+ self.connect()
188
+ n = len(self._state.players)
189
+ positions = [(int(round(x)), int(round(y)))
190
+ for x, y in self.state_setter.build_positions(n)]
191
+ st = GameState(self._bridge.reset(positions))
192
+ self._state = st
193
+ self._prev_actions = None
194
+ self.obs_builder.reset(st)
195
+ self.reward_function.reset(st)
196
+ for tc in self.terminal_conditions:
197
+ tc.reset(st)
198
+ # noop previous action
199
+ zero_act = [0.0] * self.action_parser.get_action_space_size()
200
+ return [self.obs_builder.build_obs(p, st, zero_act) for p in st.players]
201
+
202
+ def step(self, actions: Sequence[Any]):
203
+ """
204
+ Advance tick_skip frames with the given per-agent actions.
205
+
206
+ Returns (observations, rewards, terminated, game_state).
207
+ """
208
+ masks = self.action_parser.parse_actions(actions, self._state)
209
+ st = GameState(self._bridge.step(masks, self.tick_skip))
210
+ self._state = st
211
+ self._prev_actions = actions
212
+ obs = [self.obs_builder.build_obs(p, st, a) for p, a in zip(st.players, actions)]
213
+ rewards = [self.reward_function.get_reward(p, st, a)
214
+ for p, a in zip(st.players, actions)]
215
+ terminated = any(tc.is_terminal(st) for tc in self.terminal_conditions)
216
+ return obs, rewards, terminated, st
@@ -0,0 +1,6 @@
1
+ """
2
+ brawlgym.gamelaunch - boot Brawlhalla instances for training.
3
+ """
4
+ from .launch import DEFAULT_BASE_PORT, find_brawlhalla_dir, launch_instances
5
+
6
+ __all__ = ["launch_instances", "find_brawlhalla_dir", "DEFAULT_BASE_PORT"]