omnipython-apps 0.1.4.dev8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. apps/__init__.py +5 -0
  2. apps/about/__init__.py +257 -0
  3. apps/about/app.json +1 -0
  4. apps/about/credits.py +12 -0
  5. apps/about/facts.py +398 -0
  6. apps/about/fonts/OFL.txt +93 -0
  7. apps/about/fonts/latin1_14.bin +0 -0
  8. apps/about/fonts/latin1_16.bin +0 -0
  9. apps/about/fonts/latin1_24.bin +0 -0
  10. apps/about/fonts/latin1_32.bin +0 -0
  11. apps/about/fonts/latin1_40.bin +0 -0
  12. apps/backline/__init__.py +58 -0
  13. apps/backline/app.json +1 -0
  14. apps/backline/app.py +475 -0
  15. apps/backline/art.py +717 -0
  16. apps/backline/ask.py +781 -0
  17. apps/backline/box.py +502 -0
  18. apps/backline/cast.py +137 -0
  19. apps/backline/desk/__init__.py +329 -0
  20. apps/backline/desk/editor.py +331 -0
  21. apps/backline/desk/grid.py +154 -0
  22. apps/backline/desk/look.py +169 -0
  23. apps/backline/desk/pedals.py +102 -0
  24. apps/backline/desk/perform.py +157 -0
  25. apps/backline/desk/prompt.py +210 -0
  26. apps/backline/desk/strip.py +159 -0
  27. apps/backline/desk_main.py +226 -0
  28. apps/backline/engine.py +622 -0
  29. apps/backline/floor.py +509 -0
  30. apps/backline/footswitch.py +119 -0
  31. apps/backline/glyphs.py +82 -0
  32. apps/backline/kits.py +428 -0
  33. apps/backline/midipedal.py +362 -0
  34. apps/backline/page_data.py +413 -0
  35. apps/backline/parts.py +145 -0
  36. apps/backline/pedal.py +107 -0
  37. apps/backline/remote.py +134 -0
  38. apps/backline/songs/ballad_68.json +1 -0
  39. apps/backline/songs/bossa.json +1 -0
  40. apps/backline/songs/country_train.json +1 -0
  41. apps/backline/songs/funk.json +1 -0
  42. apps/backline/songs/metal.json +1 -0
  43. apps/backline/songs/pop.json +1 -0
  44. apps/backline/songs/rock.json +1 -0
  45. apps/backline/songs/shuffle.json +1 -0
  46. apps/battery/__init__.py +101 -0
  47. apps/battery/app.json +1 -0
  48. apps/bit_world/act_deck.py +683 -0
  49. apps/bit_world/act_game.py +762 -0
  50. apps/bit_world/act_pet.py +1032 -0
  51. apps/bit_world/app.json +1 -0
  52. apps/bit_world/bit_output.py +45 -0
  53. apps/bit_world/bit_palette.py +503 -0
  54. apps/bit_world/bit_sound.py +431 -0
  55. apps/bit_world/bit_sprites.py +632 -0
  56. apps/bit_world/bit_world.py +534 -0
  57. apps/btreceiver/__init__.py +690 -0
  58. apps/btreceiver/app.json +1 -0
  59. apps/btreceiver/chime.py +155 -0
  60. apps/btreceiver/demo.py +529 -0
  61. apps/btreceiver/screen.py +633 -0
  62. apps/camera/__init__.py +316 -0
  63. apps/camera/app.json +1 -0
  64. apps/card/__init__.py +113 -0
  65. apps/card/app.json +1 -0
  66. apps/cast/__init__.py +631 -0
  67. apps/cast/app.json +1 -0
  68. apps/cast/receivers.py +193 -0
  69. apps/chess/__init__.py +18 -0
  70. apps/chess/app.json +1 -0
  71. apps/chess/app.py +922 -0
  72. apps/chess/art.py +323 -0
  73. apps/chess/ble.py +411 -0
  74. apps/chess/engine.py +925 -0
  75. apps/chess/game.py +327 -0
  76. apps/chess/net.py +261 -0
  77. apps/clock/__init__.py +38 -0
  78. apps/clock/app.json +1 -0
  79. apps/detect/__init__.py +214 -0
  80. apps/detect/app.json +1 -0
  81. apps/fmsynth/__init__.py +41 -0
  82. apps/fmsynth/algorithms.py +61 -0
  83. apps/fmsynth/app.json +1 -0
  84. apps/fmsynth/app.py +355 -0
  85. apps/fmsynth/editor.py +206 -0
  86. apps/fmsynth/engine.py +257 -0
  87. apps/fmsynth/meters.py +262 -0
  88. apps/fmsynth/midi.py +375 -0
  89. apps/fmsynth/panel_view.py +1071 -0
  90. apps/fmsynth/patches/fmsynth-01.syx +0 -0
  91. apps/fmsynth/settings.py +138 -0
  92. apps/fmsynth/voice.py +398 -0
  93. apps/gamepad/__init__.py +685 -0
  94. apps/gamepad/app.json +1 -0
  95. apps/gamepad/pad.py +94 -0
  96. apps/gamepad/watch.py +352 -0
  97. apps/hidden/__init__.py +72 -0
  98. apps/hidden/app.json +1 -0
  99. apps/home/__init__.py +483 -0
  100. apps/home/app.json +1 -0
  101. apps/home/main.py +36 -0
  102. apps/homeassistant/__init__.py +213 -0
  103. apps/homeassistant/api.py +104 -0
  104. apps/homeassistant/app.json +1 -0
  105. apps/huey/__init__.py +287 -0
  106. apps/huey/acting.py +184 -0
  107. apps/huey/actor.py +194 -0
  108. apps/huey/app.json +1 -0
  109. apps/huey/client.py +125 -0
  110. apps/huey/servers.py +121 -0
  111. apps/huey/settings.example.json +8 -0
  112. apps/huey/settings.py +97 -0
  113. apps/huey/turn.py +504 -0
  114. apps/huey/voice.py +217 -0
  115. apps/info/__init__.py +810 -0
  116. apps/info/app.json +1 -0
  117. apps/lora/__init__.py +62 -0
  118. apps/lora/app.json +1 -0
  119. apps/manifest.py +71 -0
  120. apps/medialink_baby_monitor/__init__.py +222 -0
  121. apps/medialink_baby_monitor/app.json +1 -0
  122. apps/medialink_doorbell/__init__.py +251 -0
  123. apps/medialink_doorbell/app.json +1 -0
  124. apps/medialink_hands_free/__init__.py +217 -0
  125. apps/medialink_hands_free/app.json +1 -0
  126. apps/medialink_surveillance_camera/__init__.py +258 -0
  127. apps/medialink_surveillance_camera/app.json +1 -0
  128. apps/medialink_video_doorbell/__init__.py +289 -0
  129. apps/medialink_video_doorbell/app.json +1 -0
  130. apps/medialink_videophone/__init__.py +273 -0
  131. apps/medialink_videophone/app.json +1 -0
  132. apps/medialink_walkie_talkie/__init__.py +228 -0
  133. apps/medialink_walkie_talkie/app.json +1 -0
  134. apps/midicontroller/__init__.py +774 -0
  135. apps/midicontroller/app.json +1 -0
  136. apps/midicontroller/links.py +421 -0
  137. apps/midicontroller/surface.py +343 -0
  138. apps/midiengine/__init__.py +977 -0
  139. apps/midiengine/app.json +1 -0
  140. apps/midiengine/banks.py +85 -0
  141. apps/midiengine/midiin.py +165 -0
  142. apps/midiengine/player.py +392 -0
  143. apps/midiengine/umidiparser.py +1413 -0
  144. apps/mp3/__init__.py +240 -0
  145. apps/mp3/app.json +1 -0
  146. apps/perch/__init__.py +119 -0
  147. apps/perch/app.json +1 -0
  148. apps/perch/huey.py +481 -0
  149. apps/perch/huey_props.py +386 -0
  150. apps/perch/huey_shift.py +42 -0
  151. apps/perch/huey_views.py +296 -0
  152. apps/perch/scene_bench.py +680 -0
  153. apps/perch/scene_coast.py +479 -0
  154. apps/perch/scene_desk.py +492 -0
  155. apps/perch/stage.py +1274 -0
  156. apps/perch/vec.py +366 -0
  157. apps/repl/__init__.py +325 -0
  158. apps/repl/app.json +1 -0
  159. apps/roku/__init__.py +156 -0
  160. apps/roku/app.json +1 -0
  161. apps/rokucam/__init__.py +362 -0
  162. apps/rokucam/app.json +1 -0
  163. apps/security/__init__.py +261 -0
  164. apps/security/app.json +1 -0
  165. apps/settings/__init__.py +221 -0
  166. apps/settings/app.json +1 -0
  167. apps/shell/__init__.py +33 -0
  168. apps/shell/app.json +1 -0
  169. apps/spotify/__init__.py +669 -0
  170. apps/spotify/app.json +1 -0
  171. apps/spotify/screen.py +82 -0
  172. apps/steps/__init__.py +58 -0
  173. apps/steps/app.json +1 -0
  174. apps/stompbox/__init__.py +31 -0
  175. apps/stompbox/app.json +1 -0
  176. apps/stompbox/app.py +668 -0
  177. apps/stompbox/boards.json +20 -0
  178. apps/stompbox/effects.py +241 -0
  179. apps/stompbox/engine.py +340 -0
  180. apps/stompbox/footswitch.py +331 -0
  181. apps/stompbox/inputs.py +449 -0
  182. apps/stompbox/meter.py +72 -0
  183. apps/stompbox/outputs.py +135 -0
  184. apps/stompbox/pedals.txt +45 -0
  185. apps/stompbox/presets.py +106 -0
  186. apps/stompbox/styles.py +135 -0
  187. apps/stompbox/ui.py +817 -0
  188. apps/stompbox/wavfile.py +73 -0
  189. apps/synthstation/__init__.py +20 -0
  190. apps/synthstation/app.json +1 -0
  191. apps/synthstation/audio.py +397 -0
  192. apps/synthstation/catalog.py +50 -0
  193. apps/synthstation/meters.py +136 -0
  194. apps/synthstation/midi.py +380 -0
  195. apps/synthstation/pads.py +177 -0
  196. apps/synthstation/parts.py +128 -0
  197. apps/synthstation/station.py +1069 -0
  198. apps/system/__init__.py +11 -0
  199. apps/system/app.json +1 -0
  200. apps/touchcal/__init__.py +324 -0
  201. apps/touchcal/app.json +1 -0
  202. apps/touchcal/fit.py +262 -0
  203. apps/wake/__init__.py +268 -0
  204. apps/wake/app.json +1 -0
  205. apps/wake/feed.py +155 -0
  206. apps/watch/__init__.py +355 -0
  207. apps/watch/app.json +1 -0
  208. apps/watch/faces.py +35 -0
  209. apps/watch/wheel.py +157 -0
  210. apps/weather/__init__.py +278 -0
  211. apps/weather/app.json +1 -0
  212. apps/weather/icons.py +172 -0
  213. apps/weather/sizing.py +71 -0
  214. apps/weather/zippad.py +172 -0
  215. omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
  216. omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
  217. omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
  218. omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
apps/chess/engine.py ADDED
@@ -0,0 +1,925 @@
1
+ # SPDX-FileCopyrightText: 2004-2020 Douglas Bagnall and the p4wn contributors
2
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
3
+ #
4
+ # SPDX-License-Identifier: MIT
5
+ """Chess's engine: p4wn, a small chess engine, ported from JavaScript.
6
+
7
+ The original's header, kept as it was::
8
+
9
+ /* p4wn, AKA 5k chess - by Douglas Bagnall <douglas@paradise.net.nz>
10
+ *
11
+ * This code is in the public domain, or as close to it as various
12
+ * laws allow. No warranty; no restrictions.
13
+ *
14
+ * lives at http://p4wn.sf.net/
15
+ */
16
+
17
+ This follows p4wn's src/engine.js (github.com/douglasbagnall/p4wn, commit
18
+ fcdda9f): the 10 x 12 board, its piece numbers, the move scoring that
19
+ `prepare` sets up before each search, and the alpha-beta tree climber. What
20
+ is new here: a search stops at a deadline and deepens one ply at a time
21
+ (`Position.think`), it only ever plays a legal move, a level can add noise
22
+ so a beginner can win, and `perft` counts positions for the tests. Rules
23
+ the search doesn't need (draws, notation) are in `game`.
24
+
25
+ A square is ``row * 10 + column``: a1 is 21, h1 is 28, a8 is 91 and h8 is
26
+ 98. Rows 0, 1, 10 and 11 and columns 0 and 9 are the edge.
27
+ """
28
+
29
+ import math
30
+
31
+ try:
32
+ from time import ticks_diff, ticks_ms
33
+ except ImportError:
34
+ import time
35
+
36
+ def ticks_ms():
37
+ return int(time.monotonic() * 1000)
38
+
39
+ def ticks_diff(a, b):
40
+ return a - b
41
+
42
+
43
+ # The pieces are stored as numbers between 2 and 13, inclusive. Empty
44
+ # squares are 0, and off-board squares 16. There is some bitwise logic to it:
45
+ # piece & 1 -> colour (white: 0, black: 1)
46
+ # piece & 2 -> single move piece (including pawn)
47
+ # if (piece & 2) == 0:
48
+ # piece & 4 -> row and column moves
49
+ # piece & 8 -> diagonal moves
50
+ PAWN = 2
51
+ ROOK = 4
52
+ KNIGHT = 6
53
+ BISHOP = 8
54
+ KING = 10
55
+ QUEEN = 12
56
+ EDGE = 16
57
+
58
+ WHITE = 0
59
+ BLACK = 1
60
+
61
+ _ORTHO = (1, 10, -1, -10)
62
+ _DIAG = (11, 9, -11, -9)
63
+ _ALL = (1, 10, 11, 9, -1, -10, -11, -9)
64
+ #: The steps each piece takes, by piece number (even ones only).
65
+ MOVES = ((), (), (), (), _ORTHO, (), (21, 19, 12, 8, -21, -19, -12, -8), (),
66
+ _DIAG, (), _ALL, (), _ALL, ())
67
+
68
+ # The relative value of the pieces: the 1, 3, 3, 5, 9 you learn as a kid,
69
+ # times 20 for sub-pawn resolution, with bishops a wee boost over knights.
70
+ VALUES = (0, 0, 20, 20, 100, 100, 60, 60, 61, 61, 8000, 8000, 180, 180, 0)
71
+
72
+ # A score over WIN means a king has been taken. It is less than a king's
73
+ # value, in case someone sacrifices two queens to mate.
74
+ KING_VALUE = VALUES[10]
75
+ WIN = KING_VALUE >> 1
76
+ WIN_DECAY = 300 # each move, a winning score decreases by this much
77
+ WIN_NOW = KING_VALUE - 250
78
+ MAX_SCORE = 9999
79
+ MIN_SCORE = -MAX_SCORE
80
+
81
+ START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
82
+
83
+ PIECE_LUT = {"P": 2, "p": 3, "R": 4, "r": 5, "N": 6, "n": 7, "B": 8, "b": 9,
84
+ "K": 10, "k": 11, "Q": 12, "q": 13}
85
+ FEN_LUT = " PpRrNnBbKkQq"
86
+
87
+ # Weights that never change, set up once.
88
+ _CENTRALISING = [0] * 120
89
+ _KNIGHT_W = [0] * 120
90
+ _BASE_PAWN = [0] * 120
91
+ _EDGE_BOARD = bytearray(120)
92
+ for _i in range(120):
93
+ _y = _i // 10
94
+ _x = _i % 10
95
+ _dx = abs(_x - 4.5)
96
+ _dy = abs(_y - 5.5)
97
+ _CENTRALISING[_i] = int(6 - math.pow((_dx * _dx + _dy * _dy) * 1.5, 0.6))
98
+ # Knights have a flat topped centre (bishops too, but less so).
99
+ _KNIGHT_W[_i] = int((_dx < 2) + (_dy < 2) * 1.5 + (_dx < 3) + (_dy < 3)) - 2
100
+ _BASE_PAWN[_i] = int("000012347000"[_y])
101
+ if _y > 9 or _y < 2 or _x < 1 or _x > 8:
102
+ _EDGE_BOARD[_i] = EDGE
103
+
104
+
105
+ class Stopped(Exception):
106
+ """A search ran past its deadline or was told to stop."""
107
+
108
+
109
+ def square_name(p):
110
+ """``"e4"`` for square 55."""
111
+ return "abcdefgh"[p % 10 - 1] + str(p // 10 - 1)
112
+
113
+
114
+ def square_of(name):
115
+ """Square 55 for ``"e4"``; None for anything else."""
116
+ if len(name) != 2:
117
+ return None
118
+ x = "abcdefgh".find(name[0]) + 1
119
+ y = "12345678".find(name[1]) + 2
120
+ if x < 1 or y < 2:
121
+ return None
122
+ return y * 10 + x
123
+
124
+
125
+ class Position:
126
+ """A board, whose turn it is, and what p4wn needs to search it."""
127
+
128
+ def __init__(self, fen=START, seed=None):
129
+ if fen is None:
130
+ return # a blank for `copy` to fill
131
+ self.board = bytearray(_EDGE_BOARD)
132
+ self.weights = [[0] * 120 for _ in range(14)]
133
+ self.pieces = [[], []]
134
+ self.values = [list(VALUES), list(VALUES)]
135
+ self.stalemate_scores = [0, 0]
136
+ self.best_pieces = [0, 0]
137
+ self.current_repetitions = 1
138
+ self.nodes = 0
139
+ self.stop = False
140
+ self._deadline = None
141
+ self._search = None
142
+ self._rng = [0, 0, 0, 0]
143
+ self.seed(ticks_ms() if seed is None else seed)
144
+ self.set_fen(fen)
145
+
146
+ # --- p4_random_seed, p4_random31, p4_random_int -------------------------
147
+
148
+ def seed(self, seed):
149
+ """Start the random numbers (early pawn weights, a level's noise) from *seed*."""
150
+ seed &= 0xFFFFFFFF
151
+ self._rng = [0xF1EA5EED, seed, seed, seed]
152
+ for _ in range(20):
153
+ self.random31()
154
+
155
+ def random31(self):
156
+ # Bob Jenkins' small PRNG (burtleburtle.net/bob/rand/smallprng.html).
157
+ r = self._rng
158
+ m = 0xFFFFFFFF
159
+ b = r[1]
160
+ c = r[2]
161
+ e = (r[0] - (((b << 27) | (b >> 5)) & m)) & m
162
+ r[0] = b ^ (((c << 17) | (c >> 15)) & m)
163
+ r[1] = (c + r[3]) & m
164
+ r[2] = (r[3] + e) & m
165
+ r[3] = (e + r[0]) & m
166
+ return r[3] & 0x7FFFFFFF
167
+
168
+ def random_int(self, top):
169
+ """A uniform integer in ``[0, top)``."""
170
+ top = int(top)
171
+ if top <= 1:
172
+ return 0
173
+ mask = top - 1
174
+ mask |= mask >> 1
175
+ mask |= mask >> 2
176
+ mask |= mask >> 4
177
+ mask |= mask >> 8
178
+ mask |= mask >> 16
179
+ while True:
180
+ r = self.random31() & mask
181
+ if r < top:
182
+ return r
183
+
184
+ # --- FEN ---------------------------------------------------------------
185
+
186
+ def set_fen(self, fen):
187
+ """Set the position from a FEN string."""
188
+ bits = fen.split()
189
+ board = self.board
190
+ y = 90
191
+ x = 1
192
+ for c in bits[0]:
193
+ if c == "/":
194
+ x = 1
195
+ y -= 10
196
+ if y < 20:
197
+ break
198
+ continue
199
+ piece = PIECE_LUT.get(c)
200
+ if piece and x < 9:
201
+ board[y + x] = piece
202
+ x += 1
203
+ elif "1" <= c <= "8":
204
+ end = min(x + int(c), 9)
205
+ while x < end:
206
+ board[y + x] = 0
207
+ x += 1
208
+ self.to_play = BLACK if len(bits) > 1 and bits[1].lower() == "b" else WHITE
209
+ castles = bits[2] if len(bits) > 2 else "-"
210
+ self.castles = 0
211
+ # A FEN may claim a castle its pieces aren't in place for.
212
+ wk = board[25] == KING
213
+ bk = board[95] == KING + 1
214
+ lut = {"k": 8 * (bk and board[98] == ROOK + 1), "q": 4 * (bk and board[91] == ROOK + 1),
215
+ "K": 2 * (wk and board[28] == ROOK), "Q": 1 * (wk and board[21] == ROOK)}
216
+ for c in castles:
217
+ self.castles |= lut.get(c, 0)
218
+ ep = bits[3] if len(bits) > 3 else "-"
219
+ self.enpassant = square_of(ep) or 0 if ep != "-" else 0
220
+ self.draw_timeout = int(bits[4]) if len(bits) > 4 else 0
221
+ moveno = int(bits[5]) if len(bits) > 5 else 1
222
+ self.moveno = 2 * (moveno - 1) + self.to_play
223
+ self.prepared = False
224
+ self._find_pieces()
225
+
226
+ def fen(self, reduced=False):
227
+ """The position as FEN; *reduced* leaves off the two counters."""
228
+ board = self.board
229
+ rows = []
230
+ for y in range(9, 1, -1):
231
+ row = ""
232
+ count = 0
233
+ for x in range(1, 9):
234
+ piece = board[y * 10 + x]
235
+ if piece == 0:
236
+ count += 1
237
+ else:
238
+ if count:
239
+ row += str(count)
240
+ row += FEN_LUT[piece]
241
+ count = 0
242
+ if count:
243
+ row += str(count)
244
+ rows.append(row)
245
+ out = "/".join(rows) + " " + "wb"[self.to_play] + " "
246
+ castles = ""
247
+ for bit, c in ((2, "K"), (1, "Q"), (8, "k"), (4, "q")):
248
+ if self.castles & bit:
249
+ castles += c
250
+ out += (castles or "-") + " " + (square_name(self.enpassant) if self.enpassant else "-")
251
+ if reduced:
252
+ return out
253
+ return out + " %d %d" % (self.draw_timeout, (self.moveno >> 1) + 1)
254
+
255
+ def copy(self):
256
+ """Another position like this one, for a search to play with."""
257
+ p = Position(None)
258
+ p.board = bytearray(self.board)
259
+ p.weights = [[0] * 120 for _ in range(14)]
260
+ p.pieces = [list(self.pieces[0]), list(self.pieces[1])]
261
+ p.values = [list(VALUES), list(VALUES)]
262
+ p.stalemate_scores = [0, 0]
263
+ p.best_pieces = [0, 0]
264
+ p.current_repetitions = self.current_repetitions
265
+ p.nodes = 0
266
+ p.stop = False
267
+ p._deadline = None
268
+ p._search = None
269
+ p._rng = list(self._rng)
270
+ p.to_play = self.to_play
271
+ p.castles = self.castles
272
+ p.enpassant = self.enpassant
273
+ p.draw_timeout = self.draw_timeout
274
+ p.moveno = self.moveno
275
+ p.prepared = False
276
+ return p
277
+
278
+ def _find_pieces(self):
279
+ board = self.board
280
+ pieces = [[], []]
281
+ for i in range(20, 100):
282
+ a = board[i]
283
+ if a and a != EDGE:
284
+ pieces[a & 1].append((a, i))
285
+ self.pieces = pieces
286
+
287
+ # --- p4_prepare --------------------------------------------------------
288
+
289
+ def prepare(self):
290
+ """Work out the weights for scoring moves in this position.
291
+
292
+ Called before each search, not each move, so it may be slowish; it
293
+ drifts out of step with the board in a deep search, which is fine:
294
+ heuristics are heuristics.
295
+ """
296
+ board = self.board
297
+ self._find_pieces()
298
+ moveno = self.moveno >> 1
299
+ # High earliness_weight means a low move number.
300
+ earliness_weight = 0 if moveno > 50 else int(6 * math.exp(moveno * -0.07))
301
+ king_should_hide = moveno < 12
302
+ early = moveno < 5
303
+ kings = [0, 0]
304
+ material = [0, 0]
305
+ best_pieces = [0, 0]
306
+ for colour in (0, 1):
307
+ for a, i in self.pieces[colour]:
308
+ piece = a & 14
309
+ if piece == KING:
310
+ kings[colour] = i
311
+ else:
312
+ material[colour] += VALUES[piece]
313
+ best_pieces[colour] = max(best_pieces[colour], VALUES[piece])
314
+
315
+ # Does a draw seem likely soon?
316
+ draw_likely = self.draw_timeout > 90 or self.current_repetitions >= 2
317
+ qvalue = VALUES[QUEEN] # ballast in various ratios
318
+ material_sum = material[0] + material[1] + 2 * qvalue
319
+ wmul = 2 * (material[1] + qvalue) / material_sum
320
+ bmul = 2 * (material[0] + qvalue) / material_sum
321
+ multipliers = (wmul, bmul)
322
+ emptiness = 4 * QUEEN / material_sum
323
+ self.stalemate_scores = [int(0.5 + (wmul - 1) * 2 * qvalue), int(0.5 + (bmul - 1) * 2 * qvalue)]
324
+ values = [[], []]
325
+ for v in VALUES:
326
+ if v < WIN: # not a king
327
+ values[0].append(int(v * wmul + 0.5))
328
+ values[1].append(int(v * bmul + 0.5))
329
+ else:
330
+ values[0].append(v)
331
+ values[1].append(v)
332
+ self.values = values
333
+ # Used for pruning quiescence search.
334
+ self.best_pieces = [int(best_pieces[0] * wmul + 0.5), int(best_pieces[1] * bmul + 0.5)]
335
+
336
+ kx = (kings[0] % 10, kings[1] % 10)
337
+ ky = (kings[0] // 10, kings[1] // 10)
338
+
339
+ # The frontmost pawns in each file.
340
+ pawn_cols = [{}, {}]
341
+ for y in range(3, 9):
342
+ for x in range(1, 9):
343
+ a = board[y * 10 + x]
344
+ if (a & 14) != PAWN:
345
+ continue
346
+ if (a & 1) == 0:
347
+ pawn_cols[0][x] = y
348
+ elif x not in pawn_cols[1]:
349
+ pawn_cols[1][x] = y
350
+ target_king = moveno >= 20 or material_sum < 5 * qvalue
351
+ weights = self.weights
352
+
353
+ for y in range(2, 10):
354
+ for x in range(1, 9):
355
+ i = y * 10 + x
356
+ early_centre = _CENTRALISING[i] * earliness_weight
357
+ plateau = _KNIGHT_W[i]
358
+ for c in (0, 1):
359
+ dx = abs(kx[1 - c] - x)
360
+ dy = abs(ky[1 - c] - y)
361
+ our_dx = abs(kx[c] - x)
362
+ d = max(math.sqrt(dx * dx + dy * dy), 1) + 1
363
+ mul = multipliers[c] # (mul < 1) <==> we're winning
364
+ mul3 = mul * mul * mul
365
+ at_home = y == 2 + c * 7
366
+ pawn_home = y == 3 + c * 5
367
+ row4 = y == 5 + c
368
+ promotion_row = y == 9 - c * 7
369
+ get_out = (early and at_home) * -5
370
+
371
+ knight = int(early_centre * 0.3) + 2 * plateau + get_out
372
+ rook = int(early_centre * 0.3)
373
+ bishop = int(early_centre * 0.6) + plateau + get_out
374
+ if at_home:
375
+ rook += (x == 4 or x == 5) * (earliness_weight + (not target_king))
376
+ rook += (x == 1 or x == 8) * (10 < moveno < 20) * -3
377
+ rook += (x == 2 or x == 7) * (10 < moveno < 20) * -1
378
+
379
+ # The queen stays home early, then jumps right in; kings
380
+ # stay back on the home row for a while.
381
+ queen = int(plateau * 0.5 + early_centre * (0.5 - early))
382
+ king = (king_should_hide and at_home) * 2 * earliness_weight
383
+
384
+ # An empty board makes pawn advancement more urgent.
385
+ get_on_with_it = max(emptiness * 2, 1)
386
+ pawn = get_on_with_it * _BASE_PAWN[119 - i if c else i]
387
+ if early:
388
+ # Early pawn weights are slightly randomised, so each game is different.
389
+ if 4 <= y <= 7:
390
+ boost = 1 + 3 * (y == 5 or y == 6)
391
+ pawn += int((boost + self.random_int(4)) * 0.1 * early_centre)
392
+ if x == 4 or x == 5:
393
+ # Discourage middle pawns from waiting at home.
394
+ pawn -= 3 * pawn_home
395
+ pawn += 3 * row4
396
+ # The promotion row is weighted as a queen minus a pawn.
397
+ if promotion_row:
398
+ pawn += values[c][QUEEN] - values[c][PAWN]
399
+ # Pawns in front of a castled king should stay there.
400
+ pawn += 4 * (y == 3 and ky[c] == 2 and our_dx < 2 and kx[c] != 5 and x != 4 and x != 5)
401
+ # Passed pawns (no opposing pawn in front) are encouraged.
402
+ cols = pawn_cols[1 - c]
403
+ if x not in cols or (c == 0 and cols[x] < y) or (c == 1 and cols[x] > y):
404
+ pawn += 2
405
+
406
+ # After a while, go for the opposite king: attract pieces
407
+ # into its area to mill about, waiting for a chance.
408
+ if target_king:
409
+ knight += 2 * int(8 * mul / d)
410
+ rook += 2 * ((dx < 2) + (dy < 2))
411
+ bishop += 3 * (abs(dx - dy) < 2)
412
+ queen += 2 * int(8 / d) + (dx * dy == 0) + (dx - dy == 0)
413
+ # The losing king keeps to the middle, while the
414
+ # winning king goes in for the kill.
415
+ king_centre_wt = 8 * emptiness * _CENTRALISING[i]
416
+ king += int(150 * emptiness / (mul3 * d) + king_centre_wt * mul3)
417
+ weights[PAWN + c][i] = int(pawn)
418
+ weights[KNIGHT + c][i] = knight
419
+ weights[ROOK + c][i] = rook
420
+ weights[BISHOP + c][i] = bishop
421
+ weights[QUEEN + c][i] = queen
422
+ weights[KING + c][i] = king
423
+
424
+ if draw_likely and mul < 1:
425
+ # The winning side wants to avoid a draw, so it adds
426
+ # jitter to its weights.
427
+ top = 3 / mul3
428
+ for j in range(2 + c, 14, 2):
429
+ weights[j][i] += self.random_int(top)
430
+ self.prepared = True
431
+
432
+ # --- p4_parse ----------------------------------------------------------
433
+
434
+ def parse(self, colour, ep, score):
435
+ """Every pseudo-legal move for *colour*, as ``(score, from, to)``,
436
+ captures first. Castling is checked for passing through check."""
437
+ board = self.board
438
+ other_colour = 1 - colour
439
+ direction = 10 - 20 * colour
440
+ movelist = []
441
+ captures = []
442
+ push = movelist.append
443
+ take = captures.append
444
+ castle_flags = (self.castles >> (colour * 2)) & 3
445
+ values = self.values[other_colour]
446
+ all_weights = self.weights
447
+ pieces = self.pieces[colour]
448
+ for j in range(len(pieces) - 1, -1, -1):
449
+ s = pieces[j][1]
450
+ a = board[s]
451
+ weight_lut = all_weights[a]
452
+ weight = score - weight_lut[s]
453
+ a &= 14
454
+ if a > 2: # not a pawn
455
+ moves = MOVES[a]
456
+ if a & 2: # knight and king: single steps
457
+ for m in moves:
458
+ e = s + m
459
+ E = board[e]
460
+ if not E:
461
+ push((weight + weight_lut[e], s, e))
462
+ elif (E & 17) == other_colour:
463
+ take((weight + values[E] + weight_lut[e] + all_weights[E][e], s, e))
464
+ if a == KING and castle_flags:
465
+ if ((castle_flags & 1) and board[s - 1] + board[s - 2] + board[s - 3] == 0
466
+ and check_castling(board, s - 2, other_colour, direction, -1)):
467
+ push((weight + 12, s, s - 2)) # queen side: encouragement, no analysis
468
+ if ((castle_flags & 2) and board[s + 1] + board[s + 2] == 0
469
+ and check_castling(board, s, other_colour, direction, 1)):
470
+ push((weight + 13, s, s + 2))
471
+ else: # rook, bishop, queen: slides
472
+ for m in moves:
473
+ e = s
474
+ while True:
475
+ e += m
476
+ E = board[e]
477
+ if not E:
478
+ push((weight + weight_lut[e], s, e))
479
+ continue
480
+ if (E & 17) == other_colour:
481
+ take((weight + values[E] + weight_lut[e] + all_weights[E][e], s, e))
482
+ break
483
+ else: # pawns
484
+ e = s + direction
485
+ if not board[e]:
486
+ push((weight + weight_lut[e], s, e))
487
+ # s * (120 - s) < 3200 is true for the outer two rows on either side.
488
+ e2 = e + direction
489
+ if s * (120 - s) < 3200 and not board[e2]:
490
+ push((weight + weight_lut[e2], s, e2))
491
+ e -= 1
492
+ E = board[e]
493
+ if E and (E & 17) == other_colour:
494
+ take((weight + values[E] + weight_lut[e] + all_weights[E][e], s, e))
495
+ e += 2
496
+ E = board[e]
497
+ if E and (E & 17) == other_colour:
498
+ take((weight + values[E] + weight_lut[e] + all_weights[E][e], s, e))
499
+ if ep:
500
+ pawn = PAWN | colour
501
+ weight_lut = all_weights[pawn]
502
+ s = ep - direction - 1
503
+ taken = values[PAWN] + all_weights[PAWN | other_colour][ep - direction]
504
+ if board[s] == pawn:
505
+ take((score - weight_lut[s] + weight_lut[ep] + taken, s, ep))
506
+ s += 2
507
+ if board[s] == pawn:
508
+ take((score - weight_lut[s] + weight_lut[ep] + taken, s, ep))
509
+ captures.extend(movelist)
510
+ return captures
511
+
512
+ # --- p4_check_check ----------------------------------------------------
513
+
514
+ def in_check(self, colour):
515
+ """True when *colour*'s king is attacked."""
516
+ board = self.board
517
+ s = 0
518
+ king = KING | colour
519
+ pieces = self.pieces[colour]
520
+ # The pieces list updates from the end, so the last king is right.
521
+ for i in range(len(pieces) - 1, -1, -1):
522
+ if pieces[i][0] == king:
523
+ s = pieces[i][1]
524
+ break
525
+ other_colour = 1 - colour
526
+ direction = 10 - 20 * colour
527
+ pawn = PAWN | other_colour
528
+ if board[s + direction - 1] == pawn or board[s + direction + 1] == pawn:
529
+ return True
530
+ knight = KNIGHT | other_colour
531
+ king = KING | other_colour
532
+ knight_moves = MOVES[KNIGHT]
533
+ for i in range(8):
534
+ if board[s + knight_moves[i]] == knight or board[s + _ALL[i]] == king:
535
+ return True
536
+ # diag_mask ignores the rook moves of queens, grid_mask the bishop moves.
537
+ diag_slider = BISHOP | other_colour
538
+ grid_slider = ROOK | other_colour
539
+ for i in range(4):
540
+ m = _DIAG[i]
541
+ e = s + m
542
+ E = board[e]
543
+ while not E:
544
+ e += m
545
+ E = board[e]
546
+ if (E & 27) == diag_slider:
547
+ return True
548
+ m = _ORTHO[i]
549
+ e = s + m
550
+ E = board[e]
551
+ while not E:
552
+ e += m
553
+ E = board[e]
554
+ if (E & 23) == grid_slider:
555
+ return True
556
+ return False
557
+
558
+ # --- p4_make_move, p4_unmake_move ----------------------------------------
559
+
560
+ def make(self, s, e, promotion=QUEEN):
561
+ """Play the move; return what `unmake` needs to take it back."""
562
+ board = self.board
563
+ S = board[s]
564
+ E = board[e]
565
+ board[e] = S
566
+ board[s] = 0
567
+ piece = S & 14
568
+ moved_colour = S & 1
569
+ end_piece = S # differs from S when a pawn promotes
570
+ rs = re = rook = 0
571
+ ep_taken = ep_position = 0
572
+ ep = 0
573
+ if piece == PAWN:
574
+ if (60 - e) * (60 - e) > 900:
575
+ # Got to the end: replace the pawn on the board and in the pieces list.
576
+ end_piece = (promotion & 14) | moved_colour
577
+ board[e] = end_piece
578
+ elif ((s ^ e) & 1) and E == 0:
579
+ # A diagonal move to an empty square: en passant.
580
+ ep_position = e - 10 + 20 * moved_colour
581
+ ep_taken = board[ep_position]
582
+ board[ep_position] = 0
583
+ elif (s - e) * (s - e) == 400:
584
+ # Two rows at the start.
585
+ ep = (s + e) >> 1
586
+ elif piece == KING and (s - e) * (s - e) == 4:
587
+ # Castling: move the rook too.
588
+ rs = s - 4 + (s < e) * 7
589
+ re = (s + e) >> 1
590
+ rook = moved_colour + ROOK
591
+ board[rs] = 0
592
+ board[re] = rook
593
+
594
+ old_castles = self.castles
595
+ if old_castles:
596
+ mask = 0
597
+ shift = moved_colour * 2
598
+ side = moved_colour * 70
599
+ s2 = s - side
600
+ e2 = e + side
601
+ # Wipe both our sides if the king moves, one from a rook's corner,
602
+ if s2 == 25:
603
+ mask |= 3 << shift
604
+ elif s2 == 21:
605
+ mask |= 1 << shift
606
+ elif s2 == 28:
607
+ mask |= 2 << shift
608
+ # or the other side's on any move to its corners.
609
+ if e2 == 91:
610
+ mask |= 4 >> shift
611
+ elif e2 == 98:
612
+ mask |= 8 >> shift
613
+ self.castles = old_castles & ~mask
614
+
615
+ old_pieces = self.pieces
616
+ ours = [x for x in old_pieces[moved_colour] if x[1] != s and x[1] != rs]
617
+ ours.append((end_piece, e))
618
+ if rook:
619
+ ours.append((rook, re))
620
+ if E or ep_taken:
621
+ gone = ep_position if ep_taken else e
622
+ theirs = [x for x in old_pieces[1 - moved_colour] if x[1] != gone]
623
+ else:
624
+ theirs = old_pieces[1 - moved_colour]
625
+ self.pieces = [ours, theirs] if moved_colour == 0 else [theirs, ours]
626
+ return (s, e, S, E, ep, old_castles, rs, re, rook, ep_position, ep_taken, old_pieces)
627
+
628
+ def unmake(self, move):
629
+ """Take back a move `make` played."""
630
+ s, e, S, E, ep, castles, rs, re, rook, ep_position, ep_taken, pieces = move
631
+ board = self.board
632
+ if ep_position:
633
+ board[ep_position] = ep_taken
634
+ board[s] = S
635
+ board[e] = E
636
+ if rs:
637
+ board[rs] = rook
638
+ board[re] = 0
639
+ self.pieces = pieces
640
+ self.castles = castles
641
+
642
+ # --- p4_optimise_piece_list ----------------------------------------------
643
+
644
+ def optimise_piece_list(self):
645
+ """Order each side's pieces so the likeliest good moves come first."""
646
+ movelists = (self.parse(0, 0, 0), self.parse(1, 0, 0))
647
+ board = self.board
648
+ for colour in (0, 1):
649
+ our_values = self.values[colour]
650
+ pieces = self.pieces[colour]
651
+ movelist = movelists[colour]
652
+ threats = movelists[1 - colour]
653
+ scores = {}
654
+ for piece, pos in pieces:
655
+ scores[pos] = [0, piece, pos, 0]
656
+ # The best score for each piece by pure static weights, ignoring
657
+ # captures, which have their own path to the top.
658
+ for score, s, e in movelist:
659
+ if not board[e]:
660
+ x = scores[s]
661
+ if score > x[0]:
662
+ x[0] = score
663
+ # Moving out of a threat is worth considering. (p4wn meant to
664
+ # weigh a pawn's threat more, but its test is always true.)
665
+ for _score, s, e in threats:
666
+ x = scores.get(e)
667
+ if x is not None and x[3] < 0.01:
668
+ x[3] = 0.01
669
+ ordered = []
670
+ for i in range(20, 100):
671
+ x = scores.get(i)
672
+ if x is not None:
673
+ x[0] += x[3] * our_values[x[1]]
674
+ ordered.append(x)
675
+ # MicroPython's sort isn't stable: the square breaks ties, so
676
+ # every interpreter searches in the same order.
677
+ ordered.sort(key=lambda x: (x[0], x[2]))
678
+ self.pieces[colour] = [(x[1], x[2]) for x in ordered]
679
+
680
+ # --- p4_alphabeta_treeclimber ----------------------------------------------
681
+
682
+ def _climb(self, count, colour, score, s, e, alpha, beta):
683
+ self.nodes += 1
684
+ if not (self.nodes & 63) and (self.stop or (self._deadline is not None and ticks_diff(ticks_ms(), self._deadline) > 0)):
685
+ raise Stopped()
686
+ move = self.make(s, e, QUEEN)
687
+ movelist = self.parse(colour, move[4], -score)
688
+ if count:
689
+ # Branch nodes.
690
+ ncolour = 1 - colour
691
+ climb = self._climb
692
+ for mscore, ms, me in movelist:
693
+ if mscore > WIN: # we won! Don't look further.
694
+ alpha = KING_VALUE
695
+ break
696
+ t = -climb(count - 1, ncolour, mscore, ms, me, -beta, -alpha)
697
+ if t > alpha:
698
+ alpha = t
699
+ if alpha >= beta:
700
+ break
701
+ if alpha < -WIN_NOW and not self.in_check(colour):
702
+ # Whatever we do, we lose the king; but not being in check,
703
+ # this is stalemate, and the score doesn't apply.
704
+ alpha = self.stalemate_scores[colour]
705
+ if alpha < -WIN:
706
+ # Make a distant mate seem less bad.
707
+ alpha += WIN_DECAY
708
+ else:
709
+ # Leaf nodes.
710
+ for mv in movelist:
711
+ if mv[0] > alpha:
712
+ alpha = mv[0]
713
+ if alpha >= beta:
714
+ break
715
+ self.unmake(move)
716
+ return alpha
717
+
718
+ # --- p4_findmove, with a deadline and deepening ------------------------------
719
+
720
+ def legal_moves(self, colour=None):
721
+ """``[(score, from, to), ...]``: the pseudo-legal moves that don't
722
+ leave the mover's king attacked. One move per promotion."""
723
+ if colour is None:
724
+ colour = self.to_play
725
+ out = []
726
+ for mv in self.parse(colour, self.enpassant, 0):
727
+ undo = self.make(mv[1], mv[2], QUEEN)
728
+ if not self.in_check(colour):
729
+ out.append(mv)
730
+ self.unmake(undo)
731
+ return out
732
+
733
+ def think(self, depth, ms=None, noise=0, progress=None):
734
+ """The move p4wn picks, as ``(from, to, score, depth_reached)``.
735
+
736
+ It searches one ply deeper at a time, up to *depth* (0 scores each
737
+ move by its weights alone), and stops at *ms* milliseconds, keeping
738
+ the best move of the deepest search that finished; the first always
739
+ finishes. *noise* adds up to that many points (a pawn is about 20)
740
+ at random to each move's score, so a low level misses things.
741
+ *progress(depth, from, to, score)* is called after each depth.
742
+ Returns None when there is no legal move.
743
+
744
+ The search runs on a copy, so this position is never touched, and
745
+ `halt` from another thread ends it early.
746
+ """
747
+ p = self.copy()
748
+ self._search = p
749
+ try:
750
+ return p._think(depth, ms, noise, progress)
751
+ finally:
752
+ self.nodes = p.nodes
753
+ self._search = None
754
+
755
+ def halt(self):
756
+ """End a `think` running on another thread; it returns what it has."""
757
+ p = getattr(self, "_search", None)
758
+ if p is not None:
759
+ p.stop = True
760
+
761
+ def _think(self, depth, ms, noise, progress):
762
+ self.prepare()
763
+ self.optimise_piece_list()
764
+ colour = self.to_play
765
+ self.nodes = 0
766
+ roots = self.legal_moves(colour)
767
+ if not roots:
768
+ return None
769
+
770
+ def jitter():
771
+ return self.random_int(2 * noise + 1) - noise if noise else 0
772
+
773
+ if depth <= 0:
774
+ best = None
775
+ for mv in roots:
776
+ v = mv[0] + jitter()
777
+ if best is None or v > best[2]:
778
+ best = (mv[1], mv[2], v, 0)
779
+ return best
780
+
781
+ start = ticks_ms()
782
+ result = None
783
+ order = roots
784
+ for d in range(1, depth + 1):
785
+ # The first depth always finishes; later ones stop at the deadline.
786
+ self._deadline = None if (d == 1 or ms is None) else start + ms
787
+ scored = []
788
+ alpha = MIN_SCORE
789
+ try:
790
+ for mv in order:
791
+ if noise:
792
+ # Every move gets a true score, so the noise picks
793
+ # among real alternatives.
794
+ t = -self._climb(d - 1, 1 - colour, mv[0], mv[1], mv[2], MIN_SCORE, MAX_SCORE) + jitter()
795
+ else:
796
+ t = -self._climb(d - 1, 1 - colour, mv[0], mv[1], mv[2], MIN_SCORE, -alpha)
797
+ scored.append((t, mv))
798
+ if t > alpha:
799
+ alpha = t
800
+ except Stopped:
801
+ break # the board is mid-move, but it's a copy
802
+ # Of equal scores, the move searched first stays first.
803
+ ranked = sorted(range(len(scored)), key=lambda i: (-scored[i][0], i))
804
+ best_t, best_mv = scored[ranked[0]]
805
+ result = (best_mv[1], best_mv[2], best_t, d)
806
+ order = [scored[i][1] for i in ranked]
807
+ if progress is not None:
808
+ progress(d, best_mv[1], best_mv[2], best_t)
809
+ if best_t > WIN or self.stop:
810
+ break # a mate needs no deeper look
811
+ if ms is not None and ticks_diff(ticks_ms(), start) * 4 > ms:
812
+ # The next depth takes several times as long: it wouldn't finish.
813
+ break
814
+ self._deadline = None
815
+ return result
816
+
817
+
818
+ def check_castling(board, s, colour, direction, side):
819
+ """True when *colour* attacks none of the three squares from *s*
820
+ rightwards, so a king may castle across them.
821
+
822
+ *s* is the king's square, or its destination for the queen's side;
823
+ *direction* is the castling side's forward step; *side* is -1 for the
824
+ queen's side and 1 for the king's.
825
+ """
826
+ knight = colour + KNIGHT
827
+ diag_slider = BISHOP | colour
828
+ grid_slider = ROOK | colour
829
+ king_pawn = 2 | colour
830
+ # The three squares, checked for sliders and near knights.
831
+ for p in range(s, s + 3):
832
+ e = p + direction
833
+ E = board[e]
834
+ while not E:
835
+ e += direction
836
+ E = board[e]
837
+ if (E & 23) == grid_slider:
838
+ return False
839
+ delta = direction - 1
840
+ e = p + delta
841
+ E = board[e]
842
+ while not E:
843
+ e += delta
844
+ E = board[e]
845
+ if (E & 27) == diag_slider:
846
+ return False
847
+ delta += 2
848
+ e = p + delta
849
+ E = board[e]
850
+ while not E:
851
+ e += delta
852
+ E = board[e]
853
+ if (E & 27) == diag_slider:
854
+ return False
855
+ # Knights on the next row (the row after is below).
856
+ if board[p + direction - 2] == knight or board[p + direction + 2] == knight:
857
+ return False
858
+ # A pawn or king in any of five squares on the next row, or a knight on the one after.
859
+ for p in range(s + direction - 1, s + direction + 4):
860
+ if (board[p] & 23) == king_pawn or board[p + direction] == knight:
861
+ return False
862
+ # Rooks and queens along the back row, on the far side. The near side
863
+ # can't attack: the castling rook is there.
864
+ e = s + 2 if side < 0 else s
865
+ e -= side
866
+ E = board[e]
867
+ while not E:
868
+ e -= side
869
+ E = board[e]
870
+ if (E & 23) == grid_slider:
871
+ return False
872
+ return True
873
+
874
+
875
+ def insufficient_material(board):
876
+ """True when neither side has the pieces to mate: kings with at most one
877
+ knight, or bishops all on one colour of square."""
878
+ knights = False
879
+ bishops = None
880
+ for i in range(20, 100):
881
+ piece = board[i] & 14
882
+ if piece == 0 or piece == KING or board[i] == EDGE:
883
+ continue
884
+ if piece == KNIGHT:
885
+ # Only one knight of either colour, never with a bishop.
886
+ if knights or bishops is not None:
887
+ return False
888
+ knights = True
889
+ elif piece == BISHOP:
890
+ # Any number of bishops, on only one colour of square.
891
+ parity = (i & 1) ^ ((i // 10) & 1)
892
+ if knights:
893
+ return False
894
+ if bishops is None:
895
+ bishops = parity
896
+ elif bishops != parity:
897
+ return False
898
+ else:
899
+ return False
900
+ return True
901
+
902
+
903
+ def perft(pos, depth):
904
+ """How many positions *depth* plies from *pos*, every legal move and
905
+ each of a promotion's four pieces counted: the standard test of a move
906
+ generator."""
907
+ if depth == 0:
908
+ return 1
909
+ colour = pos.to_play
910
+ total = 0
911
+ for _score, s, e in pos.parse(colour, pos.enpassant, 0):
912
+ promo = (pos.board[s] & 14) == PAWN and (e > 90 or e < 30)
913
+ for piece in ((QUEEN, ROOK, BISHOP, KNIGHT) if promo else (QUEEN,)):
914
+ undo = pos.make(s, e, piece)
915
+ if not pos.in_check(colour):
916
+ if depth == 1:
917
+ total += 1
918
+ else:
919
+ saved = (pos.to_play, pos.enpassant)
920
+ pos.to_play = 1 - colour
921
+ pos.enpassant = undo[4]
922
+ total += perft(pos, depth - 1)
923
+ pos.to_play, pos.enpassant = saved
924
+ pos.unmake(undo)
925
+ return total