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