├── .github └── FUNDING.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── dependencies.txt ├── pics ├── chart.png └── hogwild3.gif ├── requirements.txt ├── setup.cfg ├── setup.py ├── src └── MAMEToolkit │ ├── .libs │ └── libasound_module_conf_pulse.so │ ├── __init__.py │ ├── emulator │ ├── Action.py │ ├── Address.py │ ├── BitmapFormat.py │ ├── Console.py │ ├── Emulator.py │ ├── StreamGobbler.py │ ├── __init__.py │ └── pipes │ │ ├── DataPipe.py │ │ ├── Pipe.py │ │ └── __init__.py │ └── sf_environment │ ├── Actions.py │ ├── Environment.py │ ├── Steps.py │ └── __init__.py ├── test └── emulator │ ├── __init__.py │ ├── pipes │ ├── __init__.py │ ├── test_data_pipe.py │ └── test_pipe.py │ ├── test_address.py │ ├── test_console.py │ ├── test_emulator.py │ └── test_stream_gobbler.py └── travis └── build-mame.sh /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: M-J-Murray 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *__pycache__* 3 | src/MAMEToolkit/emulator/mame/roms/sfiii3n.zip 4 | src/MAMEToolkit/emulator/mame/nvram 5 | src/MAMEToolkit/emulator/mame/cfg 6 | src/MAMEToolkit/emulator/mame/history 7 | binary/ 8 | build 9 | dist 10 | MAMEToolkit-** 11 | MAMEToolkit.egg-info 12 | temp 13 | wheelhouse 14 | mame 15 | profile.md 16 | venv -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.2 4 | - jruby 5 | 6 | notifications: 7 | email: false 8 | 9 | matrix: 10 | include: 11 | - sudo: required 12 | services: 13 | - docker 14 | env: DOCKER_IMAGE=quay.io/pypa/manylinux2010_x86_64 15 | PLAT=manylinux2010_x86_64 16 | 17 | install: 18 | - docker pull $DOCKER_IMAGE 19 | 20 | script: 21 | - docker run --rm -e PLAT=$PLAT -v `pwd`:/io $DOCKER_IMAGE $PRE_CMD /io/travis/build-mame.sh 22 | - ls wheelhouse/ 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The MAME RL Algorithm Training Toolkit 2 | 3 | ## About 4 | This Python library will allow you to train your reinforcement learning algorithm on almost any arcade game. It is currently available on Linux systems and works as a wrapper around [MAME](http://mamedev.org/). The toolkit allows your algorithm to step through gameplay while recieving the frame data and internal memory address values for tracking the games state, along with sending actions to interact with the game. 5 | 6 | ## Requirements: 7 | - Operating system: Vast majority of desktop and server Linux distributions 8 | - Instruction set: amd64 (this includes intel CPUs) 9 | - Python version: 3.6 or greater 10 | 11 | **NOTE**: If you are using an uncommon linux distribution or a CPU with a different instruction set, see section [Compiling custom MAME](#Compiling-custom-MAME). 12 | 13 | ## Installation 14 | You can use `pip` to install the library, just run: 15 | ```bash 16 | pip install MAMEToolkit 17 | ``` 18 | 19 | **DISCLAIMER: We are unable to provide you with any game ROMs. It is the users own legal responsibility to acquire a game ROM for emulation. This library should only be used for non-commercial research purposes.** 20 | 21 | There are some free ROMs available at: https://www.mamedev.org/roms/ 22 | 23 | ## Sponsorship & Future Development :heart: 24 | I have just joined the [Github Sponsors](https://github.com/sponsors/M-J-Murray) program and would appreciate any donations towards future development on this project. There are a plans to extend and improve upon this library, and with your help we can make this happen. If you would like to show your appreciation or request a new game environment/feature be added, feel free to go to https://github.com/sponsors/M-J-Murray and become a sponsor today! 25 | 26 | The sponsor page also outlines future plans and optimisations which will help improve the library for everyone. 27 | 28 | 29 | ## Street Fighter Random Agent Demo 30 | The toolkit has currently been applied to Street Fighter III Third Strike: Fight for the Future (Japan 990608, NO CD), but can modified for any game available on MAME. The following demonstrates how a random agent can be written for a street fighter environment. 31 | ```python 32 | import random 33 | from MAMEToolkit.sf_environment import Environment 34 | 35 | roms_path = "roms/" # Replace this with the path to your ROMs 36 | env = Environment("env1", roms_path) 37 | env.start() 38 | while True: 39 | move_action = random.randint(0, 8) 40 | attack_action = random.randint(0, 9) 41 | frames, reward, round_done, stage_done, game_done = env.step(move_action, attack_action) 42 | if game_done: 43 | env.new_game() 44 | elif stage_done: 45 | env.next_stage() 46 | elif round_done: 47 | env.next_round() 48 | ``` 49 | 50 | The toolkit also supports hogwild training: 51 | ```python 52 | from multiprocessing import Process 53 | import random 54 | from MAMEToolkit.sf_environment import Environment 55 | 56 | 57 | def run_env(worker_id, roms_path): 58 | env = Environment(f"env{worker_id}", roms_path) 59 | env.start() 60 | while True: 61 | move_action = random.randint(0, 8) 62 | attack_action = random.randint(0, 9) 63 | frames, reward, round_done, stage_done, game_done = env.step(move_action, attack_action) 64 | if game_done: 65 | env.new_game() 66 | elif stage_done: 67 | env.next_stage() 68 | elif round_done: 69 | env.next_round() 70 | 71 | 72 | workers = 8 73 | # Environments must be created outside of the threads 74 | roms_path = "roms/" # Replace this with the path to your ROMs 75 | threads = [Process(target=run_env, args=(i, roms_path)) for i in range(workers)] 76 | [thread.start() for thread in threads] 77 | ``` 78 | 79 | ![](pics/hogwild3.gif "Hogwild Random Agents") 80 | 81 | ## Setting Up Your Own Game Environment 82 | 83 | **Game ID's**
84 | To create an emulation of the game you must first have the ROM for the game you are emulating and know the game ID used by MAME, for example for this version of street fighter it is 'sfiii3n'. 85 | The id of your game can be found by running: 86 | ```python 87 | from src.MAMEToolkit.emulator import see_games 88 | see_games() 89 | ``` 90 | This will bring up the MAME emulator. You can search through the list of games to find the one you want. The id of the game is always in brackets at the end of the game title. 91 | 92 | **Memory Addresses**
93 | It doesn't take much to interact with the emulator itself using the toolkit, however the challenge comes from finding the memory address values associated with the internal state you care about, and tracking said state with your environment class. 94 | The internal memory states of a game can be tracked using the [MAME Cheat Debugger](http://docs.mamedev.org/debugger/cheats.html), which allows you to track how the memory address values of the game change over time. 95 | 96 | 97 | The cheat debugger can be run using the following: 98 | ```python 99 | from src.MAMEToolkit.emulator import run_cheat_debugger 100 | roms_path = "roms/" # Replace this with the path to your ROMs 101 | game_id = "sfiii3n" 102 | run_cheat_debugger(roms_path, game_id) 103 | ``` 104 | For information about using the debugger, see the Memory dump section of the following [tutorial](http://bzztbomb.com/blog/2013/03/23/use-mames-debugger-to-reverse-engineer-and-extend-old-games/) 105 | 106 | 107 | Once you have determined the memory addresses you wish to track you can start the emulation using: 108 | ```python 109 | from src.MAMEToolkit.emulator import Emulator 110 | from src.MAMEToolkit.emulator import Address 111 | 112 | roms_path = "roms/" # Replace this with the path to your ROMs 113 | game_id = "sfiii3n" 114 | memory_addresses = { 115 | "fighting": Address('0x0200EE44', 'u8'), 116 | "winsP1": Address('0x02011383', 'u8'), 117 | "winsP2": Address('0x02011385', 'u8'), 118 | "healthP1": Address('0x02068D0B', 's8'), 119 | "healthP2": Address('0x020691A3', 's8') 120 | } 121 | 122 | emulator = Emulator("env1", roms_path, game_id, memory_addresses) 123 | ``` 124 | This will immediately start the emulation and halt it when the toolkit has linked to the emulator process. 125 | 126 | **Stepping the emulator**
127 | Once the toolkit is linked, you can step the emulator along using the step function: 128 | ```python 129 | data = emulator.step([]) 130 | 131 | frame = data["frame"] 132 | is_fighting = data["fighting"] 133 | player1_wins = data["winsP1"] 134 | player2_wins = data["winsP2"] 135 | player1_health = data["healthP1"] 136 | player2_health = data["healthP2"] 137 | ``` 138 | The step function returns the frame data as a NumPy matrix, along with all of the memory address integer values from that timestep. 139 | 140 | **Sending inputs** 141 | To send actions to the emulator you also need to determine which input ports and fields the game supports. For example, with street fighter to insert a coin the following code is required: 142 | ```python 143 | from src.MAMEToolkit.emulator import Action 144 | 145 | insert_coin = Action(':INPUTS', 'Coin 1') 146 | data = emulator.step([insert_coin]) 147 | ``` 148 | To identify which ports are availble use the list actions command: 149 | ```python 150 | from src.MAMEToolkit.emulator import list_actions 151 | 152 | roms_path = "roms/" # Replace this with the path to your ROMs 153 | game_id = "sfiii3n" 154 | print(list_actions(roms_path, game_id)) 155 | ``` 156 | which for street fighter returns the list with all the ports and fields available for sending actions to the step function: 157 | ```python 158 | [ 159 | {'port': ':scsi:1:cdrom:SCSI_ID', 'field': 'SCSI ID'}, 160 | {'port': ':INPUTS', 'field': 'P2 Jab Punch'}, 161 | {'port': ':INPUTS', 'field': 'P1 Left'}, 162 | {'port': ':INPUTS', 'field': 'P2 Fierce Punch'}, 163 | {'port': ':INPUTS', 'field': 'P1 Down'}, 164 | {'port': ':INPUTS', 'field': 'P2 Down'}, 165 | {'port': ':INPUTS', 'field': 'P2 Roundhouse Kick'}, 166 | {'port': ':INPUTS', 'field': 'P2 Strong Punch'}, 167 | {'port': ':INPUTS', 'field': 'P1 Strong Punch'}, 168 | {'port': ':INPUTS', 'field': '2 Players Start'}, 169 | {'port': ':INPUTS', 'field': 'Coin 1'}, 170 | {'port': ':INPUTS', 'field': '1 Player Start'}, 171 | {'port': ':INPUTS', 'field': 'P2 Right'}, 172 | {'port': ':INPUTS', 'field': 'Service 1'}, 173 | {'port': ':INPUTS', 'field': 'Coin 2'}, 174 | {'port': ':INPUTS', 'field': 'P1 Jab Punch'}, 175 | {'port': ':INPUTS', 'field': 'P2 Up'}, 176 | {'port': ':INPUTS', 'field': 'P1 Up'}, 177 | {'port': ':INPUTS', 'field': 'P1 Right'}, 178 | {'port': ':INPUTS', 'field': 'Service Mode'}, 179 | {'port': ':INPUTS', 'field': 'P1 Fierce Punch'}, 180 | {'port': ':INPUTS', 'field': 'P2 Left'}, 181 | {'port': ':EXTRA', 'field': 'P2 Short Kick'}, 182 | {'port': ':EXTRA', 'field': 'P2 Forward Kick'}, 183 | {'port': ':EXTRA', 'field': 'P1 Forward Kick'}, 184 | {'port': ':EXTRA', 'field': 'P1 Roundhouse Kick'}, 185 | {'port': ':EXTRA', 'field': 'P1 Short Kick'} 186 | ] 187 | ``` 188 | We advise you to create an enum of all the possible actions, then send their action values to the emulator, see [the example Actions Enum](src/MAMEToolkit/sf_environment/Actions.py) 189 | 190 | There is also the problem of transitioning games between non-learnable gameplay screens such as the title screen and character select. To see how this can be implemented please look at the provided [Steps script](src/MAMEToolkit/sf_environment/Steps.py) and the [Example Street Fighter III Third Strike: Fight for the Future Environment Implementation](src/MAMEToolkit/sf_environment/Environment.py) 191 | 192 | The emulator class also has a frame_ratio argument which can be used for adjusting the frame rate seen by your algorithm. By default MAME generates frames at 60 frames per second, however, this may be too many frames for your algorithm. The toolkit by default will use a frame_ratio of 3, which means that 1 in 3 frames are sent through the toolkit, this converts the frame rate to 20 frames per second. Using a higher frame_ratio also increases the performance of the toolkit. 193 | ```Python 194 | from src.MAMEToolkit.emulator import Emulator 195 | 196 | emulator = Emulator(env_id, roms_path, game_id, memory_addresses, frame_ratio=3) 197 | ``` 198 | 199 | ## Running The Library Without A Screen / On A Linux Server 200 | If you are running a linux server or a docker instance then you will need to add some extra code to your python script to enable MAME to run. 201 | To achieve this we will be using the [Xvfb library](https://en.wikipedia.org/wiki/Xvfb), which will simulate an instance of the X display server. 202 | Simply install the `Xvfb` library for your relevant linux distro. Then add to the following two lines to the top of your main Python script. 203 | ```python 204 | import os 205 | os.system("Xvfb :0 -screen 0 800x600x16 +extension RANDR &") 206 | os.environ["DISPLAY"] = ":0" 207 | ``` 208 | This will simulate a 800x600 resolution screen with 16-bit colour. Feel free to change the parameters to suit your needs. 209 | 210 | 211 | ## Library Performance Benchmarks with PC Specs 212 | The development and testing of this toolkit have been completed on an 8-core AMD FX-8300 3.3GHz CPU along with a 3GB GeForce GTX 1060 GPU. 213 | With a single random agent, the street fighter environment can be run at 600%+ the normal gameplay speed. And For hogwild training with 8 random agents, the environment can be run at 300%+ the normal gameplay speed. 214 | 215 | ## Simple ConvNet Agent 216 | To ensure that the toolkit is able to train algorithms, a simple 5 layer ConvNet was setup with minimal tuning. The algorithm was able to successfully learn some simple mechanics of Street Fighter, such as combos and blocking. The Street Fighter gameplay works by having the player fight different opponents across 10 stages of increasing difficulty. Initially, the algorithm would reach stage 2 on average, but eventually could reach stage 5 on average after 2200 episodes of training. The learning rate was tracked using the net damage done vs damage taken of a single playthough for each episode. 217 | 218 | ![](pics/chart.png "ConvNet Results") 219 | 220 | ## MAME Changes 221 | The library acts as a wrapper around a modified MAME implementation. 222 | The following changes were made: 223 | * Updated the lua console to allow for the retrieval of the format of frame data 224 | * Update the lua console to allow for the retrieval of the current frames data 225 | * Disabled game start warnings 226 | 227 | The following files are affected: 228 | * src/emu/machine.cpp 229 | * src/emu/video.cpp 230 | * src/emu/video.h 231 | * src/frontend/mame/luaengine.cpp 232 | * src/frontend/mame/ui/ui.cpp 233 | * src/osd/sdl/window.cpp 234 | 235 | **The modified MAME implementation can be found at [https://github.com/M-J-Murray/mame]** 236 | 237 | ## Compiling custom MAME 238 | Unfortunately this library doesn't work with every single OS or CPU instruction set. This is because it uses a custom precompiled instance of MAME that is specific to the OS and CPU it was compiled on. 239 | However, if you are using a different linux distribution or instruction set, this does not mean you are out of options, it just means that your path to using this library is a little more complicated. 240 | Your only remaining option is to compile the custom instance of MAME yourself. To achieve this you just need a linux distribution with a GUI. Other operating systems will not work, as the library relies heavily on linux fifo pipes. 241 | 242 | ### Compilation steps 243 | To compile your own custom instance of MAME run the following commands in your terminal: 244 | ```bash 245 | git clone git@github.com:M-J-Murray/mame.git 246 | cd mame 247 | make SUBTARGET=arcade -j4 248 | ``` 249 | Adjust `j` to match the amount of virtual cores your CPU supports, as this could take several hours depending on your computer. 250 | 251 | Once the compilation has completed you should have an executable file called `mamearcade64`, or something along those lines. 252 | Now you can either use the binary_path keyword argument on your emulator method calls to point at your custom binary, or you can rename said executable to `mame` and replace the precompiled MAME instance in your python MAMEToolkit directory with your new file. 253 | You should be able to find the MAMEToolkit directory by going to your python environment directory, and then going to `site-packages`. 254 | 255 | ### Troubleshooting 256 | This section describes what to do if your `make` command fails with some kind of error message describing an incorrect/missing library. 257 | As different linux distributions implement different libraries by default it is likely that you will not have the correct libraries installed by default. These libraries will also need to be specific to your CPU instruction set. 258 | Writing all the library installation commands for all linux distributions and instruction sets would be extremely difficult, however, I can outline the libraries that MAME requires. The list is as follows: 259 | * libdl 260 | * librt 261 | * libSDL2-2.0 262 | * libpthread 263 | * libutil 264 | * libGL 265 | * libasound 266 | * libQt5Widgets 267 | * libQt5Gui 268 | * libQt5Core 269 | * libX11 270 | * libSDL2_ttf-2.0 271 | * libfontconfig 272 | * libstdc++ 273 | * libm 274 | * libgcc_s 275 | * libc 276 | 277 | Your error message should indicate that at least one of these libraries is missing. To install said library you will need to look online and find out how to install/update the library for your relevant linux distribution and instruction set. 278 | Use the following as a google search template: "{linux distribution} {CPU instruction set} install {missing library}" 279 | Just replace the curly brackets with the information relevant to you. Hopefully you should be able to find the relevant install command on a forum. If the missing library isn't available for your distro/cpu then the MAMEToolkit will not work for you. 280 | 281 | Once you have installed your library just run `make` again and it will continue where it left off, you will not lose your compilation progress. 282 | -------------------------------------------------------------------------------- /dependencies.txt: -------------------------------------------------------------------------------- 1 | libSDL2-2.0.so.0 2 | libasound.so.2 3 | libQt5Widgets.so.5 4 | libQt5Gui.so.5 5 | libQt5Core.so.5 6 | libXi.so.6 7 | libSDL2_ttf-2.0.so.0 8 | libfontconfig.so.1 9 | libc.so.6 -------------------------------------------------------------------------------- /pics/chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M-J-Murray/MAMEToolkit/3fb35a2088302fd0632b9d7c1bf5690f6a06694c/pics/chart.png -------------------------------------------------------------------------------- /pics/hogwild3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M-J-Murray/MAMEToolkit/3fb35a2088302fd0632b9d7c1bf5690f6a06694c/pics/hogwild3.gif -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | license_files = 3 | LICENSE 4 | [bdist_wheel] 5 | python-tag = py3 6 | plat-name = manylinux2010_x86_64 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | import os 3 | 4 | from setuptools import setup, find_packages 5 | from setuptools.command.build_py import build_py 6 | from distutils.dir_util import copy_tree 7 | 8 | 9 | def copy_to_build(file_path, build_dir): 10 | if os.path.exists(file_path): 11 | if not os.path.isdir(build_dir): 12 | os.makedirs(build_dir) 13 | if os.path.isdir(file_path): 14 | copy_tree(file_path, build_dir) 15 | else: 16 | shutil.copy(file_path, build_dir) 17 | 18 | 19 | class build(build_py): 20 | 21 | def run(self): 22 | build_py.run(self) 23 | copy_to_build("binary/mame", os.path.join(self.build_lib, 'MAMEToolkit/emulator/mame')) 24 | copy_to_build("src/MAMEToolkit/emulator/mame/fonts", os.path.join(self.build_lib, 'MAMEToolkit/emulator/mame/fonts')) 25 | copy_to_build("src/MAMEToolkit/emulator/mame/plugins", os.path.join(self.build_lib, 'MAMEToolkit/emulator/mame/plugins')) 26 | copy_to_build("src/MAMEToolkit/.libs", os.path.join(self.build_lib, 'MAMEToolkit/.libs')) 27 | 28 | 29 | with open("README.md", "r") as fh: 30 | long_description = fh.read() 31 | 32 | setup( 33 | name="MAMEToolkit", 34 | version="1.1.0", 35 | author="Michael Murray", 36 | author_email="m.j.murray123@gmail.com", 37 | description="A library to train your RL algorithms against MAME arcade games on Linux", 38 | long_description=long_description, 39 | long_description_content_type="text/markdown", 40 | url="https://github.com/M-J-Murray/MAMEToolkit", 41 | zip_safe=False, 42 | packages=find_packages("src", exclude=["src/MAMEToolkit/.libs", "src/MAMEToolkit/emulator/mame"]), 43 | package_dir={"": "src"}, 44 | classifiers=[ 45 | "Programming Language :: Python :: 3", 46 | "License :: OSI Approved :: MIT License", 47 | "Operating System :: POSIX :: Linux" 48 | ], 49 | install_requires=[ 50 | 'numpy', 51 | ], 52 | cmdclass={ 53 | 'build_py': build, 54 | } 55 | ) 56 | -------------------------------------------------------------------------------- /src/MAMEToolkit/.libs/libasound_module_conf_pulse.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M-J-Murray/MAMEToolkit/3fb35a2088302fd0632b9d7c1bf5690f6a06694c/src/MAMEToolkit/.libs/libasound_module_conf_pulse.so -------------------------------------------------------------------------------- /src/MAMEToolkit/__init__.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit import emulator 2 | from MAMEToolkit import sf_environment -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/Action.py: -------------------------------------------------------------------------------- 1 | class Action(object): 2 | 3 | def __init__(self, port, field): 4 | self.port = port 5 | self.field = field 6 | 7 | def get_lua_string(self): 8 | return 'iop.ports["' + self.port + '"].fields["' + self.field + '"]' 9 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/Address.py: -------------------------------------------------------------------------------- 1 | # A class used to help abstract and simplify the process of setting up a memory address that you want to read from 2 | class Address(object): 3 | 4 | def __init__(self, address, mode): 5 | self.address = address 6 | self.mode = mode 7 | 8 | def get_lua_string(self): 9 | try: 10 | return { 11 | 'u8': 'mem:read_u8('+self.address+')', 12 | 'u16': 'mem:read_u16('+self.address+')', 13 | 'u32': 'mem:read_u32('+self.address+')', 14 | 's8': 'mem:read_i8('+self.address+')', 15 | 's16': 'mem:read_i16('+self.address+')', 16 | 's32': 'mem:read_i32('+self.address+')' 17 | }[self.mode] 18 | except KeyError: 19 | raise IOError("Invalid address mode used") 20 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/BitmapFormat.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class BitmapFormat(Enum): 5 | RGB32 = 3 6 | ARGB32 = 4 7 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/Console.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | from subprocess import Popen, PIPE 4 | from MAMEToolkit.emulator.StreamGobbler import StreamGobbler 5 | import queue 6 | import logging 7 | 8 | fonts_path = os.path.join(os.path.dirname(__file__), 'mame', 'fonts') 9 | if "FONTCONFIG_PATH" not in os.environ: 10 | os.environ["FONTCONFIG_PATH"] = fonts_path 11 | elif fonts_path not in os.environ["FONTCONFIG_PATH"]: 12 | os.environ["FONTCONFIG_PATH"] += ";" + fonts_path 13 | 14 | 15 | # A class for starting the MAME emulator, and communicating with the Lua engine console 16 | class Console(object): 17 | 18 | # Starts up an instance of MAME with POpen 19 | # Uses a separate thread for reading from the console outputs 20 | # render is for displaying the frames to the emulator window, disabling it has little to no effect 21 | # throttle enabled will run any game at the intended gameplay speed, disabling it will run the game as fast as the computer can handle 22 | # debug enabled will print everything that comes out of the Lua engine console 23 | def __init__(self, roms_path, game_id, cheat_debugger=False, render=True, throttle=False, frame_skip=0, sound=False, debug=False, binary_path=None): 24 | self.logger = logging.getLogger("Console") 25 | 26 | mame_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mame") 27 | if binary_path is None: 28 | binary_path = "./mame" 29 | else: 30 | binary_path = str(Path(binary_path).absolute()) 31 | 32 | command = f"exec {binary_path} -rompath '{str(Path(roms_path).absolute())}' -pluginspath plugins -skip_gameinfo -window -nomaximize -console "+game_id 33 | if not render: 34 | command += " -video none" 35 | 36 | if cheat_debugger: 37 | command += " -debug" 38 | 39 | if throttle: 40 | command += " -throttle" 41 | else: 42 | command += " -nothrottle" 43 | 44 | command += " -frameskip "+str(frame_skip) 45 | 46 | if not sound: 47 | command += " -sound none" 48 | 49 | # Start lua console 50 | self.process = Popen(command, cwd=mame_path, shell=True, stdin=PIPE, stdout=PIPE) 51 | 52 | # Start read queues 53 | self.stdout_queue = queue.Queue() 54 | self.gobbler = StreamGobbler(self.process.stdout, self.stdout_queue, debug=debug) 55 | self.gobbler.wait_for_cursor() 56 | self.gobbler.start() 57 | 58 | # Read the oldest line which may have been output by the console 59 | # Uses the FIFO principle, once a line is read it is removed from the queue 60 | # timeout determines how long the function will wait for an output if there is nothing immediately available 61 | def readln(self, timeout=0.5): 62 | line = self.stdout_queue.get(timeout=timeout) 63 | while len(line)>0 and line[0] == 27: 64 | line = line[19:] 65 | return line.decode("utf-8") 66 | 67 | # Read as many lines from the console as there are available 68 | # timeout determines how long the function will wait for an output if there is nothing immediately available 69 | def readAll(self, timeout=0.5): 70 | lines = [] 71 | while True: 72 | try: 73 | lines.append(self.readln(timeout=timeout)) 74 | except queue.Empty as e: 75 | break 76 | return lines 77 | 78 | def writeln(self, command, expect_output=False, timeout=0.5, raiseError=True): 79 | self.process.stdin.write(command.encode("utf-8") + b'\n') 80 | self.process.stdin.flush() 81 | output = self.readAll(timeout=timeout) 82 | 83 | if expect_output and len(output) == 0: 84 | error = "Expected output but received nothing from emulator after '" + command + "'" 85 | if raiseError: 86 | self.logger.error(error) 87 | raise IOError(error) 88 | else: 89 | return None 90 | if not expect_output and len(output) > 0: 91 | error = "No output expected from command '" + command + "', but recieved: " + "\n".join(output) 92 | if raiseError: 93 | self.logger.error(error) 94 | raise IOError(error) 95 | else: 96 | return None 97 | if expect_output: 98 | return output 99 | 100 | # Mainly for testing 101 | # Safely kills the emulator process 102 | def close(self): 103 | self.process.kill() 104 | try: 105 | self.process.wait(timeout=3) 106 | except Exception as e: 107 | error = "Failed to close emulator console" 108 | self.logger.error(error, e) 109 | raise EnvironmentError(error) 110 | self.gobbler.stop() 111 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/Emulator.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import os 3 | from MAMEToolkit.emulator.Console import Console 4 | from MAMEToolkit.emulator.pipes import Pipe 5 | from MAMEToolkit.emulator.pipes import DataPipe 6 | from MAMEToolkit.emulator.BitmapFormat import BitmapFormat 7 | 8 | 9 | # Converts a list of action Enums into the relevant Lua engine representation 10 | def actions_to_string(actions): 11 | action_strings = [action.get_lua_string() for action in actions] 12 | return '+'.join(action_strings) 13 | 14 | 15 | def list_actions(roms_path, game_id, binary_path=None): 16 | console = Console(roms_path, game_id, binary_path=binary_path) 17 | console.writeln('iop = manager:machine():ioport()') 18 | actions = [] 19 | ports = console.writeln("for k,v in pairs(iop.ports) do print(k) end", expect_output=True, timeout=0.5) 20 | for port in ports: 21 | try: 22 | fields = console.writeln("for k,v in pairs(iop.ports['"+port+"'].fields) do print(k) end", expect_output=True) 23 | for field in fields: 24 | actions.append({"port": port, "field": field}) 25 | except IOError as e: 26 | console.logger.error("Could indicate unused button set") 27 | 28 | console.close() 29 | return actions 30 | 31 | 32 | def see_games(binary_path=None): 33 | Emulator("env1", "", "", {}, binary_path=binary_path) 34 | 35 | 36 | def run_cheat_debugger(roms_path, game_id, binary_path=None): 37 | Console(roms_path, game_id, cheat_debugger=True, render=True, throttle=True, debug=True, binary_path=binary_path) 38 | 39 | 40 | # An interface for using the Lua engine console functionality 41 | class Emulator(object): 42 | 43 | # env_id - the unique id of the emulator, used for fifo pipes 44 | # game_id - the game id being used 45 | # memory_addresses - The internal memory addresses of the game which this class will return the value of at every time step 46 | # frame_ratio - the ratio of frames that will be returned, 3 means 1 out of every 3 frames will be returned. Note that his also effects how often memory addresses are read and actions are sent 47 | # See console for render, throttle & debug 48 | def __init__(self, env_id, roms_path, game_id, memory_addresses, frame_ratio=3, render=True, throttle=False, frame_skip=0, sound=False, debug=False, binary_path=None): 49 | self.memory_addresses = memory_addresses 50 | self.frame_ratio = frame_ratio 51 | 52 | # setup lua engine 53 | self.console = Console(roms_path, game_id, render=render, throttle=throttle, frame_skip=frame_skip, sound=sound, debug=debug, binary_path=binary_path) 54 | atexit.register(self.close) 55 | self.wait_for_resource_registration() 56 | self.create_lua_variables() 57 | bitmap_format = self.get_bitmap_format() 58 | screen_width = self.setup_screen_width() 59 | screen_height = self.setup_screen_height() 60 | self.screenDims = {"width": screen_width, "height": screen_height} 61 | 62 | # open pipes 63 | pipes_path = f"{os.path.dirname(os.path.abspath(__file__))}/mame/pipes" 64 | self.actionPipe = Pipe(env_id, "action", 'w', pipes_path) 65 | self.actionPipe.open(self.console) 66 | 67 | self.dataPipe = DataPipe(env_id, self.screenDims, bitmap_format, memory_addresses, pipes_path) 68 | self.dataPipe.open(self.console) 69 | 70 | # Connect inter process communication 71 | self.setup_frame_access_loop() 72 | 73 | self.first = True 74 | 75 | def get_bitmap_format(self): 76 | bitmap_format = self.console.writeln('print(s:bitmap_format())', expect_output=True) 77 | if len(bitmap_format) != 1: 78 | raise IOError('Expected one result from "print(s:bitmap_format())", but received: ', bitmap_format) 79 | try: 80 | return { 81 | "RGB32 - 32bpp 8-8-8 RGB": BitmapFormat.RGB32, 82 | "ARGB32 - 32bpp 8-8-8-8 ARGB": BitmapFormat.ARGB32 83 | }[bitmap_format[0]] 84 | except KeyError: 85 | self.console.close() 86 | raise EnvironmentError("MAMEToolkit only supports RGB32 and ARGB32 frame bit format games") 87 | 88 | def create_lua_variables(self): 89 | self.console.writeln('iop = manager:machine():ioport()') 90 | self.console.writeln('s = manager:machine().screens[":screen"]') 91 | self.console.writeln('mem = manager:machine().devices[":maincpu"].spaces["program"]') 92 | self.console.writeln('releaseQueue = {}') 93 | 94 | def wait_for_resource_registration(self, max_attempts=10): 95 | screen_registered = False 96 | program_registered = False 97 | attempt = 0 98 | while not screen_registered or not program_registered: 99 | if not screen_registered: 100 | result = self.console.writeln('print(manager:machine().screens[":screen"])', expect_output=True, timeout=3, raiseError=False) 101 | screen_registered = result is not None and result is not "nil" 102 | if not program_registered: 103 | result = self.console.writeln('print(manager:machine().devices[":maincpu"].spaces["program"])', expect_output=True, timeout=3, raiseError=False) 104 | program_registered = result is not None and result is not "nil" 105 | if attempt == max_attempts: 106 | raise EnvironmentError("Failed to register MAME resources!") 107 | attempt += 1 108 | 109 | # Gets the game screen width in pixels 110 | def setup_screen_width(self): 111 | output = self.console.writeln('print(s:width())', expect_output=True, timeout=1) 112 | if len(output) != 1: 113 | raise IOError('Expected one result from "print(s:width())", but received: ', output) 114 | return int(output[0]) 115 | 116 | # Gets the game screen height in pixels 117 | def setup_screen_height(self): 118 | output = self.console.writeln('print(s:height())', expect_output=True, timeout=1) 119 | if len(output) != 1: 120 | raise IOError('Expected one result from "print(s:height())"", but received: ', output) 121 | return int(output[0]) 122 | 123 | # Pauses the emulator 124 | def pause_game(self): 125 | self.console.writeln('emu.pause()') 126 | 127 | # Unpauses the emulator 128 | def unpause_game(self): 129 | self.console.writeln('emu.unpause()') 130 | 131 | # Sets up the callback function written in Lua that the Lua engine will execute each time a frame done 132 | def setup_frame_access_loop(self): 133 | pipe_data_func = 'function pipeData() ' \ 134 | 'if (math.fmod(tonumber(s:frame_number()),' + str(self.frame_ratio) +') == 0) then ' \ 135 | 'for i=1,#releaseQueue do ' \ 136 | 'releaseQueue[i](); ' \ 137 | 'releaseQueue[i]=nil; ' \ 138 | 'end; ' \ 139 | '' + self.dataPipe.get_lua_string() + '' \ 140 | 'actions = ' + self.actionPipe.get_lua_string() + '' \ 141 | 'if (string.len(actions) > 1) then ' \ 142 | 'for action in string.gmatch(actions, "[^+]+") do ' \ 143 | 'actionFunc = loadstring(action..":set_value(1)"); ' \ 144 | 'actionFunc(); ' \ 145 | 'releaseFunc = loadstring(action..":set_value(0)"); ' \ 146 | 'table.insert(releaseQueue, releaseFunc); ' \ 147 | 'end; ' \ 148 | 'end; ' \ 149 | 'end; ' \ 150 | 'end' 151 | self.console.writeln(pipe_data_func) 152 | self.console.writeln('emu.register_frame(pipeData, "data")') 153 | 154 | # Steps the emulator along one time step 155 | def step(self, actions): 156 | if self.first: 157 | self.dataPipe.read_data(timeout=10) 158 | self.first = False 159 | action_string = actions_to_string(actions) 160 | self.actionPipe.writeln(action_string) # sends the actions for the game to perform before the next step 161 | data = self.dataPipe.read_data(timeout=10) # gathers the frame data and memory address values 162 | return data 163 | 164 | # Testing 165 | # Safely stops all of the processes related to running the emulator 166 | def close(self): 167 | self.console.close() 168 | self.actionPipe.close() 169 | self.dataPipe.close() 170 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/StreamGobbler.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | # A thread used for reading data from a pipe 5 | # pipes don't have very good time out functionality, so this is used in combination with a queue 6 | class StreamGobbler(threading.Thread): 7 | 8 | def __init__(self, pipe, queue, debug=False): 9 | threading.Thread.__init__(self) 10 | self.pipe = pipe 11 | self.queue = queue 12 | self.debug = debug 13 | self._stop_event = threading.Event() 14 | self.has_cursor = False 15 | 16 | def run(self): 17 | for line in iter(self.pipe.readline, b''): 18 | if self.debug: 19 | print(line) 20 | self.queue.put(line[:-1]) 21 | if self._stop_event.is_set(): 22 | break 23 | 24 | def wait_for_cursor(self): 25 | new_line_count = 0 26 | while new_line_count != 3: 27 | line = self.pipe.readline() 28 | if line == b'\n': 29 | new_line_count += 1 30 | 31 | def stop(self): 32 | self._stop_event.set() 33 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/__init__.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit.emulator.Action import Action 2 | from MAMEToolkit.emulator.Address import Address 3 | from MAMEToolkit.emulator.Emulator import Emulator 4 | from MAMEToolkit.emulator.Emulator import run_cheat_debugger 5 | from MAMEToolkit.emulator.Emulator import see_games 6 | from MAMEToolkit.emulator.Emulator import list_actions 7 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/pipes/DataPipe.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from MAMEToolkit.emulator.pipes import Pipe 3 | from MAMEToolkit.emulator.BitmapFormat import BitmapFormat 4 | 5 | 6 | # A special implementation of a Linux FIFO pipe which is used for reading all of the frame data and memory address values from the emulator 7 | class DataPipe(object): 8 | 9 | def __init__(self, env_id, screen_dims, bitmap_format: BitmapFormat, addresses, pipes_path): 10 | self.pipe = Pipe(env_id, "data", 'r', pipes_path) 11 | self.screenDims = screen_dims 12 | self.bitmap_format = bitmap_format 13 | self.addresses = addresses 14 | 15 | def open(self, console): 16 | self.pipe.open(console) 17 | 18 | def close(self): 19 | self.pipe.close() 20 | 21 | # Generates the equivalent Lua code specifying what data the Lua engine should return every time step 22 | def get_lua_string(self): 23 | return self.pipe.get_lua_string(args=[address.get_lua_string() for address in self.addresses.values()]+['s:bitmap_binary()']) 24 | 25 | def read_data(self, timeout=10): 26 | data = {} 27 | line = self.pipe.readln(timeout=timeout) 28 | cursor = 0 29 | for k in self.addresses.keys(): 30 | cursor_end = cursor 31 | while line[cursor_end] != 43: 32 | cursor_end += 1 33 | part = line[cursor:cursor_end] 34 | data[k] = int(part.decode("utf-8")) 35 | cursor = cursor_end+1 36 | data["frame"] = np.frombuffer(line[cursor:], dtype='uint8').reshape(self.screenDims["height"], self.screenDims["width"], self.bitmap_format.value) 37 | return data 38 | 39 | -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/pipes/Pipe.py: -------------------------------------------------------------------------------- 1 | import os 2 | from MAMEToolkit.emulator.StreamGobbler import StreamGobbler 3 | from pathlib import Path 4 | from queue import Queue 5 | from threading import Thread 6 | import logging 7 | 8 | 9 | def delete_old_pipes(pipes_path): 10 | for the_file in os.listdir(pipes_path): 11 | file_path = os.path.join(pipes_path, the_file) 12 | try: 13 | os.unlink(file_path) 14 | except Exception as e: 15 | print(e) 16 | 17 | 18 | def open_pipe(pipe_queue, path, mode): 19 | pipe_queue.put(open(path, mode + "b")) 20 | 21 | 22 | # A class used for creating and interacting with a Linux FIFO pipe 23 | class Pipe(object): 24 | 25 | def __init__(self, env_id, pipe_id, mode, pipes_path): 26 | self.pipeId = pipe_id + "Pipe" 27 | self.mode = mode 28 | self.pipes_path = Path(pipes_path) 29 | if not self.pipes_path.exists(): 30 | self.pipes_path.mkdir() 31 | self.path = self.pipes_path.joinpath(Path(pipe_id + "-" + str(env_id) + ".pipe")) 32 | self.logger = logging.getLogger("Pipe: "+str(self.path.absolute())) 33 | if self.path.exists(): 34 | self.path.unlink() 35 | os.mkfifo(str(self.path.absolute())) 36 | self.logger.info("Created pipe file") 37 | 38 | # Generates the equivalent Lua code specifying how the Lua engine should use the pipe 39 | # Args are used for specifying which data should be returned to the toolkit at every time step 40 | def get_lua_string(self, args=None): 41 | if self.mode == 'r': 42 | if not args: 43 | raise IOError("Write pipe expects arguments to write") 44 | return self.pipeId+':write('+'.."+"..'.join(args)+'.."\\n"); '+self.pipeId+':flush(); ' 45 | elif self.mode == 'w': 46 | return self.pipeId+':read(); ' 47 | else: 48 | error = "Invalid mode for pipe, '"+self.mode+"'" 49 | self.logger.error(error) 50 | raise IOError(error) 51 | 52 | # Opens the pipe in the toolkit and in the Lua engine 53 | # When a pipe is opened in read mode, it will block the thread until the same pipe is opened in write mode on a different thread 54 | def open(self, console): 55 | try: 56 | lua_mode = 'r' if self.mode == 'w' else 'w' 57 | # Open Console pipe 58 | console.writeln(self.pipeId+' = assert(io.open("'+str(self.path.absolute())+'", "'+lua_mode+'"))') 59 | self.logger.info("Opened lua pipe") 60 | 61 | # Read bytes not strings 62 | pipe_queue = Queue() 63 | open_thread = Thread(target=open_pipe, args=[pipe_queue, str(self.path.absolute()), self.mode]) 64 | open_thread.start() 65 | open_thread.join(timeout=3) 66 | self.fifo = pipe_queue.get(timeout=1) 67 | 68 | self.logger.info("Opened local pipe") 69 | 70 | if self.mode == "r": 71 | self.read_queue = Queue() 72 | StreamGobbler(self.fifo, self.read_queue).start() 73 | except Exception as e: 74 | error = "Failed to open pipe '" + str(self.path.absolute()) + "'" 75 | self.logger.error(error) 76 | raise IOError(error) 77 | 78 | def close(self): 79 | self.fifo.close() 80 | 81 | # Writes to the pipe 82 | def writeln(self, line): 83 | if self.mode == 'w': 84 | self.fifo.write(line.encode("utf-8")+b'\n') 85 | self.fifo.flush() 86 | else: 87 | error = "Attempted to write to '"+str(self.path.absolute())+"' in '"+str(self.mode)+"' mode" 88 | self.logger.error(error) 89 | raise IOError(error) 90 | 91 | # Reads to the pipe 92 | # timeout specifies how long the pipe should wait before there is likely to be a problem on the Lua engines side 93 | def readln(self, timeout=1): 94 | if self.mode == 'r': 95 | try: 96 | return self.read_queue.get(timeout=timeout) 97 | except Exception as e: 98 | error = "Failed to read value from '"+self.pipeId+"'" 99 | self.logger.error(error) 100 | raise IOError(error) 101 | else: 102 | error = "Attempted to read from '"+str(self.path.absolute())+"' in '"+str(self.mode)+"' mode" 103 | self.logger.error(error) 104 | raise IOError(error) -------------------------------------------------------------------------------- /src/MAMEToolkit/emulator/pipes/__init__.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit.emulator.pipes.Pipe import Pipe 2 | from MAMEToolkit.emulator.pipes.DataPipe import DataPipe 3 | -------------------------------------------------------------------------------- /src/MAMEToolkit/sf_environment/Actions.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from MAMEToolkit.emulator import Action 3 | 4 | 5 | # An enumerable class used to specify which actions can be used to interact with a game 6 | # Specifies the Lua engine port and field names required for performing an action 7 | class Actions(Enum): 8 | # Starting 9 | SERVICE = Action(':INPUTS', 'Service Mode') 10 | 11 | COIN_P1 = Action(':INPUTS', 'Coin 1') 12 | COIN_P2 = Action(':INPUTS', 'Coin 2') 13 | 14 | P1_START = Action(':INPUTS', '1 Player Start') 15 | P2_START = Action(':INPUTS', '2 Players Start') 16 | 17 | # Movement 18 | P1_UP = Action(':INPUTS', 'P1 Up') 19 | P1_DOWN = Action(':INPUTS', 'P1 Down') 20 | P1_LEFT = Action(':INPUTS', 'P1 Left') 21 | P1_RIGHT = Action(':INPUTS', 'P1 Right') 22 | 23 | P2_UP = Action(':INPUTS', 'P2 Up') 24 | P2_DOWN = Action(':INPUTS', 'P2 Down') 25 | P2_LEFT = Action(':INPUTS', 'P2 Left') 26 | P2_RIGHT = Action(':INPUTS', 'P2 Right') 27 | 28 | # Fighting 29 | P1_JPUNCH = Action(':INPUTS', 'P1 Jab Punch') 30 | P1_SPUNCH = Action(':INPUTS', 'P1 Strong Punch') 31 | P1_FPUNCH = Action(':INPUTS', 'P1 Fierce Punch') 32 | P1_SKICK = Action(':EXTRA', 'P1 Short Kick') 33 | P1_FKICK = Action(':EXTRA', 'P1 Forward Kick') 34 | P1_RKICK = Action(':EXTRA', 'P1 Roundhouse Kick') 35 | 36 | P2_JPUNCH = Action(':INPUTS', 'P2 Jab Punch') 37 | P2_SPUNCH = Action(':INPUTS', 'P2 Strong Punch') 38 | P2_FPUNCH = Action(':INPUTS', 'P2 Fierce Punch') 39 | P2_SKICK = Action(':EXTRA', 'P2 Short Kick') 40 | P2_FKICK = Action(':EXTRA', 'P2 Forward Kick') 41 | P2_RKICK = Action(':INPUTS', 'P2 Roundhouse Kick') 42 | -------------------------------------------------------------------------------- /src/MAMEToolkit/sf_environment/Environment.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit.emulator import Emulator 2 | from MAMEToolkit.emulator import Address 3 | from MAMEToolkit.sf_environment.Steps import * 4 | from MAMEToolkit.sf_environment.Actions import Actions 5 | 6 | 7 | # Combines the data of multiple time steps 8 | def add_rewards(old_data, new_data): 9 | for k in old_data.keys(): 10 | if "rewards" in k: 11 | for player in old_data[k]: 12 | new_data[k][player] += old_data[k][player] 13 | return new_data 14 | 15 | 16 | # Returns the list of memory addresses required to train on Street Fighter 17 | def setup_memory_addresses(): 18 | return { 19 | "fighting": Address('0x02011389', 'u8'), 20 | "winsP1": Address('0x02011383', 'u8'), 21 | "winsP2": Address('0x02011385', 'u8'), 22 | "healthP1": Address('0x02068D0A', 's16'), 23 | "healthP2": Address('0x020691A2', 's16') 24 | } 25 | 26 | 27 | # Converts and index (action) into the relevant movement action Enum, depending on the player 28 | def index_to_move_action(action): 29 | return { 30 | 0: [Actions.P1_LEFT], 31 | 1: [Actions.P1_LEFT, Actions.P1_UP], 32 | 2: [Actions.P1_UP], 33 | 3: [Actions.P1_UP, Actions.P1_RIGHT], 34 | 4: [Actions.P1_RIGHT], 35 | 5: [Actions.P1_RIGHT, Actions.P1_DOWN], 36 | 6: [Actions.P1_DOWN], 37 | 7: [Actions.P1_DOWN, Actions.P1_LEFT], 38 | 8: [] 39 | }[action] 40 | 41 | 42 | # Converts and index (action) into the relevant attack action Enum, depending on the player 43 | def index_to_attack_action(action): 44 | return { 45 | 0: [Actions.P1_JPUNCH], 46 | 1: [Actions.P1_SPUNCH], 47 | 2: [Actions.P1_FPUNCH], 48 | 3: [Actions.P1_JPUNCH, Actions.P1_SPUNCH], 49 | 4: [Actions.P1_SKICK], 50 | 5: [Actions.P1_FKICK], 51 | 6: [Actions.P1_RKICK], 52 | 7: [Actions.P1_SKICK, Actions.P1_FKICK], 53 | 8: [Actions.P1_JPUNCH, Actions.P1_SKICK], 54 | 9: [] 55 | }[action] 56 | 57 | 58 | # The Street Fighter specific interface for training an agent against the game 59 | class Environment(object): 60 | 61 | # env_id - the unique identifier of the emulator environment, used to create fifo pipes 62 | # difficulty - the difficult to be used in story mode gameplay 63 | # frame_ratio, frames_per_step - see Emulator class 64 | # render, throttle, debug - see Console class 65 | def __init__(self, env_id, roms_path, difficulty=3, frame_ratio=3, frames_per_step=3, render=True, throttle=False, frame_skip=0, sound=False, debug=False, binary_path=None): 66 | self.difficulty = difficulty 67 | self.frame_ratio = frame_ratio 68 | self.frames_per_step = frames_per_step 69 | self.throttle = throttle 70 | self.emu = Emulator(env_id, roms_path, "sfiii3n", setup_memory_addresses(), frame_ratio=frame_ratio, render=render, throttle=throttle, frame_skip=frame_skip, sound=sound, debug=debug, binary_path=binary_path) 71 | self.started = False 72 | self.expected_health = {"P1": 0, "P2": 0} 73 | self.expected_wins = {"P1": 0, "P2": 0} 74 | self.round_done = False 75 | self.stage_done = False 76 | self.game_done = False 77 | self.stage = 1 78 | 79 | # Runs a set of action steps over a series of time steps 80 | # Used for transitioning the emulator through non-learnable gameplay, aka. title screens, character selects 81 | def run_steps(self, steps): 82 | for step in steps: 83 | for i in range(step["wait"]): 84 | self.emu.step([]) 85 | self.emu.step([action.value for action in step["actions"]]) 86 | 87 | # Must be called first after creating this class 88 | # Sends actions to the game until the learnable gameplay starts 89 | # Returns the first few frames of gameplay 90 | def start(self): 91 | if self.throttle: 92 | for i in range(int(250/self.frame_ratio)): 93 | self.emu.step([]) 94 | self.run_steps(set_difficulty(self.frame_ratio, self.difficulty)) 95 | self.run_steps(start_game(self.frame_ratio)) 96 | frames = self.wait_for_fight_start() 97 | self.started = True 98 | return frames 99 | 100 | # Observes the game and waits for the fight to start 101 | def wait_for_fight_start(self): 102 | data = self.emu.step([]) 103 | while data["fighting"] == 0: 104 | data = self.emu.step([]) 105 | self.expected_health = {"P1": data["healthP1"], "P2": data["healthP2"]} 106 | data = self.gather_frames([]) 107 | return data["frame"] 108 | 109 | def reset(self): 110 | if self.game_done: 111 | return self.new_game() 112 | elif self.stage_done: 113 | return self.next_stage() 114 | elif self.round_done: 115 | return self.next_round() 116 | else: 117 | raise EnvironmentError("Reset called while gameplay still running") 118 | 119 | # To be called when a round finishes 120 | # Performs the necessary steps to take the agent to the next round of gameplay 121 | def next_round(self): 122 | self.round_done = False 123 | self.expected_health = {"P1": 0, "P2": 0} 124 | return self.wait_for_fight_start() 125 | 126 | # To be called when a game finishes 127 | # Performs the necessary steps to take the agent(s) to the next game and resets the necessary book keeping variables 128 | def next_stage(self): 129 | self.wait_for_continue() 130 | self.run_steps(next_stage(self.frame_ratio)) 131 | self.expected_health = {"P1": 0, "P2": 0} 132 | self.expected_wins = {"P1": 0, "P2": 0} 133 | self.round_done = False 134 | self.stage_done = False 135 | return self.wait_for_fight_start() 136 | 137 | def new_game(self): 138 | self.wait_for_continue() 139 | self.run_steps(new_game(self.frame_ratio)) 140 | self.expected_health = {"P1": 0, "P2": 0} 141 | self.expected_wins = {"P1": 0, "P2": 0} 142 | self.round_done = False 143 | self.stage_done = False 144 | self.game_done = False 145 | self.stage = 1 146 | return self.wait_for_fight_start() 147 | 148 | # Steps the emulator along until the screen goes black at the very end of a game 149 | def wait_for_continue(self): 150 | data = self.emu.step([]) 151 | if self.frames_per_step == 1: 152 | while data["frame"].sum() != 0: 153 | data = self.emu.step([]) 154 | else: 155 | while data["frame"][0].sum() != 0: 156 | data = self.emu.step([]) 157 | 158 | # Steps the emulator along until the round is definitely over 159 | def run_till_victor(self, data): 160 | while self.expected_wins["P1"] == data["winsP1"] and self.expected_wins["P2"] == data["winsP2"]: 161 | data = add_rewards(data, self.sub_step([])) 162 | self.expected_wins = {"P1":data["winsP1"], "P2":data["winsP2"]} 163 | return data 164 | 165 | # Checks whether the round or game has finished 166 | def check_done(self, data): 167 | if data["fighting"] == 0: 168 | data = self.run_till_victor(data) 169 | self.round_done = True 170 | if data["winsP1"] == 2: 171 | self.stage_done = True 172 | self.stage += 1 173 | if data["winsP2"] == 2: 174 | self.game_done = True 175 | return data 176 | 177 | # Collects the specified amount of frames the agent requires before choosing an action 178 | def gather_frames(self, actions): 179 | data = self.sub_step(actions) 180 | frames = [data["frame"]] 181 | for i in range(self.frames_per_step - 1): 182 | data = add_rewards(data, self.sub_step(actions)) 183 | frames.append(data["frame"]) 184 | data["frame"] = frames[0] if self.frames_per_step == 1 else frames 185 | return data 186 | 187 | # Steps the emulator along by one time step and feeds in any actions that require pressing 188 | # Takes the data returned from the step and updates book keeping variables 189 | def sub_step(self, actions): 190 | data = self.emu.step([action.value for action in actions]) 191 | 192 | p1_diff = (self.expected_health["P1"] - data["healthP1"]) 193 | p2_diff = (self.expected_health["P2"] - data["healthP2"]) 194 | self.expected_health = {"P1": data["healthP1"], "P2": data["healthP2"]} 195 | 196 | rewards = { 197 | "P1": (p2_diff-p1_diff), 198 | "P2": (p1_diff-p2_diff) 199 | } 200 | 201 | data["rewards"] = rewards 202 | return data 203 | 204 | # Steps the emulator along by the requested amount of frames required for the agent to provide actions 205 | def step(self, move_action, attack_action): 206 | if self.started: 207 | if not self.round_done and not self.stage_done and not self.game_done: 208 | actions = [] 209 | actions += index_to_move_action(move_action) 210 | actions += index_to_attack_action(attack_action) 211 | data = self.gather_frames(actions) 212 | data = self.check_done(data) 213 | return data["frame"], data["rewards"], self.round_done, self.stage_done, self.game_done 214 | else: 215 | raise EnvironmentError("Attempted to step while characters are not fighting") 216 | else: 217 | raise EnvironmentError("Start must be called before stepping") 218 | 219 | # Safely closes emulator 220 | def close(self): 221 | self.emu.close() 222 | -------------------------------------------------------------------------------- /src/MAMEToolkit/sf_environment/Steps.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit.sf_environment.Actions import Actions 2 | 3 | # A = Agent 4 | # C = Computer 5 | # H = Human 6 | # An enurable class used to specify the set of action steps required to perform different predefined tasks 7 | # E.g. changing the story mode difficulty, or starting a new game in single player story mode 8 | def set_difficulty(frame_ratio, difficulty): 9 | steps = [ 10 | {"wait": 0, "actions": [Actions.SERVICE]}, 11 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 12 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 13 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 14 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 15 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 16 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 17 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}, 18 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 19 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}] 20 | if (difficulty % 8) < 3: 21 | steps += [{"wait": int(10/frame_ratio), "actions": [Actions.P1_LEFT]} for i in range(3-(difficulty % 8))] 22 | else: 23 | steps += [{"wait": int(10/frame_ratio), "actions": [Actions.P1_RIGHT]} for i in range((difficulty % 8)-3)] 24 | steps += [ 25 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 26 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 27 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 28 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 29 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 30 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 31 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}, 32 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 33 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}, 34 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 35 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 36 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}, 37 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 38 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 39 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_DOWN]}, 40 | {"wait": int(10/frame_ratio), "actions": [Actions.P1_JPUNCH]}] 41 | return steps 42 | 43 | 44 | def start_game(frame_ratio): 45 | return [ 46 | {"wait": int(300/frame_ratio), "actions": [Actions.COIN_P1]}, 47 | {"wait": int(10/frame_ratio), "actions": [Actions.COIN_P1]}, 48 | {"wait": int(60/frame_ratio), "actions": [Actions.P1_START]}, 49 | {"wait": int(80/frame_ratio), "actions": [Actions.P1_LEFT, Actions.P1_JPUNCH]}, 50 | {"wait": int(60/frame_ratio), "actions": [Actions.P1_JPUNCH]}, 51 | {"wait": int(60/frame_ratio), "actions": [Actions.P1_JPUNCH]}] 52 | 53 | 54 | def next_stage(frame_ratio): 55 | return [{"wait": int(60 / frame_ratio), "actions": [Actions.P1_JPUNCH]}] + \ 56 | [{"wait": 0, "actions": [Actions.P1_JPUNCH]} for _ in range(int(180 / frame_ratio))] + \ 57 | [{"wait": int(60/frame_ratio), "actions": [Actions.P1_JPUNCH]}] 58 | 59 | 60 | def new_game(frame_ratio): 61 | return [{"wait": 0, "actions": [Actions.SERVICE]}, 62 | {"wait": int(30 / frame_ratio), "actions": [Actions.P1_UP]}, 63 | {"wait": int(30 / frame_ratio), "actions": [Actions.P1_JPUNCH]}, 64 | {"wait": int(300 / frame_ratio), "actions": [Actions.COIN_P1]}, 65 | {"wait": int(10 / frame_ratio), "actions": [Actions.COIN_P1]}, 66 | {"wait": int(60 / frame_ratio), "actions": [Actions.P1_START]}, 67 | {"wait": int(80 / frame_ratio), "actions": [Actions.P1_LEFT, Actions.P1_JPUNCH]}, 68 | {"wait": int(60 / frame_ratio), "actions": [Actions.P1_JPUNCH]}, 69 | {"wait": int(60 / frame_ratio), "actions": [Actions.P1_JPUNCH]}] 70 | -------------------------------------------------------------------------------- /src/MAMEToolkit/sf_environment/__init__.py: -------------------------------------------------------------------------------- 1 | from MAMEToolkit.sf_environment.Environment import Environment 2 | from MAMEToolkit.sf_environment import Steps 3 | from MAMEToolkit.sf_environment.Actions import Actions 4 | -------------------------------------------------------------------------------- /test/emulator/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M-J-Murray/MAMEToolkit/3fb35a2088302fd0632b9d7c1bf5690f6a06694c/test/emulator/__init__.py -------------------------------------------------------------------------------- /test/emulator/pipes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/M-J-Murray/MAMEToolkit/3fb35a2088302fd0632b9d7c1bf5690f6a06694c/test/emulator/pipes/__init__.py -------------------------------------------------------------------------------- /test/emulator/pipes/test_data_pipe.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | from threading import Thread 4 | from queue import Queue as DefaultQueue 5 | 6 | from src.MAMEToolkit.emulator.pipes import DataPipe 7 | from src.MAMEToolkit.emulator import Address 8 | from src.MAMEToolkit.emulator.BitmapFormat import BitmapFormat 9 | from multiprocessing import get_start_method, set_start_method, Process, Queue as MPQueue 10 | 11 | import os 12 | os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) 13 | 14 | 15 | def setup_data_pipe(data_pipe): 16 | console = MockConsole(data_pipe.pipe) 17 | data_pipe.open(console) 18 | console.open_thread.join(timeout=0.1) 19 | assert_that(console.open_thread.is_alive(), equal_to(False)) 20 | return console.results.get(timeout=0.1) 21 | 22 | 23 | def open_pipe(path, mode, queue): 24 | queue.put(open(path, mode)) 25 | 26 | 27 | def close_pipes(pipe1, pipe2): 28 | close_thread = Thread(target=pipe1.close) 29 | close_thread.start() 30 | pipe2.close() 31 | close_thread.join(timeout=0.1) 32 | 33 | 34 | def run_read(output_pipe): 35 | bitmap_format = BitmapFormat.RGB32 36 | addresses = {"test1": Address("0x00000000", "u8"), "test2": Address("0x00000001", "u16")} 37 | screen_dims = {"width": 1, "height": 1} 38 | data_pipe = DataPipe("env1", screen_dims, bitmap_format, addresses, "mame/pipes/") 39 | write_pipe = setup_data_pipe(data_pipe) 40 | write_pipe.write("1+2+abc\n") 41 | write_pipe.flush() 42 | 43 | output_pipe.put(data_pipe.read_data()) 44 | 45 | 46 | class MockConsole(object): 47 | 48 | def __init__(self, test_pipe): 49 | self.test_pipe = test_pipe 50 | self.results = DefaultQueue() 51 | self.open_thread = None 52 | 53 | def writeln(self, line): 54 | lua_mode = 'r' if self.test_pipe.mode == 'w' else 'w' 55 | assert_that(line, equal_to(self.test_pipe.pipeId + ' = assert(io.open("' + str(self.test_pipe.path.absolute()) + '", "' + lua_mode + '"))')) 56 | self.open_thread = Thread(target=open_pipe, args=[self.test_pipe.path, lua_mode, self.results]) 57 | self.open_thread.start() 58 | 59 | 60 | class DataPipeTest(unittest.TestCase): 61 | 62 | @classmethod 63 | def setUpClass(cls): 64 | cls.tearDownClass() 65 | 66 | @classmethod 67 | def tearDownClass(cls): 68 | files = os.listdir("mame/pipes/") 69 | if len(files) > 0: 70 | for f in files: 71 | os.remove("mame/pipes/"+f) 72 | 73 | def test_empty_lua_string(self): 74 | data_pipe, write_pipe = [None, None] 75 | try: 76 | bitmap_format = BitmapFormat.RGB32 77 | addresses = {} 78 | screen_dims = {"width": 1, "height": 1} 79 | data_pipe = DataPipe("env1", screen_dims, bitmap_format, addresses, "mame/pipes") 80 | write_pipe = setup_data_pipe(data_pipe) 81 | write_pipe.write("1+2+abc\n") 82 | write_pipe.flush() 83 | 84 | assert_that(data_pipe.get_lua_string(), equal_to('dataPipe:write(s:bitmap_binary().."\\n"); dataPipe:flush(); ')) 85 | finally: 86 | close_pipes(data_pipe, write_pipe) 87 | 88 | def test_lua_string(self): 89 | data_pipe, write_pipe = [None, None] 90 | try: 91 | bitmap_format = BitmapFormat.RGB32 92 | addresses = {"test1": Address("0x00000000", "u8"), "test2": Address("0x00000001", "u16")} 93 | screen_dims = {"width": 1, "height": 1} 94 | data_pipe = DataPipe("env1", screen_dims, bitmap_format, addresses, "mame/pipes") 95 | write_pipe = setup_data_pipe(data_pipe) 96 | write_pipe.write("1+2+abc\n") 97 | write_pipe.flush() 98 | 99 | assert_that(data_pipe.get_lua_string(), equal_to('dataPipe:write(mem:read_u8(0x00000000).."+"..mem:read_u16(0x00000001).."+"..s:bitmap_binary().."\\n"); dataPipe:flush(); ')) 100 | finally: 101 | close_pipes(data_pipe, write_pipe) 102 | 103 | def test_read_data(self): 104 | data_pipe, write_pipe = [None, None] 105 | try: 106 | bitmap_format = BitmapFormat.RGB32 107 | addresses = {"test1": Address("0x00000000", "u8"), "test2": Address("0x00000001", "u16")} 108 | screen_dims = {"width": 1, "height": 1} 109 | data_pipe = DataPipe("env1", screen_dims, bitmap_format, addresses, "mame/pipes") 110 | write_pipe = setup_data_pipe(data_pipe) 111 | write_pipe.write("1+2+abc\n") 112 | write_pipe.flush() 113 | 114 | data = data_pipe.read_data() 115 | assert_that(len(data), is_(equal_to(3))) 116 | assert_that(data["frame"][0][0][0], is_(equal_to(97))) 117 | assert_that(data["frame"][0][0][1], is_(equal_to(98))) 118 | assert_that(data["frame"][0][0][2], is_(equal_to(99))) 119 | assert_that(data["test1"], is_(equal_to(1))) 120 | assert_that(data["test2"], is_(equal_to(2))) 121 | finally: 122 | close_pipes(data_pipe, write_pipe) 123 | 124 | def test_read_data_multiprocessing(self): 125 | if get_start_method(True) != "spawn": 126 | set_start_method("spawn") 127 | workers = 1 128 | output_queue = MPQueue() 129 | processes = [Process(target=run_read, args=[output_queue]) for i in range(workers)] 130 | [process.start() for process in processes] 131 | [process.join() for process in processes] 132 | for i in range(workers): 133 | data = output_queue.get(timeout=0.1) 134 | assert_that(data["frame"][0][0][0], is_(equal_to(97))) 135 | assert_that(data["frame"][0][0][1], is_(equal_to(98))) 136 | assert_that(data["frame"][0][0][2], is_(equal_to(99))) 137 | assert_that(data["test1"], is_(equal_to(1))) 138 | assert_that(data["test2"], is_(equal_to(2))) -------------------------------------------------------------------------------- /test/emulator/pipes/test_pipe.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | from threading import Thread 4 | from queue import Queue as DefaultQueue 5 | from multiprocessing import set_start_method, get_start_method, Process, Queue as MPQueue 6 | 7 | from src.MAMEToolkit.emulator.pipes import Pipe 8 | 9 | import os 10 | os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) 11 | 12 | 13 | def setup_pipe(pipe): 14 | console = MockConsole(pipe) 15 | pipe.open(console) 16 | console.openThread.join(timeout=0.1) 17 | assert_that(console.openThread.is_alive(), equal_to(False)) 18 | return console.results.get() 19 | 20 | 21 | def open_pipe(path, mode, queue): 22 | queue.put(open(path,mode)) 23 | 24 | 25 | def close_pipes(pipe1, pipe2): 26 | closeThread = Thread(target=pipe1.close) 27 | closeThread.start() 28 | pipe2.close() 29 | closeThread.join(timeout=0.1) 30 | 31 | 32 | def setup_all_pipes(): 33 | write_pipe = Pipe("env1", "write", 'w', "mame/pipes") 34 | lua_read_pipe = setup_pipe(write_pipe) 35 | 36 | read_pipe = Pipe("env1", "read", 'r', "mame/pipes") 37 | lua_write_pipe = setup_pipe(read_pipe) 38 | 39 | return write_pipe, lua_read_pipe, read_pipe, lua_write_pipe 40 | 41 | 42 | def run_write(output_queue): 43 | write_pipe, lua_read_pipe = [None, None] 44 | try: 45 | write_pipe = Pipe("env1", "write", 'w', "mame/pipes") 46 | lua_read_pipe = setup_pipe(write_pipe) 47 | 48 | write_pipe.writeln("test") 49 | output_queue.put(lua_read_pipe.readline()) 50 | finally: 51 | close_pipes(write_pipe, lua_read_pipe) 52 | 53 | 54 | def run_read(output_queue): 55 | read_pipe, lua_write_pipe = [None, None] 56 | try: 57 | read_pipe = Pipe("env1", "read", 'r', "mame/pipes") 58 | lua_write_pipe = setup_pipe(read_pipe) 59 | 60 | lua_write_pipe.write("test\n") 61 | lua_write_pipe.flush() 62 | output_queue.put(read_pipe.readln(timeout=1)) 63 | finally: 64 | close_pipes(read_pipe, lua_write_pipe) 65 | 66 | 67 | class MockConsole(object): 68 | 69 | def __init__(self, testPipe): 70 | self.testPipe = testPipe 71 | self.results = DefaultQueue() 72 | 73 | def writeln(self, line): 74 | luaMode = 'r' if self.testPipe.mode == 'w' else 'w' 75 | assert_that(line, equal_to(self.testPipe.pipeId+' = assert(io.open("'+str(self.testPipe.path.absolute())+'", "'+luaMode+'"))')) 76 | self.openThread = Thread(target=open_pipe, args=[self.testPipe.path, luaMode, self.results]) 77 | self.openThread.start() 78 | 79 | 80 | # pipes must be opened simultaneously 81 | class PipeTest(unittest.TestCase): 82 | 83 | @classmethod 84 | def setUpClass(cls): 85 | if get_start_method(True) != "spawn": 86 | set_start_method("spawn") 87 | cls.tearDownClass() 88 | 89 | @classmethod 90 | def tearDownClass(cls): 91 | files = os.listdir("mame/pipes/") 92 | if len(files) > 0: 93 | for f in files: 94 | os.remove("mame/pipes/"+f) 95 | 96 | def test_write(self): 97 | write_pipe, lua_read_pipe = [None, None] 98 | try: 99 | write_pipe = Pipe("env1", "write", 'w', "mame/pipes") 100 | lua_read_pipe = setup_pipe(write_pipe) 101 | 102 | write_pipe.writeln("test") 103 | assert_that(lua_read_pipe.readline(), equal_to("test\n")) 104 | finally: 105 | close_pipes(write_pipe, lua_read_pipe) 106 | 107 | def test_read(self): 108 | read_pipe, lua_write_pipe = [None, None] 109 | try: 110 | read_pipe = Pipe("env1", "read", 'r', "mame/pipes") 111 | lua_write_pipe = setup_pipe(read_pipe) 112 | 113 | lua_write_pipe.write("test\n") 114 | lua_write_pipe.flush() 115 | assert_that(read_pipe.readln(timeout=0.1), equal_to(b"test")) 116 | finally: 117 | close_pipes(read_pipe, lua_write_pipe) 118 | 119 | def test_readln_empty(self): 120 | read_pipe, lua_write_pipe = [None, None] 121 | try: 122 | read_pipe = Pipe("env1", "read", 'r', "mame/pipes") 123 | lua_write_pipe = setup_pipe(read_pipe) 124 | 125 | with self.assertRaises(IOError) as context: 126 | read_pipe.readln(timeout=0.1) 127 | 128 | assert_that(str(context.exception), contains_string("Failed to read value from 'readPipe'")) 129 | finally: 130 | close_pipes(read_pipe, lua_write_pipe) 131 | 132 | def test_read_from_write_pipe(self): 133 | write_pipe, lua_read_pipe = [None, None] 134 | try: 135 | write_pipe = Pipe("env1", "write", 'w', "mame/pipes") 136 | lua_read_pipe = setup_pipe(write_pipe) 137 | 138 | with self.assertRaises(IOError) as context: 139 | write_pipe.readln() 140 | 141 | assert_that(str(context.exception), contains_string("Attempted to read from '/home/michael/dev/MAMEToolkit/test/emulator/mame/pipes/write-env1.pipe' in 'w' mode")) 142 | 143 | finally: 144 | close_pipes(write_pipe, lua_read_pipe) 145 | 146 | def test_write_to_read_pipe(self): 147 | read_pipe, lua_write_pipe = [None, None] 148 | try: 149 | read_pipe = Pipe("env1", "read", 'r', "mame/pipes") 150 | lua_write_pipe = setup_pipe(read_pipe) 151 | 152 | with self.assertRaises(IOError) as context: 153 | read_pipe.writeln("TEST") 154 | 155 | assert_that(str(context.exception), contains_string("Attempted to write to '/home/michael/dev/MAMEToolkit/test/emulator/mame/pipes/read-env1.pipe' in 'r' mode")) 156 | 157 | finally: 158 | close_pipes(read_pipe, lua_write_pipe) 159 | 160 | def test_lua_string(self): 161 | write_pipe, lua_read_pipe, read_pipe, lua_write_pipe = [None, None, None, None] 162 | try: 163 | write_pipe, lua_read_pipe, read_pipe, lua_write_pipe = setup_all_pipes() 164 | 165 | assert_that(read_pipe.get_lua_string(args=["test"]), equal_to('readPipe:write(test.."\\n"); readPipe:flush(); ')) 166 | assert_that(write_pipe.get_lua_string(), equal_to("writePipe:read(); ")) 167 | finally: 168 | close_pipes(write_pipe, lua_read_pipe) 169 | close_pipes(read_pipe, lua_write_pipe) 170 | 171 | def test_multiprocessing_read(self): 172 | workers = 4 173 | output_queue = MPQueue() 174 | processes = [Process(target=run_read, args=[output_queue]) for i in range(workers)] 175 | [process.start() for process in processes] 176 | [process.join() for process in processes] 177 | for i in range(workers): 178 | assert_that(output_queue.get(timeout=0.1), equal_to(b"test")) 179 | 180 | def test_multiprocessing_write(self): 181 | workers = 4 182 | output_queue = MPQueue() 183 | processes = [Process(target=run_write, args=[output_queue]) for i in range(workers)] 184 | [process.start() for process in processes] 185 | [process.join() for process in processes] 186 | for i in range(workers): 187 | assert_that(output_queue.get(timeout=0.1), equal_to("test\n")) 188 | -------------------------------------------------------------------------------- /test/emulator/test_address.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | from src.MAMEToolkit.emulator import Address 4 | 5 | 6 | class TestAddress(unittest.TestCase): 7 | 8 | def test_lua_string(self): 9 | assert_that(Address('test','u8').get_lua_string(), equal_to('mem:read_u8(test)')) 10 | assert_that(Address('test','u16').get_lua_string(), equal_to('mem:read_u16(test)')) 11 | assert_that(Address('test','u32').get_lua_string(), equal_to('mem:read_u32(test)')) 12 | assert_that(Address('test','s8').get_lua_string(), equal_to('mem:read_i8(test)')) 13 | assert_that(Address('test','s16').get_lua_string(), equal_to('mem:read_i16(test)')) 14 | assert_that(Address('test','s32').get_lua_string(), equal_to('mem:read_i32(test)')) 15 | 16 | def test_invalid_lua_string(self): 17 | with self.assertRaises(Exception) as context: 18 | Address('test','INVALID').get_lua_string(), 19 | assert_that(str(context.exception), contains_string('Invalid address mode used')) -------------------------------------------------------------------------------- /test/emulator/test_console.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | from time import sleep 4 | from multiprocessing import set_start_method, get_start_method, Process, Queue 5 | from src.MAMEToolkit.emulator.Console import Console 6 | 7 | import os 8 | del os.environ["FONTCONFIG_PATH"] 9 | 10 | 11 | def run_console(game_id, output_queue): 12 | console = None 13 | try: 14 | console = Console("/home/michael/dev/MAMEToolkit/src/MAMEToolkit/emulator/mame/roms", game_id, binary_path="../../binary/mame") 15 | sleep(5) 16 | console.writeln('s = manager:machine().screens[":screen"]') 17 | output = console.writeln('print(s:width())', expect_output=True) 18 | output_queue.put(output[0]) 19 | finally: 20 | console.close() 21 | 22 | 23 | class ConsoleTest(unittest.TestCase): 24 | 25 | def test_write_read(self): 26 | game_id = "sfiii3n" 27 | console = None 28 | try: 29 | console = Console("/home/michael/dev/MAMEToolkit/src/MAMEToolkit/emulator/mame/roms", game_id, binary_path="../../binary/mame") 30 | sleep(5) 31 | console.writeln('s = manager:machine().screens[":screen"]') 32 | output = console.writeln('print(s:width())', expect_output=True) 33 | assert_that(output[0], equal_to("384")) 34 | finally: 35 | console.close() 36 | 37 | def test_multiprocessing(self): 38 | if get_start_method(True) != "spawn": 39 | set_start_method("spawn") 40 | workers = 10 41 | game_id = "sfiii3n" 42 | output_queue = Queue() 43 | processes = [Process(target=run_console, args=[game_id, output_queue]) for i in range(workers)] 44 | [process.start() for process in processes] 45 | [process.join() for process in processes] 46 | for i in range(workers): 47 | assert_that(output_queue.get(timeout=0.1), equal_to("384")) 48 | -------------------------------------------------------------------------------- /test/emulator/test_emulator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | 4 | from src.MAMEToolkit.emulator import Emulator 5 | from src.MAMEToolkit.emulator import Address 6 | from multiprocessing import Process, Queue 7 | from time import sleep 8 | 9 | import os 10 | del os.environ["FONTCONFIG_PATH"] 11 | 12 | 13 | def run_emulator(env_id, roms_path, game_id, memory_addresses, output_queue): 14 | emulator = None 15 | try: 16 | emulator = Emulator(env_id, roms_path, game_id, memory_addresses, binary_path="../../binary/mame") 17 | output_queue.put(emulator.step([])) 18 | finally: 19 | emulator.close() 20 | 21 | 22 | class EmulatorTest(unittest.TestCase): 23 | 24 | def test_screen_dimensions(self): 25 | memory_addresses = {"test": Address("02000008", "u8")} 26 | game_id = "sfiii3n" 27 | roms_path = "/home/michael/dev/MAMEToolkit/src/MAMEToolkit/emulator/mame/roms" 28 | emulator = None 29 | try: 30 | emulator = Emulator("testEnv1", roms_path, game_id, memory_addresses, binary_path="../../binary/mame") 31 | assert_that(emulator.screenDims["width"], equal_to(384)) 32 | assert_that(emulator.screenDims["height"], equal_to(224)) 33 | finally: 34 | emulator.close() 35 | 36 | def test_step(self): 37 | memory_addresses = {"test": Address("02000008", "u8")} 38 | game_id = "sfiii3n" 39 | roms_path = "/home/michael/dev/MAMEToolkit/src/MAMEToolkit/emulator/mame/roms" 40 | emulator = None 41 | try: 42 | emulator = Emulator("testEnv1", roms_path, game_id, memory_addresses, binary_path="../../binary/mame") 43 | data = emulator.step([]) 44 | assert_that(data["frame"].shape, equal_to((224, 384, 3))) 45 | assert_that(data["test"], equal_to(0)) 46 | finally: 47 | emulator.close() 48 | 49 | def test_multiprocessing(self): 50 | workers = 2 51 | game_id = "sfiii3n" 52 | roms_path = "/home/michael/dev/MAMEToolkit/src/MAMEToolkit/emulator/mame/roms" 53 | memory_addresses = {"test": Address("02000008", "u8")} 54 | output_queue = Queue() 55 | processes = [Process(target=run_emulator, args=[f"testEnv{i}", roms_path, game_id, memory_addresses, output_queue]) for i in range(workers)] 56 | [process.start() for process in processes] 57 | sleep(14) 58 | [process.join(timeout=1) for process in processes] 59 | for i in range(workers): 60 | data = output_queue.get(timeout=0.1) 61 | assert_that(data["frame"].shape, equal_to((224, 384, 3))) 62 | assert_that(data["test"], equal_to(0)) 63 | -------------------------------------------------------------------------------- /test/emulator/test_stream_gobbler.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hamcrest import * 3 | from src.MAMEToolkit.emulator.StreamGobbler import StreamGobbler 4 | from multiprocessing import get_start_method, set_start_method, Process, Queue 5 | import queue 6 | 7 | 8 | def run_gobbler(lines, output_queue): 9 | pipe = MockPipe(lines) 10 | line_queue = queue.Queue() 11 | gobbler = None 12 | try: 13 | gobbler = StreamGobbler(pipe, line_queue) 14 | gobbler.wait_for_cursor() 15 | gobbler.start() 16 | for _ in range(3): 17 | output_queue.put(line_queue.get(timeout=0.1)) 18 | finally: 19 | gobbler.stop() 20 | 21 | 22 | class MockPipe(object): 23 | 24 | def __init__(self, lines): 25 | self.lines = lines 26 | self.index = 0 27 | 28 | def readline(self): 29 | if self.index < 3: 30 | line = b"\n" 31 | else: 32 | line = self.lines[self.index % 3] 33 | self.index += 1 34 | return line 35 | 36 | 37 | class StreamGobblerTest(unittest.TestCase): 38 | 39 | def test_read_lines(self): 40 | lines = [b"test1\n", b"test2\n", b"test3\n"] 41 | pipe = MockPipe(lines) 42 | line_queue = queue.Queue() 43 | gobbler = None 44 | try: 45 | gobbler = StreamGobbler(pipe, line_queue, debug=True) 46 | gobbler.wait_for_cursor() 47 | gobbler.start() 48 | for i in range(3): 49 | assert_that(line_queue.get(timeout=0.1), is_(equal_to(lines[i][:-1]))) 50 | finally: 51 | gobbler.stop() 52 | 53 | def test_multiprocessing(self): 54 | if get_start_method(True) != "spawn": 55 | set_start_method("spawn") 56 | workers = 2 57 | lines = [b"test1\n", b"test2\n", b"test3\n"] 58 | output_queue = Queue() 59 | processes = [Process(target=run_gobbler, args=[lines, output_queue]) for i in range(workers)] 60 | [process.start() for process in processes] 61 | [process.join() for process in processes] 62 | for _ in range(workers): 63 | for j in range(3): 64 | assert_that(output_queue.get(timeout=0.1), is_(equal_to(lines[j][:-1]))) 65 | -------------------------------------------------------------------------------- /travis/build-mame.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | yum install wget qt5-qtbase qt5-qtbase-devel alsa-lib alsa-lib-devel alsa-plugins-pulseaudioy freetype freetype-devel fontconfig fontconfig-devel libX11 libX11-devel libXi libXi-devel libXinerama libXinerama-devel 4 | 5 | # SDL2 6 | cd ~/ 7 | wget https://www.libsdl.org/release/SDL2-2.0.4.tar.gz 8 | tar -zxvf SDL2-2.0.4.tar.gz 9 | rm -fr SDL2-2.0.4.tar.gz 10 | cd SDL2-2.0.4 11 | mkdir build 12 | cd build 13 | ../configure 14 | make -j4 15 | make install 16 | 17 | # SDL-ttf2 18 | cd ~/ 19 | wget https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.14.tar.gz 20 | tar -zxvf SDL2_ttf-2.0.14.tar.gz 21 | rm -fr SDL2_ttf-2.0.14.tar.gz 22 | cd SDL2_ttf-2.0.14 23 | mkdir build 24 | cd build 25 | ../configure 26 | make -j4 27 | make install 28 | 29 | cd /io/ 30 | git clone https://github.com/M-J-Murray/mame 31 | cd mame 32 | make SUBTARGET=arcade -j4 33 | mkdir -p /io/binary 34 | cp mamearcade64 /io/binary/mame 35 | 36 | # python3 path /opt/python/cp3*/bin --------------------------------------------------------------------------------