-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstarter.py
More file actions
254 lines (232 loc) · 9.24 KB
/
starter.py
File metadata and controls
254 lines (232 loc) · 9.24 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
"""
This is the main entry point for the SoCha application.
"""
import argparse
import datetime
import json
import logging
import urllib.request
from importlib.metadata import version, PackageNotFoundError
from socha.api.networking.game_client import GameClient, IClientHandler
from socha.utils.package_builder import SochaPackageBuilder
class Starter:
"""
When this is called, the client will try to connect to the server and join a game.
When successful, the client will start the loop and call the on_update and calculate_move methods,
if the server sends updates.
"""
def __init__(
self,
logic: IClientHandler,
host: str = "localhost",
port: int = 13050,
reservation: str = None,
room_id: str = None,
password: str = None,
survive: bool = False,
auto_reconnect: bool = False,
headless: bool = False,
log: bool = False,
verbose: bool = False,
build: bool = False,
directory: str = None,
architecture: str = None,
log_level: int = logging.INFO,
python_version: str = '3.10',
):
"""
All these arguments can be overwritten, when parsed via start arguments,
or you initialize this class with the desired values.
Args:
logic: Your logic the client will call, if moves are requested.
host: The host that the client should connect to.
port: The port of the host.
reservation: Reservation code for a prepared game.
room_id: Room ID the client will try to connect.
password: Password for the server for authentication as admin.
survive: If True the client keep running, even if the connection to the server is terminated.
auto_reconnect: If True the client will try to reconnect to the server, if the connection is lost.
headless: If True the client will not use the penguin plugin.
log: If True the client write a log file to the current directory.
verbose: Verbose option for logging.
build: If set, the client will build a zip package with the given name.
python_version: When building, takes string for specified python version. Standard: "3.10".
"""
VERBOSE = 15
logging.addLevelName(VERBOSE, "VERBOSE")
args = self._handle_start_args()
self.write_log: bool = args.log or log
self.verbose = args.verbose or verbose
self.log_level = args.log_level or log_level
self._setup_debugger(self.verbose, self.log_level)
self.check_socha_version()
self.directory: str = args.directory or directory
self.architecture: str = args.architecture or architecture
self.build: str = args.build or build
self.python_version: str = args.python_version or python_version
if self.build:
builder = SochaPackageBuilder(self.directory, self.architecture, self.python_version)
builder.build_package()
exit(0)
self.host: str = args.host or host
self.port: int = args.port or port
self.reservation: str = args.reservation or reservation
self.room_id: str = args.room or room_id
if self.room_id and self.reservation:
logging.warning(
"The room ID is not taken into account because a reservation is available."
)
self.password: str = args.password or password
if self.password and (self.reservation or self.room_id):
logging.warning(
"The password is not taken into account because a reservation or Room ID is available."
)
self.survive: bool = args.survive or survive
self.auto_reconnect: bool = args.auto_reconnect or auto_reconnect
self.headless: bool = args.headless or headless
self.client = GameClient(
host=self.host,
port=self.port,
handler=logic,
reservation=self.reservation,
room_id=room_id,
password=self.password,
auto_reconnect=self.auto_reconnect,
survive=self.survive,
headless=self.headless,
)
self.client.join()
self.client.start()
def _setup_debugger(self, verbose: bool, log_level: int):
if verbose:
level: int = logging.DEBUG
else:
level: int = log_level
if self.write_log:
now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
logging.basicConfig(
filename=f"log{now}",
level=level,
format="%(asctime)s: %(levelname)s - %(message)s",
)
logging.getLogger().addHandler(logging.StreamHandler())
else:
logging.basicConfig(
level=level, format="%(asctime)s: %(levelname)s - %(message)s"
)
logging.info("Starting...")
logging.info(
"We would greatly appreciate it if you could share any issues "
"or feature requests you may have regarding socha by either creating "
"an issue on our GitHub repository or contributing to the project."
"\n(https://github.com/maxblan/socha-python-client)"
)
@staticmethod
def check_socha_version():
package_name = "socha"
try:
installed_version = version(package_name)
# trunk-ignore(bandit/B310)
response = urllib.request.urlopen(
f"https://pypi.org/pypi/{package_name}/json"
)
json_data = json.loads(response.read())
latest_version = json_data["info"]["version"]
if installed_version != latest_version:
logging.warning(
f"A newer version ({latest_version}) of {package_name} is available. You have version "
f"{installed_version}."
)
else:
logging.info(
f"You're running the latest version of {package_name} ({latest_version})"
)
except PackageNotFoundError:
logging.error(f"{package_name} is not installed.")
except urllib.error.URLError as e:
logging.warning(
f"Could not check the latest version of {package_name} due to {type(e).__name__}: {e}"
)
@staticmethod
def _handle_start_args():
parser = argparse.ArgumentParser(
description="All arguments are optional.",
add_help=False,
epilog="Please make sure that the server is already running, "
"before you start your player.",
)
parser.add_argument("--help", action="help", help="Prints this help message.")
parser.add_argument(
"-h", "--host", help="The host to connect to. The default is 'localhost'."
)
parser.add_argument(
"-p", "--port", help="The port of the host. The default is 13050.", type=int
)
parser.add_argument(
"-r",
"--reservation",
help="Reservation code for a prepared game.",
type=str,
)
parser.add_argument(
"-R", "--room", help="Room Id the client will try to connect.", type=str
)
parser.add_argument(
"-P",
"--password",
help="Password which will be used to authenticate with the server.",
type=str,
)
parser.add_argument(
"-s",
"--survive",
action="store_true",
help="If present the client will keep running, even if the connection to the server is "
"terminated.",
)
parser.add_argument(
"-l",
"--log",
action="store_true",
help="If present the client will write a log file to the current directory.",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Verbose option for logging. "
"This cancels out the log-level argument.",
)
parser.add_argument("-L", "--log_level", help="Sets the log level.", type=int)
parser.add_argument(
"--auto-reconnect",
action="store_true",
help="Automatically reconnect to the server if the connection is lost.",
)
parser.add_argument(
"--headless",
action="store_true",
help="Starts the client without the penguin plugin.",
)
parser.add_argument(
"-b",
"--build",
action="store_true",
help="Builds the this script into a package with all its dependencies.",
)
parser.add_argument(
"-d",
"--directory",
help="Specifies the name of the directory for the build package.",
)
parser.add_argument(
"-a",
"--architecture",
help="Specifies the build architecture (e.g.: manylinux2014_x86_64).",
)
parser.add_argument(
"-pyv",
"--python-version",
help="Specifies the build python version (e.g.: 3.10 - this is standard).",
)
return parser.parse_args()