-
Notifications
You must be signed in to change notification settings - Fork 538
Expand file tree
/
Copy pathindex.html
More file actions
3680 lines (3255 loc) · 161 KB
/
Copy pathindex.html
File metadata and controls
3680 lines (3255 loc) · 161 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>pyboy API documentation</title>
<meta name="description" content="" />
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:0.8em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script async src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS_CHTML'></script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>pyboy</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">#
# License: See LICENSE.md file
# GitHub: https://github.com/Baekalfen/PyBoy
#
__pdoc__ = {
"core": False,
"logging": False,
"pyboy": False,
"conftest": False,
}
__all__ = ["PyBoy", "PyBoyMemoryView", "PyBoyRegisterFile"]
from .pyboy import PyBoy, PyBoyMemoryView, PyBoyRegisterFile</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="pyboy.api" href="api/index.html">pyboy.api</a></code></dt>
<dd>
<section class="desc"><p>Tools to help interfacing with the Game Boy hardware</p></section>
</dd>
<dt><code class="name"><a title="pyboy.plugins" href="plugins/index.html">pyboy.plugins</a></code></dt>
<dd>
<section class="desc"><p>Plugins that extend PyBoy's functionality. The only publicly exposed, are the game wrappers.</p></section>
</dd>
<dt><code class="name"><a title="pyboy.utils" href="utils.html">pyboy.utils</a></code></dt>
<dd>
<section class="desc"></section>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="pyboy.PyBoy"><code class="flex name class">
<span>class <span class="ident">PyBoy</span></span>
<span>(</span><span>gamerom, *, window='SDL2', scale=3, symbols=None, bootrom=None, sound=False, sound_emulated=False, cgb=None, log_level='ERROR', **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>PyBoy is loadable as an object in Python. This means, it can be initialized from another script, and be
controlled and probed by the script. It is supported to spawn multiple emulators, just instantiate the class
multiple times.</p>
<p>A range of methods are exposed, which should allow for complete control of the emulator. Please open an issue on
GitHub, if other methods are needed for your projects. Take a look at the files in <code>examples/</code> for a crude
"bots", which interact with the game.</p>
<p>Only the <code>gamerom</code> argument is required.</p>
<p>Example:</p>
<pre><code class="language-python">>>> pyboy = PyBoy('game_rom.gb')
>>> for _ in range(60): # Use 'while True:' for infinite
... pyboy.tick()
True...
>>> pyboy.stop()
</code></pre>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>gamerom</code></strong> : <code>str</code></dt>
<dd>Filepath to a game-ROM for Game Boy or Game Boy Color.</dd>
</dl>
<h2 id="kwargs">Kwargs</h2>
<ul>
<li>window (str): "SDL2", "OpenGL", or "null"</li>
<li>scale (int): Window scale factor. Doesn't apply to API.</li>
<li>symbols (str): Filepath to a .sym file to use. If unsure, specify <code>None</code>.</li>
<li>bootrom (str): Filepath to a boot-ROM to use. If unsure, specify <code>None</code>.</li>
<li>sound (bool): Enable sound emulation and output.</li>
<li>sound_emulated (bool): Enable sound emulation without any output. Used for compatibility.</li>
<li>cgb (bool): Forcing Game Boy Color mode.</li>
<li>log_level (str): "CRITICAL", "ERROR", "WARNING", "INFO" or "DEBUG"</li>
<li>color_palette (tuple): Specify the color palette to use for rendering.</li>
<li>cgb_color_palette (list of tuple): Specify the color palette to use for rendering in CGB-mode for non-color games.</li>
</ul>
<p>Other keyword arguments may exist for plugins that are not listed here. They can be viewed by running <code>pyboy --help</code> in the terminal.</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class PyBoy:
def __init__(
self,
gamerom,
*,
window=defaults["window"],
scale=defaults["scale"],
symbols=None,
bootrom=None,
sound=False,
sound_emulated=False,
cgb=None,
log_level=defaults["log_level"],
**kwargs
):
"""
PyBoy is loadable as an object in Python. This means, it can be initialized from another script, and be
controlled and probed by the script. It is supported to spawn multiple emulators, just instantiate the class
multiple times.
A range of methods are exposed, which should allow for complete control of the emulator. Please open an issue on
GitHub, if other methods are needed for your projects. Take a look at the files in `examples/` for a crude
"bots", which interact with the game.
Only the `gamerom` argument is required.
Example:
```python
>>> pyboy = PyBoy('game_rom.gb')
>>> for _ in range(60): # Use 'while True:' for infinite
... pyboy.tick()
True...
>>> pyboy.stop()
```
Args:
gamerom (str): Filepath to a game-ROM for Game Boy or Game Boy Color.
Kwargs:
* window (str): "SDL2", "OpenGL", or "null"
* scale (int): Window scale factor. Doesn't apply to API.
* symbols (str): Filepath to a .sym file to use. If unsure, specify `None`.
* bootrom (str): Filepath to a boot-ROM to use. If unsure, specify `None`.
* sound (bool): Enable sound emulation and output.
* sound_emulated (bool): Enable sound emulation without any output. Used for compatibility.
* cgb (bool): Forcing Game Boy Color mode.
* log_level (str): "CRITICAL", "ERROR", "WARNING", "INFO" or "DEBUG"
* color_palette (tuple): Specify the color palette to use for rendering.
* cgb_color_palette (list of tuple): Specify the color palette to use for rendering in CGB-mode for non-color games.
Other keyword arguments may exist for plugins that are not listed here. They can be viewed by running `pyboy --help` in the terminal.
"""
self.initialized = False
if "bootrom_file" in kwargs:
logger.error(
"Deprecated use of 'bootrom_file'. Use 'bootrom' keyword argument instead. https://github.com/Baekalfen/PyBoy/wiki/Migrating-from-v1.x.x-to-v2.0.0"
)
bootrom = kwargs.pop("bootrom_file")
if "window_type" in kwargs:
logger.error(
"Deprecated use of 'window_type'. Use 'window' keyword argument instead. https://github.com/Baekalfen/PyBoy/wiki/Migrating-from-v1.x.x-to-v2.0.0"
)
window = kwargs.pop("window_type")
if window not in ["SDL2", "OpenGL", "null", "headless", "dummy"]:
raise KeyError(f'Unknown window type: {window}. Use "SDL2", "OpenGL", or "null"')
kwargs["window"] = window
kwargs["scale"] = scale
randomize = kwargs.pop("randomize", False) # Undocumented feature
for k, v in defaults.items():
if k not in kwargs:
kwargs[k] = v
_log_level(log_level)
if gamerom is None:
raise FileNotFoundError(f"None is not a ROM file!")
if not os.path.isfile(gamerom):
raise FileNotFoundError(f"ROM file {gamerom} was not found!")
self.gamerom = gamerom
self.rom_symbols = {}
self.rom_symbols_inverse = {}
if symbols is not None:
if not os.path.isfile(symbols):
raise FileNotFoundError(f"Symbols file {symbols} was not found!")
self.symbols_file = symbols
self._load_symbols()
self.mb = Motherboard(
gamerom,
bootrom,
kwargs["color_palette"],
kwargs["cgb_color_palette"],
sound,
sound_emulated,
cgb,
randomize=randomize,
)
# Validate all kwargs
plugin_manager_keywords = []
for x in parser_arguments():
if not x:
continue
plugin_manager_keywords.extend(z.strip("-").replace("-", "_") for y in x for z in y[:-1])
for k, v in kwargs.items():
if k not in defaults and k not in plugin_manager_keywords:
logger.error("Unknown keyword argument: %s", k)
raise KeyError(f"Unknown keyword argument: {k}")
# Performance measures
self.avg_pre = 0
self.avg_tick = 0
self.avg_post = 0
# Absolute frame count of the emulation
self.frame_count = 0
self.set_emulation_speed(1)
self.paused = False
self.events = []
self.queued_input = []
self.quitting = False
self.stopped = False
self.window_title = "PyBoy"
###################
# API attributes
self.screen = Screen(self.mb)
"""
Use this method to get a `pyboy.api.screen.Screen` object. This can be used to get the screen buffer in
a variety of formats.
It's also here you can find the screen position (SCX, SCY, WX, WY) for each scan line in the screen buffer. See
`pyboy.api.screen.Screen.tilemap_position_list` for more information.
Example:
```python
>>> pyboy.screen.image.show()
>>> pyboy.screen.ndarray.shape
(144, 160, 4)
>>> pyboy.screen.raw_buffer_format
'RGBA'
```
Returns
-------
`pyboy.api.screen.Screen`:
A Screen object with helper functions for reading the screen buffer.
"""
self.memory = PyBoyMemoryView(self.mb)
"""
Provides a `pyboy.PyBoyMemoryView` object for reading and writing the memory space of the Game Boy.
For a more comprehensive description, see the `pyboy.PyBoyMemoryView` class.
Example:
```python
>>> pyboy.memory[0x0000:0x0010] # Read 16 bytes from ROM bank 0
[49, 254, 255, 33, 0, 128, 175, 34, 124, 254, 160, 32, 249, 6, 48, 33]
>>> pyboy.memory[1, 0x2000] = 12 # Override address 0x2000 from ROM bank 1 with the value 12
>>> pyboy.memory[0xC000] = 1 # Write to address 0xC000 with value 1
```
"""
self.register_file = PyBoyRegisterFile(self.mb.cpu)
"""
Provides a `pyboy.PyBoyRegisterFile` object for reading and writing the CPU registers of the Game Boy.
The register file is best used inside the callback of a hook, as `PyBoy.tick` doesn't return at a specific point.
For a more comprehensive description, see the `pyboy.PyBoyRegisterFile` class.
Example:
```python
>>> def my_callback(register_file):
... print("Register A:", register_file.A)
>>> pyboy.hook_register(0, 0x100, my_callback, pyboy.register_file)
>>> pyboy.tick(70)
Register A: 1
True
```
"""
self.memory_scanner = MemoryScanner(self)
"""
Provides a `pyboy.api.memory_scanner.MemoryScanner` object for locating addresses of interest in the memory space
of the Game Boy. This might require some trial and error. Values can be represented in memory in surprising ways.
_Open an issue on GitHub if you need finer control, and we will take a look at it._
Example:
```python
>>> current_score = 4 # You write current score in game
>>> pyboy.memory_scanner.scan_memory(current_score, start_addr=0xC000, end_addr=0xDFFF)
[]
>>> for _ in range(175):
... pyboy.tick(1, True) # Progress the game to change score
True...
>>> current_score = 8 # You write the new score in game
>>> from pyboy.api.memory_scanner import DynamicComparisonType
>>> addresses = pyboy.memory_scanner.rescan_memory(current_score, DynamicComparisonType.MATCH)
>>> print(addresses) # If repeated enough, only one address will remain
[]
```
"""
self.tilemap_background = TileMap(self, self.mb, "BACKGROUND")
"""
The Game Boy uses two tile maps at the same time to draw graphics on the screen. This method will provide one
for the _background_ tiles. The game chooses whether it wants to use the low or the high tilemap.
Read more details about it, in the [Pan Docs](https://gbdev.io/pandocs/Tile_Maps.html).
Example:
```
>>> pyboy.tilemap_background[8,8]
1
>>> pyboy.tilemap_background[7:12,8]
[0, 1, 0, 1, 0]
>>> pyboy.tilemap_background[7:12,8:11]
[[0, 1, 0, 1, 0], [0, 2, 3, 4, 5], [0, 0, 6, 0, 0]]
```
Returns
-------
`pyboy.api.tilemap.TileMap`:
A TileMap object for the tile map.
"""
self.tilemap_window = TileMap(self, self.mb, "WINDOW")
"""
The Game Boy uses two tile maps at the same time to draw graphics on the screen. This method will provide one
for the _window_ tiles. The game chooses whether it wants to use the low or the high tilemap.
Read more details about it, in the [Pan Docs](https://gbdev.io/pandocs/Tile_Maps.html).
Example:
```
>>> pyboy.tilemap_window[8,8]
1
>>> pyboy.tilemap_window[7:12,8]
[0, 1, 0, 1, 0]
>>> pyboy.tilemap_window[7:12,8:11]
[[0, 1, 0, 1, 0], [0, 2, 3, 4, 5], [0, 0, 6, 0, 0]]
```
Returns
-------
`pyboy.api.tilemap.TileMap`:
A TileMap object for the tile map.
"""
self.cartridge_title = self.mb.cartridge.gamename
"""
The title stored on the currently loaded cartridge ROM. The title is all upper-case ASCII and may
have been truncated to 11 characters.
Example:
```python
>>> pyboy.cartridge_title # Title of PyBoy's default ROM
'DEFAULT-ROM'
```
Returns
-------
str :
Game title
"""
self.cartridge_title = self.mb.cartridge.gametype
"""
The game type stored on the currently loaded cartridge ROM. Values are:
Game Boy, Game Boy Color, Super Game Boy
Example:
```python
>>> pyboy.cartridge_type # Game type of PyBoy's default ROM
'Game Boy Color'
```
Returns
-------
str :
Game type
"""
self.cartridge_region = self.mb.cartridge.gameregion
"""
The game region stored on the currently loaded cartridge ROM. Example values are:
Europe, USA, Japan, Spain, Germany, World...
Example:
```python
>>> pyboy.cartridge_region # Game region of PyBoy's default ROM
'Europe'
```
Returns
-------
str :
Europe
"""
self._hooks = {}
self._plugin_manager = PluginManager(self, self.mb, kwargs)
"""
Returns
-------
`pyboy.plugins.manager.PluginManager`:
Object for handling plugins in PyBoy
"""
self.game_wrapper = self._plugin_manager.gamewrapper()
"""
Provides an instance of a game-specific or generic wrapper. The game is detected by the cartridge's hard-coded
game title (see `pyboy.PyBoy.cartridge_title`).
If a game-specific wrapper is not found, a generic wrapper will be returned.
To get more information, find the wrapper for your game in `pyboy.plugins`.
Example:
```python
>>> pyboy.game_wrapper.start_game()
>>> pyboy.game_wrapper.reset_game()
```
Returns
-------
`pyboy.plugins.base_plugin.PyBoyGameWrapper`:
A game-specific wrapper object.
"""
self.initialized = True
def _tick(self, render):
if self.stopped:
return False
t_start = time.perf_counter_ns()
self._handle_events(self.events)
t_pre = time.perf_counter_ns()
if not self.paused:
self.__rendering(render)
# Reenter mb.tick until we eventually get a clean exit without breakpoints
while self.mb.tick():
# Breakpoint reached
# NOTE: Potentially reinject breakpoint that we have now stepped passed
self.mb.breakpoint_reinject()
# NOTE: PC has not been incremented when hitting breakpoint!
breakpoint_meta = self.mb.breakpoint_reached()
if breakpoint_meta != (-1, -1, -1):
bank, addr, _ = breakpoint_meta
self.mb.breakpoint_remove(bank, addr)
self.mb.breakpoint_singlestep_latch = 0
if not self._handle_hooks():
self._plugin_manager.handle_breakpoint()
else:
if self.mb.breakpoint_singlestep_latch:
if not self._handle_hooks():
self._plugin_manager.handle_breakpoint()
# Keep singlestepping on, if that's what we're doing
self.mb.breakpoint_singlestep = self.mb.breakpoint_singlestep_latch
self.frame_count += 1
t_tick = time.perf_counter_ns()
self._post_tick()
t_post = time.perf_counter_ns()
nsecs = t_pre - t_start
self.avg_pre = 0.9 * self.avg_pre + (0.1*nsecs/1_000_000_000)
nsecs = t_tick - t_pre
self.avg_tick = 0.9 * self.avg_tick + (0.1*nsecs/1_000_000_000)
nsecs = t_post - t_tick
self.avg_post = 0.9 * self.avg_post + (0.1*nsecs/1_000_000_000)
return not self.quitting
def tick(self, count=1, render=True):
"""
Progresses the emulator ahead by `count` frame(s).
To run the emulator in real-time, it will need to process 60 frames a second (for example in a while-loop).
This function will block for roughly 16,67ms per frame, to not run faster than real-time, unless you specify
otherwise with the `PyBoy.set_emulation_speed` method.
If you need finer control than 1 frame, have a look at `PyBoy.hook_register` to inject code at a specific point
in the game.
Setting `render` to `True` will make PyBoy render the screen for *the last frame* of this tick. This can be seen
as a type of "frameskipping" optimization.
For AI training, it's adviced to use as high a count as practical, as it will otherwise reduce performance
substantially. While setting `render` to `False`, you can still access the `PyBoy.game_area` to get a simpler
representation of the game.
If `render` was enabled, use `pyboy.api.screen.Screen` to get a NumPy buffer or raw memory buffer.
Example:
```python
>>> pyboy.tick() # Progress 1 frame with rendering
True
>>> pyboy.tick(1) # Progress 1 frame with rendering
True
>>> pyboy.tick(60, False) # Progress 60 frames *without* rendering
True
>>> pyboy.tick(60, True) # Progress 60 frames and render *only the last frame*
True
>>> for _ in range(60): # Progress 60 frames and render every frame
... if not pyboy.tick(1, True):
... break
>>>
```
Args:
count (int): Number of ticks to process
render (bool): Whether to render an image for this tick
Returns
-------
(True or False):
False if emulation has ended otherwise True
"""
running = False
while count != 0:
_render = render and count == 1 # Only render on last tick to improve performance
running = self._tick(_render)
count -= 1
return running
def _handle_events(self, events):
# This feeds events into the tick-loop from the window. There might already be events in the list from the API.
events = self._plugin_manager.handle_events(events)
for event in events:
if event == WindowEvent.QUIT:
self.quitting = True
elif event == WindowEvent.RELEASE_SPEED_UP:
# Switch between unlimited and 1x real-time emulation speed
self.target_emulationspeed = int(bool(self.target_emulationspeed) ^ True)
logger.debug("Speed limit: %d", self.target_emulationspeed)
elif event == WindowEvent.STATE_SAVE:
with open(self.gamerom + ".state", "wb") as f:
self.mb.save_state(IntIOWrapper(f))
elif event == WindowEvent.STATE_LOAD:
state_path = self.gamerom + ".state"
if not os.path.isfile(state_path):
logger.error("State file not found: %s", state_path)
continue
with open(state_path, "rb") as f:
self.mb.load_state(IntIOWrapper(f))
elif event == WindowEvent.PASS:
pass # Used in place of None in Cython, when key isn't mapped to anything
elif event == WindowEvent.PAUSE_TOGGLE:
if self.paused:
self._unpause()
else:
self._pause()
elif event == WindowEvent.PAUSE:
self._pause()
elif event == WindowEvent.UNPAUSE:
self._unpause()
elif event == WindowEvent._INTERNAL_RENDERER_FLUSH:
self._plugin_manager._post_tick_windows()
else:
self.mb.buttonevent(event)
def _pause(self):
if self.paused:
return
self.paused = True
self.save_target_emulationspeed = self.target_emulationspeed
self.target_emulationspeed = 1
logger.info("Emulation paused!")
self._update_window_title()
def _unpause(self):
if not self.paused:
return
self.paused = False
self.target_emulationspeed = self.save_target_emulationspeed
logger.info("Emulation unpaused!")
self._update_window_title()
def _post_tick(self):
# Fix buggy PIL. They will copy our image buffer and destroy the
# reference on some user operations like .save().
if self.screen.image and not self.screen.image.readonly:
self.screen._set_image()
if self.frame_count % 60 == 0:
self._update_window_title()
self._plugin_manager.post_tick()
self._plugin_manager.frame_limiter(self.target_emulationspeed)
# Prepare an empty list, as the API might be used to send in events between ticks
self.events = []
while self.queued_input and self.frame_count == self.queued_input[0][0]:
_, _event = heapq.heappop(self.queued_input)
self.events.append(WindowEvent(_event))
def _update_window_title(self):
avg_emu = self.avg_pre + self.avg_tick + self.avg_post
self.window_title = f"CPU/frame: {(self.avg_pre + self.avg_tick) / SPF * 100:0.2f}%"
self.window_title += f' Emulation: x{(round(SPF / avg_emu) if avg_emu > 0 else "INF")}'
if self.paused:
self.window_title += "[PAUSED]"
self.window_title += self._plugin_manager.window_title()
self._plugin_manager._set_title()
def __del__(self):
self.stop(save=False)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.stop()
def stop(self, save=True):
"""
Gently stops the emulator and all sub-modules.
Example:
```python
>>> pyboy.stop() # Stop emulator and save game progress (cartridge RAM)
>>> pyboy.stop(False) # Stop emulator and discard game progress (cartridge RAM)
```
Args:
save (bool): Specify whether to save the game upon stopping. It will always be saved in a file next to the
provided game-ROM.
"""
if self.initialized and not self.stopped:
logger.info("###########################")
logger.info("# Emulator is turning off #")
logger.info("###########################")
self._plugin_manager.stop()
self.mb.stop(save)
self.stopped = True
###################################################################
# Scripts and bot methods
#
def button(self, input, delay=1):
"""
Send input to PyBoy in the form of "a", "b", "start", "select", "left", "right", "up" and "down".
The button will automatically be released at the following call to `PyBoy.tick`.
Example:
```python
>>> pyboy.button('a') # Press button 'a' and release after `pyboy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' released
True
>>> pyboy.button('a', 3) # Press button 'a' and release after 3 `pyboy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.tick() # Button 'a' released
True
```
Args:
input (str): button to press
delay (int, optional): Number of frames to delay the release. Defaults to 1
"""
input = input.lower()
if input == "left":
self.send_input(WindowEvent.PRESS_ARROW_LEFT)
self.send_input(WindowEvent.RELEASE_ARROW_LEFT, delay)
elif input == "right":
self.send_input(WindowEvent.PRESS_ARROW_RIGHT)
self.send_input(WindowEvent.RELEASE_ARROW_RIGHT, delay)
elif input == "up":
self.send_input(WindowEvent.PRESS_ARROW_UP)
self.send_input(WindowEvent.RELEASE_ARROW_UP, delay)
elif input == "down":
self.send_input(WindowEvent.PRESS_ARROW_DOWN)
self.send_input(WindowEvent.RELEASE_ARROW_DOWN, delay)
elif input == "a":
self.send_input(WindowEvent.PRESS_BUTTON_A)
self.send_input(WindowEvent.RELEASE_BUTTON_A, delay)
elif input == "b":
self.send_input(WindowEvent.PRESS_BUTTON_B)
self.send_input(WindowEvent.RELEASE_BUTTON_B, delay)
elif input == "start":
self.send_input(WindowEvent.PRESS_BUTTON_START)
self.send_input(WindowEvent.RELEASE_BUTTON_START, delay)
elif input == "select":
self.send_input(WindowEvent.PRESS_BUTTON_SELECT)
self.send_input(WindowEvent.RELEASE_BUTTON_SELECT, delay)
else:
raise Exception("Unrecognized input:", input)
def button_press(self, input):
"""
Send input to PyBoy in the form of "a", "b", "start", "select", "left", "right", "up" and "down".
The button will remain press until explicitly released with `PyBoy.button_release` or `PyBoy.send_input`.
Example:
```python
>>> pyboy.button_press('a') # Press button 'a' and keep pressed after `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.button_release('a') # Release button 'a' on next call to `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' released
True
```
Args:
input (str): button to press
"""
input = input.lower()
if input == "left":
self.send_input(WindowEvent.PRESS_ARROW_LEFT)
elif input == "right":
self.send_input(WindowEvent.PRESS_ARROW_RIGHT)
elif input == "up":
self.send_input(WindowEvent.PRESS_ARROW_UP)
elif input == "down":
self.send_input(WindowEvent.PRESS_ARROW_DOWN)
elif input == "a":
self.send_input(WindowEvent.PRESS_BUTTON_A)
elif input == "b":
self.send_input(WindowEvent.PRESS_BUTTON_B)
elif input == "start":
self.send_input(WindowEvent.PRESS_BUTTON_START)
elif input == "select":
self.send_input(WindowEvent.PRESS_BUTTON_SELECT)
else:
raise Exception("Unrecognized input")
def button_release(self, input):
"""
Send input to PyBoy in the form of "a", "b", "start", "select", "left", "right", "up" and "down".
This will release a button after a call to `PyBoy.button_press` or `PyBoy.send_input`.
Example:
```python
>>> pyboy.button_press('a') # Press button 'a' and keep pressed after `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.button_release('a') # Release button 'a' on next call to `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' released
True
```
Args:
input (str): button to release
"""
input = input.lower()
if input == "left":
self.send_input(WindowEvent.RELEASE_ARROW_LEFT)
elif input == "right":
self.send_input(WindowEvent.RELEASE_ARROW_RIGHT)
elif input == "up":
self.send_input(WindowEvent.RELEASE_ARROW_UP)
elif input == "down":
self.send_input(WindowEvent.RELEASE_ARROW_DOWN)
elif input == "a":
self.send_input(WindowEvent.RELEASE_BUTTON_A)
elif input == "b":
self.send_input(WindowEvent.RELEASE_BUTTON_B)
elif input == "start":
self.send_input(WindowEvent.RELEASE_BUTTON_START)
elif input == "select":
self.send_input(WindowEvent.RELEASE_BUTTON_SELECT)
else:
raise Exception("Unrecognized input")
def send_input(self, event, delay=0):
"""
Send a single input to control the emulator. This is both Game Boy buttons and emulator controls. See
`pyboy.utils.WindowEvent` for which events to send.
Consider using `PyBoy.button` instead for easier access.
Example:
```python
>>> from pyboy.utils import WindowEvent
>>> pyboy.send_input(WindowEvent.PRESS_BUTTON_A) # Press button 'a' and keep pressed after `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.send_input(WindowEvent.RELEASE_BUTTON_A) # Release button 'a' on next call to `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' released
True
```
And even simpler with delay:
```python
>>> from pyboy.utils import WindowEvent
>>> pyboy.send_input(WindowEvent.PRESS_BUTTON_A) # Press button 'a' and keep pressed after `PyBoy.tick()`
>>> pyboy.send_input(WindowEvent.RELEASE_BUTTON_A, 2) # Release button 'a' on third call to `PyBoy.tick()`
>>> pyboy.tick() # Button 'a' pressed
True
>>> pyboy.tick() # Button 'a' still pressed
True
>>> pyboy.tick() # Button 'a' released
True
```
Args:
event (pyboy.WindowEvent): The event to send
delay (int): 0 for immediately, number of frames to delay the input
"""
if delay:
assert delay > 0, "Only positive integers allowed"
heapq.heappush(self.queued_input, (self.frame_count + delay, event))
else:
self.events.append(WindowEvent(event))
def save_state(self, file_like_object):
"""
Saves the complete state of the emulator. It can be called at any time, and enable you to revert any progress in
a game.
You can either save it to a file, or in-memory. The following two examples will provide the file handle in each
case. Remember to `seek` the in-memory buffer to the beginning before calling `PyBoy.load_state`:
```python
>>> # Save to file
>>> with open("state_file.state", "wb") as f:
... pyboy.save_state(f)
>>>
>>> # Save to memory
>>> import io
>>> with io.BytesIO() as f:
... f.seek(0)
... pyboy.save_state(f)
0
```
Args:
file_like_object (io.BufferedIOBase): A file-like object for which to write the emulator state.
"""
if isinstance(file_like_object, str):
raise Exception("String not allowed. Did you specify a filepath instead of a file-like object?")
if file_like_object.__class__.__name__ == "TextIOWrapper":
raise Exception("Text file not allowed. Did you specify open(..., 'wb')?")
self.mb.save_state(IntIOWrapper(file_like_object))
def load_state(self, file_like_object):
"""
Restores the complete state of the emulator. It can be called at any time, and enable you to revert any progress
in a game.
You can either load it from a file, or from memory. See `PyBoy.save_state` for how to save the state, before you
can load it here.
To load a file, remember to load it as bytes:
```python
>>> # Load file
>>> with open("state_file.state", "rb") as f:
... pyboy.load_state(f)
>>>
```
Args:
file_like_object (io.BufferedIOBase): A file-like object for which to read the emulator state.
"""
if isinstance(file_like_object, str):
raise Exception("String not allowed. Did you specify a filepath instead of a file-like object?")
if file_like_object.__class__.__name__ == "TextIOWrapper":
raise Exception("Text file not allowed. Did you specify open(..., 'rb')?")
self.mb.load_state(IntIOWrapper(file_like_object))
def game_area_dimensions(self, x, y, width, height, follow_scrolling=True):
"""
If using the generic game wrapper (see `pyboy.PyBoy.game_wrapper`), you can use this to set the section of the
tilemaps to extract. This will default to the entire tilemap.
Example:
```python
>>> pyboy.game_wrapper.shape
(32, 32)
>>> pyboy.game_area_dimensions(2, 2, 10, 18, False)
>>> pyboy.game_wrapper.shape
(10, 18)
```
Args:
x (int): Offset from top-left corner of the screen
y (int): Offset from top-left corner of the screen
width (int): Width of game area
height (int): Height of game area
follow_scrolling (bool): Whether to follow the scrolling of [SCX and SCY](https://gbdev.io/pandocs/Scrolling.html)
"""
self.game_wrapper._set_dimensions(x, y, width, height, follow_scrolling=True)
def game_area_collision(self):
"""
Some game wrappers define a collision map. Check if your game wrapper has this feature implemented: `pyboy.plugins`.
The output will be unique for each game wrapper.
Example:
```python
>>> # This example show nothing, but a supported game will
>>> pyboy.game_area_collision()
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint32)
```
Returns
-------
memoryview:
Simplified 2-dimensional memoryview of the collision map
"""
return self.game_wrapper.game_area_collision()
def game_area_mapping(self, mapping, sprite_offset=0):
"""
Define custom mappings for tile identifiers in the game area.
Example of custom mapping:
```python
>>> mapping = [x for x in range(384)] # 1:1 mapping
>>> mapping[0] = 0 # Map tile identifier 0 -> 0
>>> mapping[1] = 0 # Map tile identifier 1 -> 0
>>> mapping[2] = 0 # Map tile identifier 2 -> 0
>>> mapping[3] = 0 # Map tile identifier 3 -> 0
>>> pyboy.game_area_mapping(mapping, 1000)
```
Some game wrappers will supply mappings as well. See the specific documentation for your game wrapper:
`pyboy.plugins`.
```python
>>> pyboy.game_area_mapping(pyboy.game_wrapper.mapping_one_to_one, 0)