home · contact · privacy
Server: Correct initial log message.
[plomrogue] / client_prototype.py
1 import curses
2 import math
3 import os
4 import signal
5 import time
6
7
8 def set_window_geometries():
9
10     def set_window_size():
11         win["size"], win["start"] = [0, 0], [0, 0]
12         win["size"][0] = win["config"][0]
13         if (win["config"][0] == 0):
14             win["size"][0] = screen_size[0] - sep_size
15         elif (win["config"][0] < 0):
16             win["size"][0] = screen_size[0] + win["config"][0] - sep_size
17         win["size"][1] = win["config"][1]
18         if (win["config"][1] == 0):
19             win["size"][1] = screen_size[1]
20         elif (win["config"][1] < 0):
21             win["size"][1] = screen_size[1] + win["config"][1]
22
23     def place_window():
24         win_i = windows.index(win)
25
26         # If win is first window, it goes into the top left corner.
27         win["start"][0] = 0 + sep_size
28         win["start"][1] = 0
29         if (win_i > 0):
30
31             # If not, get win's closest predecessor starting a new stack on the
32             # screen top,fit win's top left to that win_top's top right corner.
33             win_top = None
34             for i in range(win_i - 1, -1, -1):
35                 win_top = windows[i]
36                 if (win_top["start"][0] == 0 + sep_size):
37                     break
38             win["start"][1] = win_top["start"][1] + win_top["size"][1] \
39                 + sep_size
40
41             # If enough space is found below win's predecessor, fit win's top
42             # left corner to that predecessor's bottom left corner.
43             win_prev = windows[win_i - 1]
44             next_free_y = win_prev["start"][0] + win_prev["size"][0] + sep_size
45             if (win["size"][1] <= win_prev["size"][1] and
46                     win["size"][0] <= screen_size[0] - next_free_y):
47                 win["start"][1] = win_prev["start"][1]
48                 win["start"][0] = next_free_y
49
50             # If that fails, try to fit win's top left corner to the top right
51             # corner of its closest predecessor win_test 1) below win_top (see
52             # above) 2) and with enough space open to its right between its
53             # right edge and the lower edge of a win_high located directly
54             # above win_test to fit win there (without growing further to the
55             # right than win_high does or surpassing the screen's lower edge).
56             else:
57                 win_test = win_prev
58                 win_high = None
59                 while (win_test != win_top):
60                     for i in range(win_i - 2, -1, -1):
61                         win_high = windows[i]
62                         if win_test["start"][0] > win_high["start"][0]:
63                             break
64                     next_free_y = win_high["start"][0] + win_high["size"][0] \
65                         + sep_size
66                     first_free_x = win_test["start"][1] + win_test["size"][1] \
67                         + sep_size
68                     last_free_x = win_high["start"][1] + win_high["size"][1]
69                     if (win["size"][0] <= screen_size[0] - next_free_y and
70                             win["size"][1] <= last_free_x - first_free_x):
71                         win["start"][1] = first_free_x
72                         win["start"][0] = next_free_y
73                         break
74                     win_test = win_high
75
76     global screen_size, stdscr
77     curses.endwin()
78     stdscr = curses.initscr()
79     screen_size = stdscr.getmaxyx()
80     for win in windows:
81         set_window_size()
82         place_window()
83     cursed_main.redraw = True
84
85
86 def draw_screen():
87
88     def healthy_addch(y, x, char, attr=0):
89         """Workaround for <http://stackoverflow.com/questions/7063128/>."""
90         if y == screen_size[0] - 1 and x == screen_size[1] - 1:
91             char_before = stdscr.inch(y, x - 1)
92             stdscr.addch(y, x - 1, char, attr)
93             stdscr.insstr(y, x - 1, " ")
94             stdscr.addch(y, x - 1, char_before)
95         else:
96             stdscr.addch(y, x, char, attr)
97
98     def draw_window_border_lines():
99         for win in windows:
100             for k in range(2):
101                 j = win["start"][int(k == 0)] - sep_size
102                 if (j >= 0 and j < screen_size[int(k == 0)]):
103                     start = win["start"][k]
104                     end = win["start"][k] + win["size"][k]
105                     end = end if end < screen_size[k] else screen_size[k]
106                     if k:
107                         [healthy_addch(j, i, '-') for i in range(start, end)]
108                     else:
109                         [healthy_addch(i, j, '|') for i in range(start, end)]
110
111     def draw_window_border_corners():
112         for win in windows:
113             up = win["start"][0] - sep_size
114             down = win["start"][0] + win["size"][0]
115             left = win["start"][1] - sep_size
116             right = win["start"][1] + win["size"][1]
117             if (up >= 0 and up < screen_size[0]):
118                 if (left >= 0 and left < screen_size[1]):
119                     healthy_addch(up, left, '+')
120                 if (right >= 0 and right < screen_size[1]):
121                     healthy_addch(up, right, '+')
122             if (down >= 0 and down < screen_size[0]):
123                 if (left >= 0 and left < screen_size[1]):
124                     healthy_addch(down, left, '+')
125                 if (right >= 0 and right < screen_size[1]):
126                     healthy_addch(down, right, '+')
127
128     def draw_window_titles():
129         for win in windows:
130             title = " " + win["title"] + " "
131             if len(title) <= win["size"][1]:
132                 y = win["start"][0] - 1
133                 start_x = win["start"][1] + int((win["size"][1] \
134                     - len(title))/2)
135                 for x in range(len(title)):
136                     healthy_addch(y, start_x + x, title[x])
137
138     def draw_window_contents():
139         def draw_winmap():
140             """Draw winmap in area delimited by offset, winmap_size.
141
142             The individuall cell of a winmap is interpreted as either a single
143             character element, or as a tuple of character and attribute,
144             depending on the size len(cell) spits out.
145             """
146             stop = [0, 0]
147             for i in range(2):
148                 stop[i] = win["size"][i] + offset[i]
149                 if stop[i] >= winmap_size[i]:
150                     stop[i] = winmap_size[i]
151             for y in range(offset[0], stop[0]):
152                 for x in range(offset[1], stop[1]):
153                     cell = winmap[y * winmap_size[1] + x]
154                     attr = 0
155                     if len(cell) > 1:
156                         attr = cell[1]
157                         cell = cell[0]
158                     y_in_screen = win["start"][0] + (y - offset[0])
159                     x_in_screen = win["start"][1] + (x - offset[1])
160                     if (y_in_screen < screen_size[0]
161                             and x_in_screen < screen_size[1]):
162                         healthy_addch(y_in_screen, x_in_screen, cell, attr)
163         def draw_scroll_hints():
164             def draw_scroll_string(n_lines_outside):
165                 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
166                 if len(hint) <= win["size"][ni]:
167                     non_hint_space = win["size"][ni] - len(hint)
168                     hint_offset = int(non_hint_space / 2)
169                     for j in range(win["size"][ni] - non_hint_space):
170                         pos_2 = win["start"][ni] + hint_offset + j
171                         x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
172                         healthy_addch(y, x, hint[j], curses.A_REVERSE)
173             def draw_scroll_arrows(ar1, ar2):
174                 for j in range(win["size"][ni]):
175                     pos_2 = win["start"][ni] + j
176                     x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
177                     healthy_addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
178             for i in range(2):
179                 ni = int(i == 0)
180                 unit = 'rows' if ni else 'columns'
181                 if (offset[i] > 0):
182                     pos_1 = win["start"][i]
183                     draw_scroll_arrows('^', '<')
184                     draw_scroll_string(offset[i])
185                 if (winmap_size[i] > offset[i] + win["size"][i]):
186                     pos_1 = win["start"][i] + win["size"][i] - 1
187                     draw_scroll_arrows('v', '>')
188                     draw_scroll_string(winmap_size[i] - offset[i]
189                         - win["size"][i])
190         for win in windows:
191             offset, winmap_size, winmap = win["func"]()
192             draw_winmap()
193             draw_scroll_hints()
194
195     stdscr.erase()
196     draw_window_border_lines()
197     draw_window_border_corners()
198     draw_window_titles()
199     draw_window_contents()
200     stdscr.refresh()
201
202
203 def read_worldstate():
204     if not os.access(io["path_worldstate"], os.F_OK):
205         msg = "No world state file found at " + io["path_worldstate"] + "."
206         raise SystemExit(msg)
207     read_anew = False
208     worldstate_file = open(io["path_worldstate"], "r")
209     turn_string = worldstate_file.readline()
210     if int(turn_string) != world_data["turn"]:
211         read_anew = True
212     if not read_anew: # In rare cases, world may change, but not turn number.
213         mtime = os.stat(io["path_worldstate"])
214         if mtime != read_worldstate.last_checked_mtime:
215             read_worldstate.last_checked_mtime = mtime
216             read_anew = True
217     if read_anew:
218         cursed_main.redraw = True
219         world_data["turn"] = int(turn_string)
220         world_data["lifepoints"] = int(worldstate_file.readline())
221         world_data["satiation"] = int(worldstate_file.readline())
222         world_data["inventory"] = []
223         while True:
224             line = worldstate_file.readline().replace("\n", "")
225             if line == '%':
226                 break
227             world_data["inventory"] += [line]
228         world_data["avatar_position"][0] = int(worldstate_file.readline())
229         world_data["avatar_position"][1] = int(worldstate_file.readline())
230         if not world_data["look_mode"]:
231             world_data["map_center"][0] = world_data["avatar_position"][0]
232             world_data["map_center"][1] = world_data["avatar_position"][1]
233         world_data["map_size"] = int(worldstate_file.readline())
234         world_data["fov_map"] = ""
235         for i in range(world_data["map_size"]):
236             line = worldstate_file.readline().replace("\n", "")
237             world_data["fov_map"] += line
238         world_data["mem_map"] = ""
239         for i in range(world_data["map_size"]):
240             line = worldstate_file.readline().replace("\n", "")
241             world_data["mem_map"] += line
242     worldstate_file.close()
243 read_worldstate.last_checked_mtime = -1
244
245
246 def read_message_queue():
247     while (len(message_queue["messages"]) > 1
248         or (len(message_queue["messages"]) == 1
249             and not message_queue["open_end"])):
250         message = message_queue["messages"].pop(0)
251         if message == "THINGS_HERE START":
252             read_message_queue.parse_thingshere = True
253             world_data["look"] = []
254         elif message == "THINGS_HERE END":
255             read_message_queue.parse_thingshere = False
256             if world_data["look"] == []:
257                 world_data["look"] = ["(none known)"]
258             cursed_main.redraw = True
259         elif read_message_queue.parse_thingshere:
260             world_data["look"] += [message]
261         elif message[0:4] == "LOG ":
262             world_data["log"] += [message[4:]]
263             cursed_main.redraw = True
264         elif message == "WORLD_UPDATED":
265             query_mapcell()
266 read_message_queue.parse_thingshere = False
267
268
269 def query_mapcell():
270    command_sender("THINGS_HERE " + str(world_data["map_center"][0]) + " "
271         + str(world_data["map_center"][1]))()
272    world_data["look"] = ["(polling)"]
273
274
275 def cursed_main(stdscr):
276
277     def ping_test():
278         half_wait_time = 5
279         if len(new_data_from_server) > 0:
280             ping_test.sent = False
281         elif ping_test.wait_start + half_wait_time < time.time():
282             if not ping_test.sent:
283                 io["file_out"].write("PING\n")
284                 io["file_out"].flush()
285                 ping_test.sent = True
286                 ping_test.wait_start = time.time()
287             elif ping_test.sent:
288                 raise SystemExit("Server not answering anymore.")
289     ping_test.wait_start = 0
290
291     def read_into_message_queue():
292         if new_data_from_server == "":
293             return
294         new_open_end = False
295         if new_data_from_server[-1] is not "\n":
296             new_open_end = True
297         new_messages = new_data_from_server.splitlines()
298         if message_queue["open_end"]:
299             message_queue["messages"][-1] += new_messages[0]
300             del new_messages[0]
301         message_queue["messages"] += new_messages
302         if new_open_end:
303             message_queue["open_end"] = True
304
305     curses.noecho()
306     curses.curs_set(False)
307     signal.signal(signal.SIGWINCH,
308         lambda ignore_1, ignore_2: set_window_geometries())
309     set_window_geometries()
310     delay = 1
311     while True:
312         stdscr.timeout(int(delay))
313         delay = delay * 1.1 if delay < 1000 else delay
314         if cursed_main.redraw:
315             delay = 1
316             draw_screen()
317             cursed_main.redraw = False
318         char = stdscr.getch()
319         if char >= 0:
320             char = chr(char)
321             if char in commands:
322                 if len(commands[char]) == 1 or not world_data["look_mode"]:
323                     commands[char][0]()
324                     cursed_main.redraw = True
325                 else:
326                     commands[char][1]()
327                     cursed_main.redraw = True
328         new_data_from_server = io["file_in"].read()
329         ping_test()
330         read_into_message_queue()
331         read_worldstate()
332         read_message_queue()
333
334
335 def win_map():
336     win_size = next(win["size"] for win in windows if win["func"] == win_map)
337     offset = [0, 0]
338     for i in range(2):
339         if world_data["map_center"][i] * (i + 1) > win_size[i] / 2:
340             if world_data["map_center"][i] * (i + 1) \
341                 < world_data["map_size"] * (i + 1) - win_size[i] / 2:
342                 offset[i] = world_data["map_center"][i] * (i + 1) \
343                     - int(win_size[i] / 2)
344                 if i == 1:
345                     offset[1] = offset[1] + world_data["map_center"][0] % 2
346             else:
347                 offset[i] = world_data["map_size"] * (i + 1) - win_size[i] + i
348     winmap_size = [world_data["map_size"], world_data["map_size"] * 2 + 1]
349     winmap = []
350     curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
351     curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
352     for y in range(world_data["map_size"]):
353         for x in range(world_data["map_size"]):
354             char = world_data["fov_map"][y * world_data["map_size"] + x]
355             if world_data["look_mode"] and y == world_data["map_center"][0] \
356                     and x == world_data["map_center"][1]:
357                 if char == " ":
358                     char = \
359                         world_data["mem_map"][y * world_data["map_size"] + x]
360                 winmap += [(char, curses.A_REVERSE), (" ", curses.A_REVERSE)]
361                 continue
362             if char == " ":
363                 char = world_data["mem_map"][y * world_data["map_size"] + x]
364                 attribute = curses.color_pair(1) if char == " " \
365                     else curses.color_pair(2)
366                 winmap += [(char, attribute), (" ", attribute)]
367             else:
368                 winmap += char + " "
369         if y % 2 == 0:
370             winmap += "  "
371     return offset, winmap_size, winmap
372
373
374 def win_inventory():
375     win_size = next(win["size"] for win in windows
376                                 if win["func"] == win_inventory)
377     winmap = []
378     winmap_size = [0, win_size[1]]
379     for line in world_data["inventory"]:
380         winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
381             else len(line)
382     count = 0
383     for line in world_data["inventory"]:
384         padding_size = winmap_size[1] - len(line)
385         line += (" " * padding_size)
386         if count == world_data["inventory_selection"]:
387             line_new = []
388             for x in range(len(line)):
389                 line_new += [(line[x], curses.A_REVERSE)]
390             line = line_new
391         winmap += line
392         winmap_size[0] = winmap_size[0] + 1
393         count += 1
394     offset = [0, 0]
395     if world_data["inventory_selection"] > win_size[0]/2:
396         if world_data["inventory_selection"] < len(world_data["inventory"]) \
397             - win_size[0]/2:
398             offset[0] = world_data["inventory_selection"] - int(win_size[0]/2)
399         else:
400             offset[0] = len(world_data["inventory"]) - win_size[0]
401     return offset, winmap_size, winmap
402
403
404 def win_look():
405     winmap = ""
406     winmap_size = [0, 0]
407     for line in world_data["look"]:
408         winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
409             else len(line)
410     for line in world_data["look"]:
411         padding_size = winmap_size[1] - len(line)
412         winmap += line + (" " * padding_size)
413         winmap_size[0] = winmap_size[0] + 1
414     offset = [world_data["look_scroll"], 0]
415     return offset, winmap_size, winmap
416
417
418 def win_info():
419     winmap = "T: " + str(world_data["turn"]) \
420         + " H: " + str(world_data["lifepoints"]) \
421         + " S: " + str(world_data["satiation"])
422     winmap_size = [1, len(winmap)]
423     offset = [0, 0]
424     return offset, winmap_size, winmap
425
426
427 def win_log():
428     win_size = next(win["size"] for win in windows if win["func"] == win_log)
429     offset = [0, 0]
430     winmap = ""
431     number_of_lines = 0
432     for line in world_data["log"]:
433         number_of_lines += math.ceil(len(line) / win_size[1])
434         padding_size = win_size[1] - (len(line) % win_size[1])
435         winmap += line + (padding_size * " ")
436     if number_of_lines < win_size[0]:
437         winmap = (" " * win_size[1] * (win_size[0] - number_of_lines)) + winmap
438         number_of_lines = win_size[0]
439     elif number_of_lines > win_size[0]:
440         offset[0] = number_of_lines - win_size[0]
441     winmap_size = [number_of_lines, win_size[1]]
442     return offset, winmap_size, winmap
443
444
445 def command_quit():
446     command_sender("QUIT")()
447     raise SystemExit("Received QUIT command, forwarded to server, leaving.")
448
449
450 def command_toggle_look_mode():
451     if not world_data["look_mode"]:
452         world_data["look_mode"] = True
453     else:
454         world_data["look_mode"] = False
455         world_data["map_center"] = world_data["avatar_position"]
456         query_mapcell()
457
458
459 def command_sender(string, int_field=None):
460     def command_send():
461         int_string = ""
462         if int_field:
463             int_string = " " + str(world_data[int_field])
464         io["file_out"].write(string + int_string + "\n")
465         io["file_out"].flush()
466     return command_send
467
468
469 def command_looker(string):
470     def command_look():
471         if string == "west" \
472                 and world_data["map_center"][1] > 0:
473             world_data["map_center"][1] -= 1
474         elif string == "east" \
475                 and world_data["map_center"][1] < world_data["map_size"] - 1:
476             world_data["map_center"][1] += 1
477         else:
478             y_unevenness = world_data["map_center"][0] % 2
479             y_evenness = int(not(y_unevenness))
480             if string[6:] == "west" and \
481                     world_data["map_center"][1] > -y_unevenness:
482                 if string[:5] == "north" and world_data["map_center"][0] > 0:
483                     world_data["map_center"][0] -= 1
484                     world_data["map_center"][1] -= y_evenness
485                 if string[:5] == "south" and world_data["map_center"][0] \
486                         < world_data["map_size"] - 1:
487                     world_data["map_center"][0] += 1
488                     world_data["map_center"][1] -= y_evenness
489             elif string[6:] == "east" and world_data["map_center"][1] \
490                     < world_data["map_size"] - y_unevenness:
491                 if string[:5] == "north" and world_data["map_center"][0] > 0:
492                     world_data["map_center"][0] -= 1
493                     world_data["map_center"][1] += y_unevenness
494                 if string[:5] == "south" and world_data["map_center"][0] \
495                         < world_data["map_size"] - 1:
496                     world_data["map_center"][0] += 1
497                     world_data["map_center"][1] += y_unevenness
498         query_mapcell()
499     return command_look
500
501
502 def command_look_scroller(string):
503     def command_look_scroll():
504         win_size = next(win["size"] for win in windows
505                                     if win["func"] == win_look)
506         if string == "up" and world_data["look_scroll"] > 0:
507             world_data["look_scroll"] -= 1
508         elif string == "down" and world_data["look_scroll"] \
509                 < len(world_data["look"]) - win_size[0]:
510             world_data["look_scroll"] += 1
511     return command_look_scroll
512
513
514 def command_inventory_selector(string):
515     def command_inventory_select():
516         if string == "up" and world_data["inventory_selection"] > 0:
517             world_data["inventory_selection"] -= 1
518         elif string == "down" and world_data["inventory_selection"] \
519                 < len(world_data["inventory"]) - 1:
520             world_data["inventory_selection"] += 1
521     return command_inventory_select
522
523
524 windows = [
525     {"config": [1, 33], "func": win_info, "title": "Info"},
526     {"config": [-7, 33], "func": win_log, "title": "Log"},
527     {"config": [4, 16], "func": win_inventory, "title": "Inventory"},
528     {"config": [4, 16], "func": win_look, "title": "Things here"},
529     {"config": [0, -34], "func": win_map, "title": "Map"}
530 ]
531 io = {
532     "path_out": "server/in",
533     "path_in": "server/out",
534     "path_worldstate": "server/worldstate"
535 }
536 commands = {
537     "A": (command_sender("ai"),),
538     "D": (command_sender("drop", "inventory_selection"),),
539     "J": (command_look_scroller("down"),),
540     "K": (command_look_scroller("up"),),
541     "P": (command_sender("pick_up"),),
542     "Q": (command_quit,),
543     "U": (command_sender("use", "inventory_selection"),),
544     "W": (command_sender("wait"),),
545     "c": (command_sender("move south-east"), command_looker("south-east")),
546     "d": (command_sender("move east"), command_looker("east")),
547     "e": (command_sender("move north-east"), command_looker("north-east")),
548     "j": (command_inventory_selector("down"),),
549     "k": (command_inventory_selector("up"),),
550     "l": (command_toggle_look_mode,),
551     "s": (command_sender("move west"), command_looker("west")),
552     "w": (command_sender("move north-west"), command_looker("north-west")),
553     "x": (command_sender("move south-west"), command_looker("south-west")),
554 }
555 message_queue = {
556     "open_end": False,
557     "messages": []
558 }
559 world_data = {
560     "avatar_position": [-1, -1],
561     "fov_map": "",
562     "inventory": [],
563     "inventory_selection": 0,
564     "lifepoints": -1,
565     "look": [],
566     "look_mode": False,
567     "look_scroll": 0,
568     "log": [],
569     "map_center": [-1, -1],
570     "map_size": 0,
571     "mem_map": "",
572     "satiation": -1,
573     "turn": -1
574 }
575 sep_size = 1  # Width of inter-window borders and title bars.
576 stdscr = None
577 screen_size = [0,0]
578
579
580 try:
581     if (not os.access(io["path_out"], os.F_OK)):
582         msg = "No server input file found at " + io["path_out"] + "."
583         raise SystemExit(msg)
584     io["file_out"] = open(io["path_out"], "a")
585     io["file_in"] = open(io["path_in"], "r")
586     curses.wrapper(cursed_main)
587 except SystemExit as exit:
588     print("ABORTING: " + exit.args[0])
589 except:
590     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
591     raise
592 finally:
593     if "file_out" in io:
594         io["file_out"].close()
595     if "file_in" in io:
596         io["file_in"].close()