6 from plomrogue.io_tcp import PlomSocket
7 from plomrogue.game import GameBase
8 from plomrogue.parser import Parser
9 from plomrogue.mapping import YX, MapGeometrySquare, MapGeometryHex
10 from plomrogue.things import ThingBase
11 from plomrogue.misc import quote
13 def cmd_TURN(game, n):
17 game.turn_complete = False
18 cmd_TURN.argtypes = 'int:nonneg'
20 def cmd_LOGIN_OK(game):
21 game.tui.switch_mode('post_login_wait')
22 game.tui.send('GET_GAMESTATE')
23 game.tui.log_msg('@ welcome')
24 cmd_LOGIN_OK.argtypes = ''
26 def cmd_CHAT(game, msg):
27 game.tui.log_msg('# ' + msg)
28 game.tui.do_refresh = True
29 cmd_CHAT.argtypes = 'string'
31 def cmd_PLAYER_ID(game, player_id):
32 game.player_id = player_id
33 cmd_PLAYER_ID.argtypes = 'int:nonneg'
35 def cmd_THING_POS(game, thing_id, position):
36 t = game.get_thing(thing_id, True)
38 cmd_THING_POS.argtypes = 'int:nonneg yx_tuple:nonneg'
40 def cmd_THING_NAME(game, thing_id, name):
41 t = game.get_thing(thing_id, True)
43 cmd_THING_NAME.argtypes = 'int:nonneg string'
45 def cmd_MAP(game, geometry, size, content):
46 map_geometry_class = globals()['MapGeometry' + geometry]
47 game.map_geometry = map_geometry_class(size)
48 game.map_content = content
49 if type(game.map_geometry) == MapGeometrySquare:
50 game.tui.movement_keys = {
56 elif type(game.map_geometry) == MapGeometryHex:
57 game.tui.movement_keys = {
65 cmd_MAP.argtypes = 'string:map_geometry yx_tuple:pos string'
67 def cmd_GAME_STATE_COMPLETE(game):
69 if game.tui.mode.name == 'post_login_wait':
70 game.tui.switch_mode('play')
72 if game.tui.mode.shows_info:
74 player = game.get_thing(game.player_id, False)
75 if player.position in game.portals:
76 #host, port = game.portals[player.position].split(':')
77 game.tui.teleport_target_host = game.portals[player.position]
78 game.tui.teleport_target_port = 5000
79 game.tui.switch_mode('teleport')
80 game.turn_complete = True
81 game.tui.do_refresh = True
82 cmd_GAME_STATE_COMPLETE.argtypes = ''
84 def cmd_PORTAL(game, position, msg):
85 game.portals[position] = msg
86 cmd_PORTAL.argtypes = 'yx_tuple:nonneg string'
88 def cmd_PLAY_ERROR(game, msg):
90 game.tui.do_refresh = True
91 cmd_PLAY_ERROR.argtypes = 'string'
93 def cmd_GAME_ERROR(game, msg):
94 game.tui.log_msg('? game error: ' + msg)
95 game.tui.do_refresh = True
96 cmd_GAME_ERROR.argtypes = 'string'
98 def cmd_ARGUMENT_ERROR(game, msg):
99 game.tui.log_msg('? syntax error: ' + msg)
100 game.tui.do_refresh = True
101 cmd_ARGUMENT_ERROR.argtypes = 'string'
103 def cmd_ANNOTATION(game, position, msg):
104 game.info_db[position] = msg
105 if game.tui.mode.shows_info:
106 game.tui.do_refresh = True
107 cmd_ANNOTATION.argtypes = 'yx_tuple:nonneg string'
109 class Game(GameBase):
110 commands = {'LOGIN_OK': cmd_LOGIN_OK,
112 'PLAYER_ID': cmd_PLAYER_ID,
114 'THING_POS': cmd_THING_POS,
115 'THING_NAME': cmd_THING_NAME,
117 'PORTAL': cmd_PORTAL,
118 'ANNOTATION': cmd_ANNOTATION,
119 'GAME_STATE_COMPLETE': cmd_GAME_STATE_COMPLETE,
120 'ARGUMENT_ERROR': cmd_ARGUMENT_ERROR,
121 'GAME_ERROR': cmd_GAME_ERROR,
122 'PLAY_ERROR': cmd_PLAY_ERROR}
123 thing_type = ThingBase
124 turn_complete = False
126 def __init__(self, *args, **kwargs):
127 super().__init__(*args, **kwargs)
128 self.map_content = ''
133 def get_string_options(self, string_option_type):
134 if string_option_type == 'map_geometry':
135 return ['Hex', 'Square']
138 def get_command(self, command_name):
139 from functools import partial
140 f = partial(self.commands[command_name], self)
141 f.argtypes = self.commands[command_name].argtypes
148 def __init__(self, name, has_input_prompt=False, shows_info=False,
151 self.has_input_prompt = has_input_prompt
152 self.shows_info = shows_info
153 self.is_intro = is_intro
155 def __init__(self, host, port):
158 self.mode_play = self.Mode('play')
159 self.mode_study = self.Mode('study', shows_info=True)
160 self.mode_edit = self.Mode('edit')
161 self.mode_annotate = self.Mode('annotate', has_input_prompt=True, shows_info=True)
162 self.mode_portal = self.Mode('portal', has_input_prompt=True, shows_info=True)
163 self.mode_chat = self.Mode('chat', has_input_prompt=True)
164 self.mode_waiting_for_server = self.Mode('waiting_for_server', is_intro=True)
165 self.mode_login = self.Mode('login', has_input_prompt=True, is_intro=True)
166 self.mode_post_login_wait = self.Mode('post_login_wait', is_intro=True)
167 self.mode_teleport = self.Mode('teleport', has_input_prompt=True)
170 self.parser = Parser(self.game)
172 self.do_refresh = True
173 self.queue = queue.Queue()
174 self.login_name = None
175 self.switch_mode('waiting_for_server')
176 curses.wrapper(self.loop)
183 self.socket.send(msg)
184 except BrokenPipeError:
185 self.log_msg('@ server disconnected :(')
186 self.do_refresh = True
188 def log_msg(self, msg):
190 if len(self.log) > 100:
191 self.log = self.log[-100:]
193 def query_info(self):
194 self.send('GET_ANNOTATION ' + str(self.explorer))
196 def switch_mode(self, mode_name, keep_position = False):
197 self.mode = getattr(self, 'mode_' + mode_name)
198 if self.mode.shows_info and not keep_position:
199 player = self.game.get_thing(self.game.player_id, False)
200 self.explorer = YX(player.position.y, player.position.x)
201 if self.mode.name == 'waiting_for_server':
202 self.log_msg('@ waiting for server …')
203 elif self.mode.name == 'login':
205 self.send('LOGIN ' + quote(self.login_name))
207 self.log_msg('@ enter username')
208 elif self.mode.name == 'teleport':
209 self.log_msg("@ May teleport to %s:%s" % (self.teleport_target_host,
210 self.teleport_target_port));
211 self.log_msg("@ Enter 'YES!' to enthusiastically affirm.");
212 elif self.mode.name == 'annotate' and self.explorer in self.game.info_db:
213 info = self.game.info_db[self.explorer]
216 elif self.mode.name == 'portal' and self.explorer in self.game.portals:
217 self.input_ = self.game.portals[self.explorer]
220 self.log_msg("HELP:");
221 self.log_msg("chat mode commands:");
222 self.log_msg(" :nick NAME - re-name yourself to NAME");
223 self.log_msg(" :msg USER TEXT - send TEXT to USER");
224 self.log_msg(" :help - show this help");
225 self.log_msg(" :P or :play - switch to play mode");
226 self.log_msg(" :? or :study - switch to study mode");
227 self.log_msg("commands common to study and play mode:");
228 if type(self.game.map_geometry) == MapGeometrySquare:
229 self.log_msg(" w,a,s,d - move");
230 elif type(self.game.map_geometry) == MapGeometryHex:
231 self.log_msg(" e,d,c,x,s,w - move");
232 self.log_msg(" C - switch to chat mode");
233 self.log_msg("commands specific to play mode:");
234 self.log_msg(" E - write following ASCII character");
235 self.log_msg(" f - flatten surroundings");
236 self.log_msg(" ? - switch to study mode");
237 self.log_msg("commands specific to study mode:");
238 self.log_msg(" E - annotate terrain");
239 self.log_msg(" P - switch to play mode");
241 def loop(self, stdscr):
243 def safe_addstr(y, x, line):
244 if y < self.size.y - 1 or x + len(line) < self.size.x:
245 stdscr.addstr(y, x, line)
246 else: # workaround to <https://stackoverflow.com/q/7063128>
247 cut_i = self.size.x - x - 1
249 last_char = line[cut_i]
250 stdscr.addstr(y, self.size.x - 2, last_char)
251 stdscr.insstr(y, self.size.x - 2, ' ')
252 stdscr.addstr(y, x, cut)
258 for msg in self.socket.recv():
265 s = socket.create_connection((self.host, self.port))
266 self.socket = PlomSocket(s)
267 self.socket_thread = threading.Thread(target=recv_loop)
268 self.socket_thread.start()
269 self.switch_mode('login')
271 except ConnectionRefusedError:
272 self.log_msg('@ server connect failure, trying again …')
279 self.switch_mode('waiting_for_server')
282 def handle_input(msg):
283 command, args = self.parser.parse(msg)
286 def msg_into_lines_of_width(msg, width):
290 for i in range(len(msg)):
291 if x >= width or msg[i] == "\n":
301 def reset_screen_size():
302 self.size = YX(*stdscr.getmaxyx())
303 self.size = self.size - YX(self.size.y % 2, 0)
304 self.size = self.size - YX(0, self.size.x % 4)
305 self.window_width = int(self.size.x / 2)
307 def recalc_input_lines():
308 if not self.mode.has_input_prompt:
309 self.input_lines = []
311 self.input_lines = msg_into_lines_of_width(input_prompt + self.input_,
314 def move_explorer(direction):
315 target = self.game.map_geometry.move(self.explorer, direction)
317 self.explorer = target
324 for line in self.log:
325 lines += msg_into_lines_of_width(line, self.window_width)
328 max_y = self.size.y - len(self.input_lines)
329 for i in range(len(lines)):
330 if (i >= max_y - height_header):
332 safe_addstr(max_y - i - 1, self.window_width, lines[i])
335 if not self.game.turn_complete:
337 if self.explorer in self.game.portals:
338 info = 'PORTAL: ' + self.game.portals[self.explorer] + '\n'
340 info = 'PORTAL: (none)\n'
341 if self.explorer in self.game.info_db:
342 info += 'ANNOTATION: ' + self.game.info_db[self.explorer]
344 info += 'ANNOTATION: waiting …'
345 lines = msg_into_lines_of_width(info, self.window_width)
347 for i in range(len(lines)):
348 y = height_header + i
349 if y >= self.size.y - len(self.input_lines):
351 safe_addstr(y, self.window_width, lines[i])
354 y = self.size.y - len(self.input_lines)
355 for i in range(len(self.input_lines)):
356 safe_addstr(y, self.window_width, self.input_lines[i])
360 if not self.game.turn_complete:
362 safe_addstr(0, self.window_width, 'TURN: ' + str(self.game.turn))
365 safe_addstr(1, self.window_width, 'MODE: ' + self.mode.name)
368 if not self.game.turn_complete:
371 for y in range(self.game.map_geometry.size.y):
372 start = self.game.map_geometry.size.x * y
373 end = start + self.game.map_geometry.size.x
374 map_lines_split += [list(self.game.map_content[start:end])]
375 for t in self.game.things:
376 map_lines_split[t.position.y][t.position.x] = '@'
377 if self.mode.shows_info:
378 map_lines_split[self.explorer.y][self.explorer.x] = '?'
380 if type(self.game.map_geometry) == MapGeometryHex:
382 for line in map_lines_split:
383 map_lines += [indent*' ' + ' '.join(line)]
384 indent = 0 if indent else 1
386 for line in map_lines_split:
387 map_lines += [''.join(line)]
388 window_center = YX(int(self.size.y / 2),
389 int(self.window_width / 2))
390 player = self.game.get_thing(self.game.player_id, False)
391 center = player.position
392 if self.mode.shows_info:
393 center = self.explorer
394 if type(self.game.map_geometry) == MapGeometryHex:
395 center = YX(center.y, center.x * 2)
396 offset = center - window_center
397 if type(self.game.map_geometry) == MapGeometryHex and offset.y % 2:
399 term_y = max(0, -offset.y)
400 term_x = max(0, -offset.x)
401 map_y = max(0, offset.y)
402 map_x = max(0, offset.x)
403 while (term_y < self.size.y and map_y < self.game.map_geometry.size.y):
404 to_draw = map_lines[map_y][map_x:self.window_width + offset.x]
405 safe_addstr(term_y, term_x, to_draw)
412 if self.mode.has_input_prompt:
414 if self.mode.shows_info:
419 if not self.mode.is_intro:
423 curses.curs_set(False) # hide cursor
426 self.explorer = YX(0, 0)
433 self.do_refresh = False
436 msg = self.queue.get(block=False)
441 key = stdscr.getkey()
442 self.do_refresh = True
445 if key == 'KEY_RESIZE':
447 elif self.mode.has_input_prompt and key == 'KEY_BACKSPACE':
448 self.input_ = self.input_[:-1]
449 elif self.mode.has_input_prompt and key != '\n': # Return key
451 max_length = self.window_width * self.size.y - len(input_prompt) - 1
452 if len(self.input_) > max_length:
453 self.input_ = self.input_[:max_length]
454 elif self.mode == self.mode_login and key == '\n':
455 self.login_name = self.input_
456 self.send('LOGIN ' + quote(self.input_))
458 elif self.mode == self.mode_chat and key == '\n':
459 if self.input_[0] == ':':
460 if self.input_ in {':P', ':play'}:
461 self.switch_mode('play')
462 elif self.input_ in {':?', ':study'}:
463 self.switch_mode('study')
464 if self.input_ == ':help':
466 if self.input_ == ':reconnect':
468 elif self.input_.startswith(':nick'):
469 tokens = self.input_.split(maxsplit=1)
471 self.send('LOGIN ' + quote(tokens[1]))
473 self.log_msg('? need login name')
474 elif self.input_.startswith(':msg'):
475 tokens = self.input_.split(maxsplit=2)
477 self.send('QUERY %s %s' % (quote(tokens[1]),
480 self.log_msg('? need message target and message')
482 self.log_msg('? unknown command')
484 self.send('ALL ' + quote(self.input_))
486 elif self.mode == self.mode_annotate and key == '\n':
487 if self.input_ == '':
489 self.send('ANNOTATE %s %s' % (self.explorer, quote(self.input_)))
491 self.switch_mode('study', keep_position=True)
492 elif self.mode == self.mode_portal and key == '\n':
493 if self.input_ == '':
495 self.send('PORTAL %s %s' % (self.explorer, quote(self.input_)))
497 self.switch_mode('study', keep_position=True)
498 elif self.mode == self.mode_teleport and key == '\n':
499 if self.input_ == 'YES!':
500 self.host = self.teleport_target_host
501 self.port = self.teleport_target_port
504 self.log_msg('@ teleport aborted')
505 self.switch_mode('play')
507 elif self.mode == self.mode_study:
509 self.switch_mode('chat')
511 self.switch_mode('play')
513 self.switch_mode('annotate', keep_position=True)
515 self.switch_mode('portal', keep_position=True)
516 elif key in self.movement_keys:
517 move_explorer(self.movement_keys[key])
518 elif self.mode == self.mode_play:
520 self.switch_mode('chat')
522 self.switch_mode('study')
524 self.switch_mode('edit')
526 self.send('TASK:FLATTEN_SURROUNDINGS')
527 elif key in self.movement_keys:
528 self.send('TASK:MOVE ' + self.movement_keys[key])
529 elif self.mode == self.mode_edit:
530 self.send('TASK:WRITE ' + key)
531 self.switch_mode('play')
533 TUI('127.0.0.1', 5000)