home · contact · privacy
Fix map indentation handling bug in client cursor movement.
[plomrogue2-experiments] / new / example_client.py
1 #!/usr/bin/env python3
2 import curses
3 import socket
4 import threading
5 from plomrogue.parser import ArgError, Parser
6 from plomrogue.commands import cmd_PLAYER_ID, cmd_THING_HEALTH
7 from plomrogue.game import GameBase
8 from plomrogue.mapping import Map, MapGeometryHex, YX
9 from plomrogue.io import PlomSocket
10 from plomrogue.things import ThingBase
11 import types
12 import queue
13
14
15 class ClientMap(Map):
16
17     def y_cut(self, map_lines, center_y, view_height):
18         map_height = len(map_lines)
19         if map_height > view_height and center_y > view_height / 2:
20             if center_y > map_height - view_height / 2:
21                 map_lines[:] = map_lines[map_height - view_height:]
22             else:
23                 start = center_y - int(view_height / 2) - 1
24                 map_lines[:] = map_lines[start:start + view_height]
25
26     def x_cut(self, map_lines, center_x, view_width, map_width):
27         if map_width > view_width and center_x > view_width / 2:
28             if center_x > map_width - view_width / 2:
29                 cut_start = map_width - view_width
30                 cut_end = None
31             else:
32                 cut_start = center_x - int(view_width / 2)
33                 cut_end = cut_start + view_width
34             map_lines[:] = [line[cut_start:cut_end] for line in map_lines]
35
36     def format_to_view(self, map_cells, center, size):
37
38         def map_cells_to_lines(map_cells):
39             map_view_chars = []
40             if self.start_indented:
41                 map_view_chars += ['0']
42             x = 0
43             y = 0
44             for cell in map_cells:
45                 if type(cell) == str:
46                     map_view_chars += [cell, ' ']
47                 else:
48                     map_view_chars += [cell[0], cell[1]]
49                 x += 1
50                 if x == self.size.x:
51                     map_view_chars += ['\n']
52                     x = 0
53                     y += 1
54                     if y % 2 == int(not self.start_indented):
55                         map_view_chars += ['0']
56             if y % 2 == int(not self.start_indented):
57                 map_view_chars = map_view_chars[:-1]
58             map_view_chars = map_view_chars[:-1]
59             return ''.join(map_view_chars).split('\n')
60
61         map_lines = map_cells_to_lines(map_cells)
62         self.y_cut(map_lines, center[1].y, size.y)
63         map_width = self.size.x * 2 + 1
64         self.x_cut(map_lines, center[1].x * 2, size.x, map_width)
65         return map_lines
66
67
68 def cmd_LAST_PLAYER_TASK_RESULT(game, msg):
69     if msg != "success":
70         game.log(msg)
71 cmd_LAST_PLAYER_TASK_RESULT.argtypes = 'string'
72
73
74 def cmd_TURN_FINISHED(game, n):
75     """Do nothing. (This may be extended later.)"""
76     pass
77 cmd_TURN_FINISHED.argtypes = 'int:nonneg'
78
79
80 def cmd_TURN(game, n):
81     """Set game.turn to n, empty game.things."""
82     game.turn = n
83     game.things = []
84     game.pickable_items[:] = []
85 cmd_TURN.argtypes = 'int:nonneg'
86
87
88 def cmd_VISIBLE_MAP(game, size, indent_first_line):
89     game.new_map(size, indent_first_line)
90 cmd_VISIBLE_MAP.argtypes = 'yx_tuple:pos bool'
91
92
93 def cmd_VISIBLE_MAP_LINE(game, y, terrain_line):
94     game.map_.set_line(y, terrain_line)
95 cmd_VISIBLE_MAP_LINE.argtypes = 'int:nonneg string'
96
97
98 def cmd_GAME_STATE_COMPLETE(game):
99     game.tui.to_update['turn'] = True
100     game.tui.to_update['map'] = True
101     game.tui.to_update['inventory'] = True
102
103
104 def cmd_THING_TYPE(game, i, type_):
105     t = game.get_thing(i)
106     t.type_ = type_
107 cmd_THING_TYPE.argtypes = 'int:nonneg string'
108
109
110 def cmd_THING_POS(game, i, yx):
111     t = game.get_thing(i)
112     t.position = YX(0,0), yx
113 cmd_THING_POS.argtypes = 'int:nonneg yx_tuple:nonneg'
114
115
116 def cmd_PLAYER_INVENTORY(game, ids):
117     game.player_inventory[:] = ids  # TODO: test whether valid IDs
118     game.tui.to_update['inventory'] = True
119 cmd_PLAYER_INVENTORY.argtypes = 'seq:int:nonneg'
120
121
122 def cmd_PICKABLE_ITEMS(game, ids):
123     game.pickable_items[:] = ids
124     game.tui.to_update['pickable_items'] = True
125 cmd_PICKABLE_ITEMS.argtypes = 'seq:int:nonneg'
126
127
128 class Game(GameBase):
129
130     def __init__(self, *args, **kwargs):
131         super().__init__(*args, **kwargs)
132         self.map_ = ClientMap()  # we need an empty default map cause we draw
133         self.offset = YX(0,0)    # the map widget even before we get a real one
134         self.player_inventory = []
135         self.player_id = 0
136         self.pickable_items = []
137         self.parser = Parser(self)
138         self.map_geometry = MapGeometryHex()
139         self.thing_type = ThingBase
140         self.commands = {'LAST_PLAYER_TASK_RESULT': cmd_LAST_PLAYER_TASK_RESULT,
141                          'TURN_FINISHED': cmd_TURN_FINISHED,
142                          'TURN': cmd_TURN,
143                          'VISIBLE_MAP_LINE': cmd_VISIBLE_MAP_LINE,
144                          'PLAYER_ID': cmd_PLAYER_ID,
145                          'PLAYER_INVENTORY': cmd_PLAYER_INVENTORY,
146                          'GAME_STATE_COMPLETE': cmd_GAME_STATE_COMPLETE,
147                          'VISIBLE_MAP': cmd_VISIBLE_MAP,
148                          'PICKABLE_ITEMS': cmd_PICKABLE_ITEMS,
149                          'THING_TYPE': cmd_THING_TYPE,
150                          'THING_HEALTH': cmd_THING_HEALTH,
151                          'THING_POS': cmd_THING_POS}
152         self.log_text = ''
153         self.do_quit = False
154         self.tui = None
155
156     def new_map(self, size, indent_first_line):
157         self.map_ = ClientMap(size, start_indented=indent_first_line)
158
159     @property
160     def player(self):
161         return self.get_thing(self.player_id)
162
163     def get_command(self, command_name):
164         from functools import partial
165         if command_name in self.commands:
166             f = partial(self.commands[command_name], self)
167             if hasattr(self.commands[command_name], 'argtypes'):
168                 f.argtypes = self.commands[command_name].argtypes
169             return f
170         return None
171
172     def get_string_options(self, string_option_type):
173         return None
174
175     def handle_input(self, msg):
176         self.log(msg)
177         if msg == 'BYE':
178             self.do_quit = True
179             return
180         try:
181             command, args = self.parser.parse(msg)
182             if command is None:
183                 self.log('UNHANDLED INPUT: ' + msg)
184             else:
185                 command(*args)
186         except ArgError as e:
187             self.log('ARGUMENT ERROR: ' + msg + '\n' + str(e))
188
189     def log(self, msg):
190         """Prefix msg plus newline to self.log_text."""
191         self.log_text = msg + '\n' + self.log_text
192         self.tui.to_update['log'] = True
193
194     def symbol_for_type(self, type_):
195         symbol = '?'
196         if type_ == 'human':
197             symbol = '@'
198         elif type_ == 'monster':
199             symbol = 'm'
200         elif type_ == 'food':
201             symbol = 'f'
202         return symbol
203
204
205 ASCII_printable = ' !"#$%&\'\(\)*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWX'\
206                   'YZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~'
207
208
209 def recv_loop(plom_socket, game, q):
210     for msg in plom_socket.recv():
211         q.put(msg)
212
213
214 class Widget:
215
216     def __init__(self, tui, start, size, check_updates=[], visible=True):
217         self.check_updates = check_updates
218         self.tui = tui
219         self.start = start
220         self.win = curses.newwin(1, 1, self.start.y, self.start.x)
221         self.size_def = size  # store for re-calling .size on SIGWINCH
222         self.size = size
223         self.do_update = True
224         self.visible = visible
225         self.children = []
226
227     @property
228     def size(self):
229         return YX(*self.win.getmaxyx())
230
231     @size.setter
232     def size(self, size):
233         """Set window size. Size be y,x tuple. If y or x None, use legal max."""
234         n_lines, n_cols = size
235         getmaxyx = YX(*self.tui.stdscr.getmaxyx())
236         if n_lines is None:
237             n_lines = getmaxyx.y - self.start.y
238         if n_cols is None:
239             n_cols = getmaxyx.x - self.start.x
240         self.win.resize(n_lines, n_cols)
241
242     def __len__(self):
243         getmaxyx = YX(*self.win.getmaxyx())
244         return getmaxyx.y * getmaxyx.x
245
246     def safe_write(self, foo):
247
248         def to_chars_with_attrs(part):
249             attr = curses.A_NORMAL
250             part_string = part
251             if not type(part) == str:
252                 part_string = part[0]
253                 attr = part[1]
254             return [(char, attr) for char in part_string]
255
256         chars_with_attrs = []
257         if type(foo) == str or (len(foo) == 2 and type(foo[1]) == int):
258             chars_with_attrs += to_chars_with_attrs(foo)
259         else:
260             for part in foo:
261                 chars_with_attrs += to_chars_with_attrs(part)
262         self.win.move(0, 0)
263         if len(chars_with_attrs) < len(self):
264             for char_with_attr in chars_with_attrs:
265                 self.win.addstr(char_with_attr[0], char_with_attr[1])
266         else:  # workaround to <https://stackoverflow.com/q/7063128>
267             cut = chars_with_attrs[:len(self) - 1]
268             last_char_with_attr = chars_with_attrs[len(self) - 1]
269             self.win.addstr(self.size.y - 1, self.size.x - 2,
270                             last_char_with_attr[0], last_char_with_attr[1])
271             self.win.insstr(self.size.y - 1, self.size.x - 2, ' ')
272             self.win.move(0, 0)
273             for char_with_attr in cut:
274                 self.win.addstr(char_with_attr[0], char_with_attr[1])
275
276     def ensure_freshness(self, do_refresh=False):
277         did_refresh = False
278         if self.visible:
279             if not do_refresh:
280                 for key in self.check_updates:
281                     if key in self.tui.to_update and self.tui.to_update[key]:
282                         do_refresh = True
283                         break
284             if do_refresh:
285                 self.win.erase()
286                 self.draw()
287                 self.win.refresh()
288                 did_refresh = True
289             for child in self.children:
290                 did_refresh = child.ensure_freshness(do_refresh) | did_refresh
291         return did_refresh
292
293
294 class EditWidget(Widget):
295
296     def draw(self):
297         self.safe_write((''.join(self.tui.to_send), curses.color_pair(1)))
298
299
300 class TextLinesWidget(Widget):
301
302     def draw(self):
303         lines = self.get_text_lines()
304         line_width = self.size.x
305         to_join = []
306         for line in lines:
307             to_pad = line_width - (len(line) % line_width)
308             if to_pad == line_width:
309                 to_pad = 0
310             to_join += [line + ' '*to_pad]
311         self.safe_write((''.join(to_join), curses.color_pair(3)))
312
313
314 class LogWidget(TextLinesWidget):
315
316     def get_text_lines(self):
317         return self.tui.game.log_text.split('\n')
318
319
320 class DescriptorWidget(TextLinesWidget):
321
322     def get_text_lines(self):
323         lines = []
324         pos_i = self.tui.game.map_.\
325                 get_position_index(self.tui.examiner_position[1])
326         terrain = self.tui.game.map_.terrain[pos_i]
327         lines = [terrain]
328         for t in self.tui.game.things_at_pos(self.tui.examiner_position):
329             lines += [t.type_]
330         return lines
331
332
333 class PopUpWidget(Widget):
334
335     def draw(self):
336         self.safe_write(self.tui.popup_text)
337
338     def reconfigure(self):
339         size = (1, len(self.tui.popup_text))
340         self.size = size
341         self.size_def = size
342         getmaxyx = YX(*self.tui.stdscr.getmaxyx())
343         offset_y = int(getmaxyx.y / 2 - size.y / 2)
344         offset_x = int(getmaxyx.x / 2 - size.x / 2)
345         self.start = YX(offset_y, offset_x)
346         self.win.mvwin(self.start.y, self.start.x)
347
348
349 class ItemsSelectorWidget(Widget):
350
351     def __init__(self, headline, selection, *args, **kwargs):
352         super().__init__(*args, **kwargs)
353         self.headline = headline
354         self.selection = selection
355
356     def ensure_freshness(self, *args, **kwargs):
357         # We only update pointer on non-empty selection so that the zero-ing
358         # of the selection at TURN_FINISHED etc. before pulling in a new
359         # state does not destroy any memory of previous item pointer positions.
360         if len(self.selection) > 0 and\
361            len(self.selection) < self.tui.item_pointer + 1 and\
362            self.tui.item_pointer > 0:
363             self.tui.item_pointer = max(0, len(self.selection) - 1)
364             self.tui.to_update[self.check_updates[0]] = True
365         super().ensure_freshness(*args, **kwargs)
366
367     def draw(self):
368         lines = [self.headline]
369         counter = 0
370         for id_ in self.selection:
371             pointer = '*' if counter == self.tui.item_pointer else ' '
372             t = self.tui.game.get_thing(id_)
373             lines += ['%s %s' % (pointer, t.type_)]
374             counter += 1
375         line_width = self.size.x
376         to_join = []
377         for line in lines:
378             to_pad = line_width - (len(line) % line_width)
379             if to_pad == line_width:
380                 to_pad = 0
381             to_join += [line + ' '*to_pad]
382         self.safe_write((''.join(to_join), curses.color_pair(3)))
383
384
385 class MapWidget(Widget):
386
387     def draw(self):
388
389         def annotated_terrain():
390             terrain_as_list = list(self.tui.game.map_.terrain[:])
391             for t in self.tui.game.things:
392                 if t.id_ in self.tui.game.player_inventory:
393                     continue
394                 pos_i = self.tui.game.map_.get_position_index(t.position[1])
395                 symbol = self.tui.game.symbol_for_type(t.type_)
396                 if terrain_as_list[pos_i][0] in {'f', '@', 'm'}:
397                     old_symbol = terrain_as_list[pos_i][0]
398                     if old_symbol in {'@', 'm'}:
399                         symbol = old_symbol
400                     terrain_as_list[pos_i] = (symbol, '+')
401                 else:
402                     terrain_as_list[pos_i] = symbol
403             if self.tui.examiner_mode:
404                 pos_i = self.tui.game.map_.\
405                         get_position_index(self.tui.examiner_position[1])
406                 terrain_as_list[pos_i] = (terrain_as_list[pos_i][0], '?')
407             return terrain_as_list
408
409         def pad_or_cut_x(lines):
410             line_width = self.size.x
411             for y in range(len(lines)):
412                 line = lines[y]
413                 if line_width > len(line):
414                     to_pad = line_width - (len(line) % line_width)
415                     lines[y] = line + '0' * to_pad
416                 else:
417                     lines[y] = line[:line_width]
418
419         def pad_y(lines):
420             if len(lines) < self.size.y:
421                 to_pad = self.size.y - len(lines)
422                 lines += to_pad * ['0' * self.size.x]
423
424         def lines_to_colored_chars(lines):
425             chars_with_attrs = []
426             for c in ''.join(lines):
427                 if c in {'@', 'm'}:
428                     chars_with_attrs += [(c, curses.color_pair(1))]
429                 elif c == 'f':
430                     chars_with_attrs += [(c, curses.color_pair(4))]
431                 elif c == '.':
432                     chars_with_attrs += [(c, curses.color_pair(2))]
433                 elif c in {'x', 'X', '#'}:
434                     chars_with_attrs += [(c, curses.color_pair(3))]
435                 elif c == '?':
436                     chars_with_attrs += [(c, curses.color_pair(5))]
437                 else:
438                     chars_with_attrs += [c]
439             return chars_with_attrs
440
441         if self.tui.game.map_.terrain == '':
442             lines = []
443             pad_y(lines)
444             self.safe_write(''.join(lines))
445             return
446
447         annotated_terrain = annotated_terrain()
448         center = self.tui.game.player.position
449         if self.tui.examiner_mode:
450             center = self.tui.examiner_position
451         lines = self.tui.game.map_.\
452                 format_to_view(annotated_terrain, center, self.size)
453         pad_or_cut_x(lines)
454         pad_y(lines)
455         self.safe_write(lines_to_colored_chars(lines))
456
457
458 class TurnWidget(Widget):
459
460     def draw(self):
461         self.safe_write((str(self.tui.game.turn), curses.color_pair(2)))
462
463
464 class HealthWidget(Widget):
465
466     def draw(self):
467         if hasattr(self.tui.game.player, 'health'):
468             self.safe_write((str(self.tui.game.player.health),
469                              curses.color_pair(2)))
470
471
472 class TextLineWidget(Widget):
473
474     def __init__(self, text_line, *args, **kwargs):
475         self.text_line = text_line
476         super().__init__(*args, **kwargs)
477
478     def draw(self):
479         self.safe_write(self.text_line)
480
481
482 class TUI:
483
484     def __init__(self, plom_socket, game, q):
485         self.socket = plom_socket
486         self.game = game
487         self.game.tui = self
488         self.queue = q
489         self.parser = Parser(self.game)
490         self.to_update = {}
491         self.item_pointer = 0
492         self.examiner_position = (YX(0,0), YX(0, 0))
493         self.examiner_mode = False
494         self.popup_text = 'Hi bob'
495         self.to_send = []
496         self.draw_popup_if_visible = True
497         curses.wrapper(self.loop)
498
499     def loop(self, stdscr):
500
501         def setup_screen(stdscr):
502             self.stdscr = stdscr
503             self.stdscr.refresh()  # will be called by getkey else, clearing screen
504             self.stdscr.timeout(10)
505
506         def switch_widgets(widget_1, widget_2):
507             widget_1.visible = False
508             widget_2.visible = True
509             trigger = widget_2.check_updates[0]
510             self.to_update[trigger] = True
511
512         def selectables_menu(key, widget, selectables, f):
513             if key == 'c':
514                 switch_widgets(widget, map_widget)
515             elif key == 'j':
516                 self.item_pointer += 1
517             elif key == 'k' and self.item_pointer > 0:
518                 self.item_pointer -= 1
519             elif not f(key, selectables):
520                 return
521             trigger = widget.check_updates[0]
522             self.to_update[trigger] = True
523
524         def pickup_menu(key):
525
526             def f(key, selectables):
527                 if key == 'p' and len(selectables) > 0:
528                     id_ = selectables[self.item_pointer]
529                     self.socket.send('TASK:PICKUP %s' % id_)
530                     self.socket.send('GET_PICKABLE_ITEMS')
531                 else:
532                     return False
533                 return True
534
535             selectables_menu(key, pickable_items_widget,
536                              self.game.pickable_items, f)
537
538         def inventory_menu(key):
539
540             def f(key, selectables):
541                 if key == 'd' and len(selectables) > 0:
542                     id_ = selectables[self.item_pointer]
543                     self.socket.send('TASK:DROP %s' % id_)
544                 elif key == 'e' and len(selectables) > 0:
545                     id_ = selectables[self.item_pointer]
546                     self.socket.send('TASK:EAT %s' % id_)
547                 else:
548                     return False
549                 return True
550
551             selectables_menu(key, inventory_widget,
552                              self.game.player_inventory, f)
553
554         def move_examiner(direction):
555             start_pos = self.examiner_position
556             new_examine_pos = self.game.map_geometry.move(start_pos, direction,
557                                                           self.game.map_.size,
558                                                           self.game.map_.start_indented)
559             if new_examine_pos[0] == (0,0):
560                 self.examiner_position = new_examine_pos
561             self.to_update['map'] = True
562
563         def switch_to_pick_or_drop(target_widget):
564             self.item_pointer = 0
565             switch_widgets(map_widget, target_widget)
566             if self.examiner_mode:
567                 self.examiner_mode = False
568                 switch_widgets(descriptor_widget, log_widget)
569
570         def toggle_examiner_mode():
571             if self.examiner_mode:
572                 self.examiner_mode = False
573                 switch_widgets(descriptor_widget, log_widget)
574             else:
575                 self.examiner_mode = True
576                 self.examiner_position = self.game.player.position
577                 switch_widgets(log_widget, descriptor_widget)
578             self.to_update['map'] = True
579
580         def toggle_popup():
581             if popup_widget.visible:
582                 popup_widget.visible = False
583                 for w in top_widgets:
584                     w.ensure_freshness(True)
585             else:
586                 self.to_update['popup'] = True
587                 popup_widget.visible = True
588                 popup_widget.reconfigure()
589                 self.draw_popup_if_visible = True
590
591         def try_write_keys():
592             if len(key) == 1 and key in ASCII_printable and \
593                     len(self.to_send) < len(edit_line_widget):
594                 self.to_send += [key]
595                 self.to_update['edit'] = True
596             elif key == 'KEY_BACKSPACE':
597                 self.to_send[:] = self.to_send[:-1]
598                 self.to_update['edit'] = True
599             elif key == '\n':  # Return key
600                 self.socket.send(''.join(self.to_send))
601                 self.to_send[:] = []
602                 self.to_update['edit'] = True
603
604         def try_examiner_keys():
605             if key == 'w':
606                 move_examiner('UPLEFT')
607             elif key == 'e':
608                 move_examiner('UPRIGHT')
609             elif key == 's':
610                 move_examiner('LEFT')
611             elif key == 'd':
612                 move_examiner('RIGHT')
613             elif key == 'x':
614                 move_examiner('DOWNLEFT')
615             elif key == 'c':
616                 move_examiner('DOWNRIGHT')
617
618         def try_player_move_keys():
619             if key == 'w':
620                 self.socket.send('TASK:MOVE UPLEFT')
621             elif key == 'e':
622                 self.socket.send('TASK:MOVE UPRIGHT')
623             elif key == 's':
624                 self.socket.send('TASK:MOVE LEFT')
625             elif key == 'd':
626                 self.socket.send('TASK:MOVE RIGHT')
627             elif key == 'x':
628                 self.socket.send('TASK:MOVE DOWNLEFT')
629             elif key == 'c':
630                 self.socket.send('TASK:MOVE DOWNRIGHT')
631
632         def init_colors():
633             curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_RED)
634             curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_GREEN)
635             curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLUE)
636             curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_YELLOW)
637             curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_WHITE)
638
639         # Basic curses initialization work.
640         setup_screen(stdscr)
641         curses.curs_set(False)  # hide cursor
642         init_colors()
643
644         # With screen initialized, set up widgets with their curses windows.
645         edit_widget = TextLineWidget('SEND:', self, YX(0, 0), YX(1, 20))
646         edit_line_widget = EditWidget(self, YX(0, 6), YX(1, 14), ['edit'])
647         edit_widget.children += [edit_line_widget]
648         turn_widget = TextLineWidget('TURN:', self, YX(2, 0), YX(1, 20))
649         turn_widget.children += [TurnWidget(self, YX(2, 6), YX(1, 14), ['turn'])]
650         health_widget = TextLineWidget('HEALTH:', self, YX(3, 0), YX(1, 20))
651         health_widget.children += [HealthWidget(self, YX(3, 8), YX(1, 12), ['turn'])]
652         log_widget = LogWidget(self, YX(5, 0), YX(None, 20), ['log'])
653         descriptor_widget = DescriptorWidget(self, YX(5, 0), YX(None, 20),
654                                              ['map'], False)
655         map_widget = MapWidget(self, YX(0, 21), YX(None, None), ['map'])
656         inventory_widget = ItemsSelectorWidget('INVENTORY:',
657                                                self.game.player_inventory,
658                                                self, YX(0, 21), YX(None, None),
659                                                ['inventory'], False)
660         pickable_items_widget = ItemsSelectorWidget('PICKABLE:',
661                                                     self.game.pickable_items,
662                                                     self, YX(0, 21),
663                                                     YX(None, None),
664                                                     ['pickable_items'],
665                                                     False)
666         top_widgets = [edit_widget, turn_widget, health_widget, log_widget,
667                        descriptor_widget, map_widget, inventory_widget,
668                        pickable_items_widget]
669         popup_widget = PopUpWidget(self, YX(0, 0), YX(1, 1), visible=False)
670
671         # Ensure initial window state before loop starts.
672         for w in top_widgets:
673             w.ensure_freshness(True)
674         self.socket.send('GET_GAMESTATE')
675         write_mode = False
676         while True:
677
678             # Draw screen.
679             for w in top_widgets:
680                 if w.ensure_freshness():
681                     self.draw_popup_if_visible = True
682             if popup_widget.visible and self.draw_popup_if_visible:
683                 popup_widget.ensure_freshness(True)
684                 self.draw_popup_if_visible = False
685             for k in self.to_update.keys():
686                 self.to_update[k] = False
687
688             # Handle input from server.
689             while True:
690                 try:
691                     command = self.queue.get(block=False)
692                 except queue.Empty:
693                     break
694                 self.game.handle_input(command)
695
696             # Handle keys (and resize event read as key).
697             try:
698                 key = self.stdscr.getkey()
699                 if key == 'KEY_RESIZE':
700                     curses.endwin()
701                     setup_screen(curses.initscr())
702                     for w in top_widgets:
703                         w.size = w.size_def
704                         w.ensure_freshness(True)
705                 elif key == '\t':  # Tabulator key.
706                     write_mode = False if write_mode else True
707                 elif write_mode:
708                     try_write_keys()
709                 elif key == 't':
710                     toggle_popup()
711                 elif map_widget.visible:
712                     if key == '?':
713                         toggle_examiner_mode()
714                     elif key == 'p':
715                         self.socket.send('GET_PICKABLE_ITEMS')
716                         switch_to_pick_or_drop(pickable_items_widget)
717                     elif key == 'i':
718                         switch_to_pick_or_drop(inventory_widget)
719                     elif self.examiner_mode:
720                         try_examiner_keys()
721                     else:
722                         try_player_move_keys()
723                 elif pickable_items_widget.visible:
724                     pickup_menu(key)
725                 elif inventory_widget.visible:
726                     inventory_menu(key)
727             except curses.error:
728                 pass
729
730             # Quit when server recommends it.
731             if self.game.do_quit:
732                 break
733
734
735 s = socket.create_connection(('127.0.0.1', 5000))
736 plom_socket = PlomSocket(s)
737 game = Game()
738 q = queue.Queue()
739 t = threading.Thread(target=recv_loop, args=(plom_socket, game, q))
740 t.start()
741 TUI(plom_socket, game, q)