AEI 1.4.0__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.
- aei-1.4.0.dist-info/METADATA +97 -0
- aei-1.4.0.dist-info/RECORD +25 -0
- aei-1.4.0.dist-info/WHEEL +5 -0
- aei-1.4.0.dist-info/entry_points.txt +7 -0
- aei-1.4.0.dist-info/licenses/LICENSE.txt +39 -0
- aei-1.4.0.dist-info/top_level.txt +1 -0
- pyrimaa/__init__.py +0 -0
- pyrimaa/aei.py +413 -0
- pyrimaa/analyze.py +244 -0
- pyrimaa/board.py +1364 -0
- pyrimaa/game.py +221 -0
- pyrimaa/gameroom.py +1026 -0
- pyrimaa/postal_controller.py +135 -0
- pyrimaa/roundrobin.py +309 -0
- pyrimaa/simple_engine.py +184 -0
- pyrimaa/test_runner.py +99 -0
- pyrimaa/tests/__init__.py +0 -0
- pyrimaa/tests/socketadapter.py +56 -0
- pyrimaa/tests/test_aei.py +282 -0
- pyrimaa/tests/test_analyze.py +433 -0
- pyrimaa/tests/test_board.py +631 -0
- pyrimaa/tests/test_game.py +1135 -0
- pyrimaa/tests/test_simple_engine.py +161 -0
- pyrimaa/tests/test_util.py +85 -0
- pyrimaa/util.py +102 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: AEI
|
|
3
|
+
Version: 1.4.0
|
|
4
|
+
Summary: Arimaa Engine Interface tools
|
|
5
|
+
Author-email: Janzert <janzert@janzert.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://arimaa.janzert.com/aei
|
|
8
|
+
Project-URL: Source Code, https://github.com/janzert/aei
|
|
9
|
+
Keywords: Arimaa
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Topic :: Games/Entertainment :: Board Games
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE.txt
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: coverage[toml]>=7.0; extra == "dev"
|
|
25
|
+
Requires-Dist: ruff>=0.8.0; extra == "dev"
|
|
26
|
+
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# AEI Readme
|
|
30
|
+
|
|
31
|
+
This package provides a specification for the Arimaa Engine Interface (AEI).
|
|
32
|
+
It also includes some tools for using engines that implement AEI. Including an
|
|
33
|
+
interface to the arimaa.com gameroom. A full description of AEI can be found in
|
|
34
|
+
the file `AEI_PROTOCOL.md`.
|
|
35
|
+
|
|
36
|
+
The scripts included for working with an AEI engine are:
|
|
37
|
+
|
|
38
|
+
- `analyze` - A simple script that runs an engine and has it search a given position or move sequence.
|
|
39
|
+
- `gameroom` - AEI controller that connects to the arimaa.com gameroom and plays a game.
|
|
40
|
+
- `postal_controller` - Keeps a bot making moves as needed in any postal games it is a participant in.
|
|
41
|
+
- `pyrimaa_tests` - Test runner utility.
|
|
42
|
+
- `roundrobin` - Plays engines against each other in a round robin tournament.
|
|
43
|
+
- `simple_engine` - Very basic AEI engine, just plays random step moves.
|
|
44
|
+
|
|
45
|
+
Basic examples of using the scripts can be found in the file `USAGE.md`.
|
|
46
|
+
|
|
47
|
+
The pyrimaa package also includes modules implementing the controller side of
|
|
48
|
+
the AEI protocol (`aei.py`), the Arimaa position representation (as bitboards
|
|
49
|
+
in `board.py`), and a few utility functions for handling Arimaa timecontrols
|
|
50
|
+
(`util.py`).
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
### For CLI Tools (Recommended)
|
|
55
|
+
|
|
56
|
+
If you just want to use the command-line tools, install with [uv](https://docs.astral.sh/uv/):
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
uv tool install aei
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
This creates an isolated environment for the AEI tools and makes them available in your PATH automatically. You can immediately run commands like `analyze`, `gameroom`, `roundrobin`, etc. without managing virtual environments.
|
|
63
|
+
|
|
64
|
+
### For Library Usage or Traditional Installation
|
|
65
|
+
|
|
66
|
+
If you need to import `pyrimaa` modules in your own Python code (for example, to use `pyrimaa.aei`, `pyrimaa.board`, or `pyrimaa.util`), use:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv pip install aei
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Or install from a source directory checkout:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
uv pip install .
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Or skipping `uv` and using plain `pip`:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pip install aei
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### For Development
|
|
85
|
+
|
|
86
|
+
If you're contributing to the AEI project, install in editable mode:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
uv pip install -e .
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Or with pip:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
pip install -e .
|
|
96
|
+
```
|
|
97
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
aei-1.4.0.dist-info/licenses/LICENSE.txt,sha256=ilT6yBG0O1ctXTFz8WX05qXb1Z1TPa7YE8rf0xaTa5A,1989
|
|
2
|
+
pyrimaa/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
pyrimaa/aei.py,sha256=8tLv7MdV09z99lRSanyouMb3_tdDS56qKNMx2-oOD9s,13280
|
|
4
|
+
pyrimaa/analyze.py,sha256=CeEPyTDruVBlAmW4hWaupvWvB5mpsSAEZWBHMpYOLXY,7813
|
|
5
|
+
pyrimaa/board.py,sha256=PJc1GUyBAUO-W3Pxyq7IMShsu8tv6UAHA3bviecQdoQ,47998
|
|
6
|
+
pyrimaa/game.py,sha256=Pmy4Pu9Ibi6pLTH704cikzM3PXprMPfvMMARY0E_kdI,8753
|
|
7
|
+
pyrimaa/gameroom.py,sha256=O7UY62UrU90iUStwhGUkg-EgiZAKV6XbI5Bq3hhlnHo,38856
|
|
8
|
+
pyrimaa/postal_controller.py,sha256=-8KuNS8Du3yKa0wk05TuevFjxED3bMdlVOconPx9n0Y,4822
|
|
9
|
+
pyrimaa/roundrobin.py,sha256=nvXlVM__Xfk5FCKQ3QfdXW_2vdzglY7ZkCZ1rYI0Lc4,10347
|
|
10
|
+
pyrimaa/simple_engine.py,sha256=gl2sNldPVVjn8MslRyHVfzha1eF-n3bjnYspbh-me5s,5471
|
|
11
|
+
pyrimaa/test_runner.py,sha256=b1Op-VD4hf_5AO4Ypc-4miwMupkOaloMfRQMwfLfnjU,2799
|
|
12
|
+
pyrimaa/util.py,sha256=DlnPh_8YB9xVAsVL_gJ7dRPJ3EA6CEhE8HPKLJTT_aI,3203
|
|
13
|
+
pyrimaa/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
pyrimaa/tests/socketadapter.py,sha256=jhpXAptnlPOvDIS4jkXlCsQ8WqKVGUIiDyySVFZ4SpE,1453
|
|
15
|
+
pyrimaa/tests/test_aei.py,sha256=vmsWv9QnDJUS4HCpqPvQLtLiMlvqboKQ_8BgNTfXoTY,8664
|
|
16
|
+
pyrimaa/tests/test_analyze.py,sha256=ij_Hose3E3eaQyWiusFMdp8bMGlgOxT7iZN6wnWbCQE,13914
|
|
17
|
+
pyrimaa/tests/test_board.py,sha256=X16fdEYk2CpVgv9tcN27ciziUpF5s5XDLB6K8koraI4,22459
|
|
18
|
+
pyrimaa/tests/test_game.py,sha256=QOisCN2scNSuh1SHCPh82mERnGfjelG9m1nPOVV2_eY,29455
|
|
19
|
+
pyrimaa/tests/test_simple_engine.py,sha256=SNXowam26nz4BhS3PVpQenA6WgYjqvjN9HMc-6R7VuA,5625
|
|
20
|
+
pyrimaa/tests/test_util.py,sha256=h-VSYVFR2eS0L_XE_Ehsz-BGUt-8-YWUMOur9-lNDdk,3096
|
|
21
|
+
aei-1.4.0.dist-info/METADATA,sha256=NgFjaRSwicc7_QIz6XREH0vCJCE8iT5dtyMDVcgVOUg,3232
|
|
22
|
+
aei-1.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
23
|
+
aei-1.4.0.dist-info/entry_points.txt,sha256=stW62pDWqAuKR180mzs_FB-_zK_5kO-Yj6Vmk3Hhwhk,254
|
|
24
|
+
aei-1.4.0.dist-info/top_level.txt,sha256=3v_hVz-JMoUJHZa3C8vgzmaxrG3AOFgS1BeEGxrmClA,8
|
|
25
|
+
aei-1.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
This software is provided under the MIT license below. The notice of
|
|
2
|
+
authorization for use of the game Arimaa is given after the license.
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
Software License:
|
|
6
|
+
Copyright 2008-2026 Brian Haskin Jr.
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
9
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
10
|
+
in the Software without restriction, including without limitation the rights
|
|
11
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
12
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
13
|
+
furnished to do so, subject to the following conditions:
|
|
14
|
+
|
|
15
|
+
The above copyright notice and this permission notice shall be included in
|
|
16
|
+
all copies or substantial portions of the Software.
|
|
17
|
+
|
|
18
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
19
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
20
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
21
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
22
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
23
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
24
|
+
THE SOFTWARE.
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
Arimaa authorization:
|
|
28
|
+
This software is being provided with a written authorization from Arimaa.com
|
|
29
|
+
and in compliance with "Section 3 of the Arimaa Public License". Authorization
|
|
30
|
+
#90819. Any rights granted by the end user license of this software apply only
|
|
31
|
+
to this software and do not extend to the Arimaa game. The end user is
|
|
32
|
+
responsible to ensure that any derivate work based on this software complies
|
|
33
|
+
with the Arimaa Public License and obtain any authorization or license by
|
|
34
|
+
contacting Arimaa.com.
|
|
35
|
+
The Arimaa name is a trademark of Arimaa.com. The Arimaa game is patented. The
|
|
36
|
+
Arimaa game rules, the Arimaa board design and the Arimaa piece design are
|
|
37
|
+
copyright protected. The Arimaa Public License allows cost free use of the
|
|
38
|
+
Arimaa game for non-commercial use.
|
|
39
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pyrimaa
|
pyrimaa/__init__.py
ADDED
|
File without changes
|
pyrimaa/aei.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import socket
|
|
3
|
+
import sys
|
|
4
|
+
import time
|
|
5
|
+
from queue import Empty, Queue
|
|
6
|
+
from subprocess import PIPE, Popen
|
|
7
|
+
from threading import Event, Thread
|
|
8
|
+
|
|
9
|
+
if sys.platform == "win32":
|
|
10
|
+
import ctypes
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _get_child_pids():
|
|
15
|
+
class ProcessEntry(ctypes.Structure):
|
|
16
|
+
_fields_ = [
|
|
17
|
+
("dwSize", ctypes.c_ulong),
|
|
18
|
+
("cntUsage", ctypes.c_ulong),
|
|
19
|
+
("th32ProcessID", ctypes.c_ulong),
|
|
20
|
+
("th32DefaultHeapID", ctypes.c_void_p),
|
|
21
|
+
("th32ModuleID", ctypes.c_ulong),
|
|
22
|
+
("cntThreads", ctypes.c_ulong),
|
|
23
|
+
("th32ParentProcessID", ctypes.c_ulong),
|
|
24
|
+
("pcPriClassBase", ctypes.c_long),
|
|
25
|
+
("dwFlags", ctypes.c_ulong),
|
|
26
|
+
("szExeFile", ctypes.c_char * 260),
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
TH32CS_SNAPPROCESS = 0x2
|
|
30
|
+
kernel32 = ctypes.windll.kernel32
|
|
31
|
+
psnap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
|
|
32
|
+
childIDs = defaultdict(list)
|
|
33
|
+
entry = ProcessEntry()
|
|
34
|
+
entry.dwSize = ctypes.sizeof(ProcessEntry)
|
|
35
|
+
kernel32.Process32First.argtypes = [ctypes.c_ulong, ctypes.POINTER(ProcessEntry)]
|
|
36
|
+
if kernel32.Process32First(psnap, ctypes.byref(entry)) == 0:
|
|
37
|
+
errno = kernel32.GetLastError()
|
|
38
|
+
raise OSError(f"Received error from Process32First, {errno}")
|
|
39
|
+
else:
|
|
40
|
+
childIDs[entry.th32ParentProcessID].append(entry.th32ProcessID)
|
|
41
|
+
while kernel32.Process32Next(psnap, ctypes.pointer(entry)):
|
|
42
|
+
childIDs[entry.th32ParentProcessID].append(entry.th32ProcessID)
|
|
43
|
+
errno = kernel32.GetLastError()
|
|
44
|
+
if errno != 18:
|
|
45
|
+
raise OSError(f"Received error from Process32Next, {errno}")
|
|
46
|
+
kernel32.CloseHandle(psnap)
|
|
47
|
+
return childIDs
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _kill_proc_tree(pid, cid_map=None):
|
|
51
|
+
if cid_map is None:
|
|
52
|
+
cid_map = _get_child_pids()
|
|
53
|
+
if len(cid_map[pid]) > 0:
|
|
54
|
+
for cid in cid_map[pid]:
|
|
55
|
+
_kill_proc_tree(cid, cid_map)
|
|
56
|
+
PROCESS_TERMINATE = 0x1
|
|
57
|
+
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid)
|
|
58
|
+
if handle is not None:
|
|
59
|
+
ctypes.windll.kernel32.TerminateProcess(handle, -1)
|
|
60
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
61
|
+
else:
|
|
62
|
+
raise OSError(f"Could not kill process, {pid}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
START_TIME = 5.0
|
|
66
|
+
INIT_TIME = 15.0
|
|
67
|
+
STOP_TIME = 5.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class EngineException(Exception):
|
|
71
|
+
def __init__(self, message=None):
|
|
72
|
+
self.message = message
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def find_line_end(posline):
|
|
76
|
+
nloc = posline.find("\n")
|
|
77
|
+
rloc = posline.find("\r")
|
|
78
|
+
return max(nloc, rloc)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _ProcCom(Thread):
|
|
82
|
+
def __init__(self, proc, log):
|
|
83
|
+
Thread.__init__(self)
|
|
84
|
+
self.proc = proc
|
|
85
|
+
self.log = log
|
|
86
|
+
self.outq = Queue()
|
|
87
|
+
self.stop = Event()
|
|
88
|
+
self.daemon = True
|
|
89
|
+
|
|
90
|
+
def run(self):
|
|
91
|
+
while not self.stop.is_set() and self.proc.poll() is None:
|
|
92
|
+
msg = self.proc.stdout.readline()
|
|
93
|
+
if self.log:
|
|
94
|
+
self.log.debug(f"Received from bot: {repr(msg)}")
|
|
95
|
+
self.outq.put(msg.strip())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class StdioEngine:
|
|
99
|
+
def __init__(self, cmdline, log=None):
|
|
100
|
+
proc = Popen(cmdline, shell=True, stdin=PIPE, stdout=PIPE, text=True)
|
|
101
|
+
self.proc = proc
|
|
102
|
+
self.log = log
|
|
103
|
+
self.proc_com = _ProcCom(proc, log)
|
|
104
|
+
self.proc_com.start()
|
|
105
|
+
self.active = True
|
|
106
|
+
|
|
107
|
+
def __del__(self):
|
|
108
|
+
try:
|
|
109
|
+
if self.active:
|
|
110
|
+
self.cleanup()
|
|
111
|
+
except AttributeError:
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
def is_running(self):
|
|
115
|
+
return self.proc.poll() is None
|
|
116
|
+
|
|
117
|
+
def send(self, msg):
|
|
118
|
+
if self.log:
|
|
119
|
+
self.log.debug(f"Sending to bot: {repr(msg)}")
|
|
120
|
+
self.proc.stdin.write(msg)
|
|
121
|
+
self.proc.stdin.flush()
|
|
122
|
+
|
|
123
|
+
def readline(self, timeout=None):
|
|
124
|
+
try:
|
|
125
|
+
msg = self.proc_com.outq.get(timeout=timeout)
|
|
126
|
+
except Empty:
|
|
127
|
+
raise socket.timeout() from None
|
|
128
|
+
return msg
|
|
129
|
+
|
|
130
|
+
def waitfor(self, expect, timeout=0.5):
|
|
131
|
+
endtime = time.time() + timeout
|
|
132
|
+
response = []
|
|
133
|
+
while time.time() <= endtime:
|
|
134
|
+
wait = endtime - time.time()
|
|
135
|
+
try:
|
|
136
|
+
line = self.readline(timeout=wait)
|
|
137
|
+
response.append(line)
|
|
138
|
+
if line.lstrip().lower().startswith(expect):
|
|
139
|
+
break
|
|
140
|
+
except socket.timeout:
|
|
141
|
+
pass
|
|
142
|
+
else:
|
|
143
|
+
raise EngineException("Engine did not respond in alloted time.")
|
|
144
|
+
return response
|
|
145
|
+
|
|
146
|
+
def cleanup(self):
|
|
147
|
+
self.active = False
|
|
148
|
+
self.proc_com.stop.set()
|
|
149
|
+
if self.proc.poll() is None:
|
|
150
|
+
if sys.platform == "win32":
|
|
151
|
+
_kill_proc_tree(self.proc.pid)
|
|
152
|
+
else:
|
|
153
|
+
self.proc.terminate()
|
|
154
|
+
stop_time = time.time() + STOP_TIME
|
|
155
|
+
while time.time() < stop_time and self.proc.poll() is None:
|
|
156
|
+
pass
|
|
157
|
+
if self.proc.poll() is None:
|
|
158
|
+
self.proc.kill()
|
|
159
|
+
for stream in [self.proc.stdin, self.proc.stdout]:
|
|
160
|
+
try:
|
|
161
|
+
stream.close()
|
|
162
|
+
except Exception:
|
|
163
|
+
pass
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class SocketEngine:
|
|
167
|
+
def __init__(self, con, proc=None, legacy_mode=False, log=None):
|
|
168
|
+
if len(con) != 2 or not hasattr(con[0], "settimeout"):
|
|
169
|
+
address = ("127.0.0.1", 40015)
|
|
170
|
+
listensock = socket.socket()
|
|
171
|
+
while True:
|
|
172
|
+
try:
|
|
173
|
+
listensock.bind(address)
|
|
174
|
+
listensock.listen(1)
|
|
175
|
+
listensock.settimeout(30)
|
|
176
|
+
break
|
|
177
|
+
except OSError as exc:
|
|
178
|
+
if hasattr(exc, "args") and (
|
|
179
|
+
exc.args[0] == 10048 or exc.args[0] == 98
|
|
180
|
+
):
|
|
181
|
+
address = (address[0], address[1] + 1)
|
|
182
|
+
else:
|
|
183
|
+
raise
|
|
184
|
+
if legacy_mode:
|
|
185
|
+
botargs = con + " 127.0.0.1 " + str(address[1])
|
|
186
|
+
else:
|
|
187
|
+
botargs = con + " --server 127.0.0.1 --port " + str(address[1])
|
|
188
|
+
if con == "listen":
|
|
189
|
+
print(f"Listening on {address[0]}:{address[1]}")
|
|
190
|
+
proc = None
|
|
191
|
+
else:
|
|
192
|
+
proc = Popen(botargs, shell=True)
|
|
193
|
+
con = listensock.accept()
|
|
194
|
+
listensock.close()
|
|
195
|
+
|
|
196
|
+
self.proc = proc
|
|
197
|
+
self.log = log
|
|
198
|
+
self.sock = con[0]
|
|
199
|
+
self.address = con[1]
|
|
200
|
+
self.buf = ""
|
|
201
|
+
self.active = True
|
|
202
|
+
|
|
203
|
+
def __del__(self):
|
|
204
|
+
if self.active:
|
|
205
|
+
self.cleanup()
|
|
206
|
+
|
|
207
|
+
def is_running(self):
|
|
208
|
+
return self.proc.poll() is None
|
|
209
|
+
|
|
210
|
+
def send(self, msg):
|
|
211
|
+
if self.log is not None:
|
|
212
|
+
self.log.debug(f"Sending to bot: {repr(msg)}")
|
|
213
|
+
self.sock.sendall(msg.encode("utf-8"))
|
|
214
|
+
|
|
215
|
+
def readline(self, timeout=None):
|
|
216
|
+
sock = self.sock
|
|
217
|
+
buf = self.buf
|
|
218
|
+
|
|
219
|
+
if buf:
|
|
220
|
+
lineend = find_line_end(buf)
|
|
221
|
+
if lineend != -1:
|
|
222
|
+
self.buf = buf[lineend + 1 :]
|
|
223
|
+
return buf[: lineend + 1].strip()
|
|
224
|
+
|
|
225
|
+
if timeout is None:
|
|
226
|
+
endtime = None
|
|
227
|
+
sock.settimeout(None)
|
|
228
|
+
else:
|
|
229
|
+
endtime = time.time() + timeout
|
|
230
|
+
response = buf
|
|
231
|
+
first = True
|
|
232
|
+
while first or endtime is None or time.time() <= endtime:
|
|
233
|
+
try:
|
|
234
|
+
if endtime is None:
|
|
235
|
+
sock.settimeout(None)
|
|
236
|
+
else:
|
|
237
|
+
wait = endtime - time.time()
|
|
238
|
+
if wait < 0:
|
|
239
|
+
wait = 0
|
|
240
|
+
sock.settimeout(wait)
|
|
241
|
+
packet = sock.recv(4096).decode("utf-8")
|
|
242
|
+
if self.log:
|
|
243
|
+
self.log.debug(f"Received from bot: {repr(packet)}")
|
|
244
|
+
response += packet
|
|
245
|
+
if find_line_end(response) != -1:
|
|
246
|
+
break
|
|
247
|
+
except socket.timeout:
|
|
248
|
+
pass
|
|
249
|
+
except OSError as exc:
|
|
250
|
+
if hasattr(exc, "args") and (exc.args[0] == 10035 or exc.args[0] == 11):
|
|
251
|
+
pass
|
|
252
|
+
else:
|
|
253
|
+
raise
|
|
254
|
+
first = False
|
|
255
|
+
else:
|
|
256
|
+
raise socket.timeout()
|
|
257
|
+
line = response[: find_line_end(response) + 1]
|
|
258
|
+
self.buf = response[len(line) :]
|
|
259
|
+
return line.strip()
|
|
260
|
+
|
|
261
|
+
def waitfor(self, expect, timeout=0.5):
|
|
262
|
+
endtime = time.time() + timeout
|
|
263
|
+
response = []
|
|
264
|
+
while time.time() <= endtime:
|
|
265
|
+
wait = endtime - time.time()
|
|
266
|
+
try:
|
|
267
|
+
line = self.readline(timeout=wait)
|
|
268
|
+
response.append(line)
|
|
269
|
+
if line.lstrip().lower().startswith(expect):
|
|
270
|
+
break
|
|
271
|
+
except socket.timeout:
|
|
272
|
+
pass
|
|
273
|
+
else:
|
|
274
|
+
raise EngineException("Engine did not respond in alloted time.")
|
|
275
|
+
return response
|
|
276
|
+
|
|
277
|
+
def cleanup(self):
|
|
278
|
+
self.active = False
|
|
279
|
+
self.sock.close()
|
|
280
|
+
if self.proc and self.proc.poll() is None:
|
|
281
|
+
if sys.platform == "win32":
|
|
282
|
+
_kill_proc_tree(self.proc.pid)
|
|
283
|
+
else:
|
|
284
|
+
self.proc.terminate()
|
|
285
|
+
stop_time = time.time() + STOP_TIME
|
|
286
|
+
while time.time() < stop_time and self.proc.poll() is None:
|
|
287
|
+
pass
|
|
288
|
+
if self.proc.poll() is None:
|
|
289
|
+
self.proc.kill()
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def get_engine(channel, cmd, logname=None):
|
|
293
|
+
"""Get the appropriate Engine for a given communication channel.
|
|
294
|
+
Valid channel types are 'stdio', 'socket' and '2008cc'
|
|
295
|
+
"""
|
|
296
|
+
if logname is not None:
|
|
297
|
+
log = logging.getLogger(logname)
|
|
298
|
+
else:
|
|
299
|
+
log = None
|
|
300
|
+
if channel == "stdio":
|
|
301
|
+
engine = StdioEngine(cmd, log=log)
|
|
302
|
+
elif channel == "socket":
|
|
303
|
+
engine = SocketEngine(cmd, log=log)
|
|
304
|
+
elif channel == "2008cc":
|
|
305
|
+
engine = SocketEngine(cmd, legacy_mode=True, log=log)
|
|
306
|
+
else:
|
|
307
|
+
raise ValueError(f"Unrecognized channel given to get_engine ({channel})")
|
|
308
|
+
return engine
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class EngineResponse:
|
|
312
|
+
def __init__(self, msg_type):
|
|
313
|
+
self.type = msg_type
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
class EngineController:
|
|
317
|
+
def __init__(self, engine):
|
|
318
|
+
self.engine = engine
|
|
319
|
+
try:
|
|
320
|
+
engine.send("aei\n")
|
|
321
|
+
except OSError as exc:
|
|
322
|
+
raise EngineException("Could not send initial message to engine.") from exc
|
|
323
|
+
try:
|
|
324
|
+
response = engine.waitfor("aeiok", START_TIME)
|
|
325
|
+
except socket.timeout as exc:
|
|
326
|
+
raise EngineException("No aeiok received from engine.") from exc
|
|
327
|
+
|
|
328
|
+
self.protocol_version = 0
|
|
329
|
+
if response[0].lstrip().startswith("protocol-version"):
|
|
330
|
+
version = response[0].lstrip().split()[1].strip()
|
|
331
|
+
response = response[1:]
|
|
332
|
+
self.protocol_version = 1
|
|
333
|
+
if engine.log:
|
|
334
|
+
if version != "1":
|
|
335
|
+
engine.log.warn(
|
|
336
|
+
f"Unrecognized protocol version from engine, {version}."
|
|
337
|
+
)
|
|
338
|
+
engine.log.info("Setting aei protocol to version 1")
|
|
339
|
+
|
|
340
|
+
self.ident = {}
|
|
341
|
+
for line in response:
|
|
342
|
+
line = line.lstrip()
|
|
343
|
+
if line.startswith("id"):
|
|
344
|
+
var, val = line[2:].strip().split(None, 1)
|
|
345
|
+
self.ident[var] = val
|
|
346
|
+
|
|
347
|
+
self.isready(INIT_TIME)
|
|
348
|
+
|
|
349
|
+
def cleanup(self):
|
|
350
|
+
self.engine.cleanup()
|
|
351
|
+
|
|
352
|
+
def is_running(self):
|
|
353
|
+
return self.engine.is_running()
|
|
354
|
+
|
|
355
|
+
def _parse_resp(self, rstr):
|
|
356
|
+
resp = EngineResponse(rstr.split()[0].lower())
|
|
357
|
+
if resp.type == "info":
|
|
358
|
+
resp.message = rstr[rstr.find("info") + len("info") :].strip()
|
|
359
|
+
if resp.type == "log":
|
|
360
|
+
resp.message = rstr[rstr.find("log") + len("log") :].strip()
|
|
361
|
+
if resp.type == "bestmove":
|
|
362
|
+
resp.move = rstr[rstr.find("bestmove") + len("bestmove") :].strip()
|
|
363
|
+
return resp
|
|
364
|
+
|
|
365
|
+
def get_response(self, timeout=None):
|
|
366
|
+
rstr = self.engine.readline(timeout=timeout)
|
|
367
|
+
if rstr == "":
|
|
368
|
+
raise socket.timeout()
|
|
369
|
+
return self._parse_resp(rstr)
|
|
370
|
+
|
|
371
|
+
def isready(self, timeout=15):
|
|
372
|
+
self.engine.send("isready\n")
|
|
373
|
+
rstrs = self.engine.waitfor("readyok", timeout)
|
|
374
|
+
if rstrs[-1].strip().lower() != "readyok":
|
|
375
|
+
raise EngineException(f"Unexpected final response to isready ({rstrs[-1]})")
|
|
376
|
+
responses = []
|
|
377
|
+
for rstr in rstrs[:-1]:
|
|
378
|
+
responses.append(self._parse_resp(rstr))
|
|
379
|
+
return responses
|
|
380
|
+
|
|
381
|
+
def newgame(self):
|
|
382
|
+
self.engine.send("newgame\n")
|
|
383
|
+
|
|
384
|
+
def makemove(self, move):
|
|
385
|
+
self.engine.send(f"makemove {move}\n")
|
|
386
|
+
|
|
387
|
+
def setposition(self, pos):
|
|
388
|
+
side_colors = "wb"
|
|
389
|
+
if self.protocol_version != 0:
|
|
390
|
+
side_colors = "gs"
|
|
391
|
+
self.engine.send(
|
|
392
|
+
f"setposition {side_colors[pos.color]} {pos.board_to_str('short')}\n"
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
def go(self, searchtype=None):
|
|
396
|
+
gocmd = ["go"]
|
|
397
|
+
if searchtype == "ponder":
|
|
398
|
+
gocmd.append(" ponder")
|
|
399
|
+
gocmd.append("\n")
|
|
400
|
+
gocmd = "".join(gocmd)
|
|
401
|
+
self.engine.send(gocmd)
|
|
402
|
+
|
|
403
|
+
def stop(self):
|
|
404
|
+
self.engine.send("stop\n")
|
|
405
|
+
|
|
406
|
+
def setoption(self, name, value=None):
|
|
407
|
+
setoptcmd = f"setoption name {name}"
|
|
408
|
+
if value is not None:
|
|
409
|
+
setoptcmd += f" value {value}"
|
|
410
|
+
self.engine.send(setoptcmd + "\n")
|
|
411
|
+
|
|
412
|
+
def quit(self):
|
|
413
|
+
self.engine.send("quit\n")
|