home · contact · privacy
5bcfee5f641937450155aa63f198d7fc45963112
[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                     # start = start if start >= 0 else 0
105                     end = win["start"][k] + win["size"][k]
106                     end = end if end < screen_size[k] else screen_size[k]
107                     if k:
108                         [healthy_addch(j, i, '-') for i in range(start, end)]
109                     else:
110                         [healthy_addch(i, j, '|') for i in range(start, end)]
111
112     def draw_window_border_corners():
113         for win in windows:
114             up = win["start"][0] - sep_size
115             down = win["start"][0] + win["size"][0]
116             left = win["start"][1] - sep_size
117             right = win["start"][1] + win["size"][1]
118             if (up >= 0 and up < screen_size[0]):
119                 if (left >= 0 and left < screen_size[1]):
120                     healthy_addch(up, left, '+')
121                 if (right >= 0 and right < screen_size[1]):
122                     healthy_addch(up, right, '+')
123             if (down >= 0 and down < screen_size[0]):
124                 if (left >= 0 and left < screen_size[1]):
125                     healthy_addch(down, left, '+')
126                 if (right >= 0 and right < screen_size[1]):
127                     healthy_addch(down, right, '+')
128
129     def draw_window_contents():
130         def draw_winmap():
131             stop = [0, 0]
132             for i in range(2):
133                 stop[i] = win["size"][i] + offset[i]
134                 if stop[i] >= winmap_size[i]:
135                     stop[i] = winmap_size[i]
136             for y in range(offset[0], stop[0]):
137                 for x in range(offset[1], stop[1]):
138                     cell = winmap[y * winmap_size[1] + x]
139                     attr = 0
140                     if len(cell) > 1:
141                         attr = cell[1]
142                         cell = cell[0]
143                     y_in_screen = win["start"][0] + (y - offset[0])
144                     x_in_screen = win["start"][1] + (x - offset[1])
145                     if (y_in_screen < screen_size[0]
146                             and x_in_screen < screen_size[1]):
147                         healthy_addch(y_in_screen, x_in_screen, cell, attr)
148         def draw_scroll_hints():
149             def draw_scroll_string(n_lines_outside):
150                 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
151                 if len(hint) <= win["size"][ni]:
152                     non_hint_space = win["size"][ni] - len(hint)
153                     hint_offset = int(non_hint_space / 2)
154                     for j in range(win["size"][ni] - non_hint_space):
155                         pos_2 = win["start"][ni] + hint_offset + j
156                         x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
157                         healthy_addch(y, x, hint[j], curses.A_REVERSE)
158             def draw_scroll_arrows(ar1, ar2):
159                 for j in range(win["size"][ni]):
160                     pos_2 = win["start"][ni] + j
161                     x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
162                     healthy_addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
163             for i in range(2):
164                 ni = int(i == 0)
165                 unit = 'rows' if ni else 'columns'
166                 if (offset[i] > 0):
167                     pos_1 = win["start"][i]
168                     draw_scroll_arrows('^', '<')
169                     draw_scroll_string(offset[i])
170                 if (winmap_size[i] > offset[i] + win["size"][i]):
171                     pos_1 = win["start"][i] + win["size"][i] - 1
172                     draw_scroll_arrows('v', '>')
173                     draw_scroll_string(winmap_size[i] - offset[i]
174                         - win["size"][i])
175         for win in windows:
176             offset, winmap_size, winmap = win["func"]()
177             draw_winmap()
178             draw_scroll_hints()
179
180     stdscr.erase()
181     draw_window_border_lines()
182     draw_window_border_corners()
183     draw_window_contents()
184     stdscr.refresh()
185
186
187 def read_worldstate():
188     if not os.access(io["path_worldstate"], os.F_OK):
189         msg = "No world state file found at " + io["path_worldstate"] + "."
190         raise SystemExit(msg)
191     read_anew = False
192     worldstate_file = open(io["path_worldstate"], "r")
193     turn_string = worldstate_file.readline()
194     if int(turn_string) != world_data["turn"]:
195         read_anew = True
196     if not read_anew: # In rare cases, world may change, but not turn number.
197         mtime = os.stat(io["path_worldstate"])
198         if mtime != read_worldstate.last_checked_mtime:
199             read_worldstate.last_checked_mtime = mtime
200             read_anew = True
201     if read_anew:
202         cursed_main.redraw = True
203         world_data["turn"] = int(turn_string)
204         world_data["lifepoints"] = int(worldstate_file.readline())
205         world_data["satiation"] = int(worldstate_file.readline())
206         world_data["inventory"] = []
207         while True:
208             line = worldstate_file.readline().replace("\n", "")
209             if line == '%':
210                 break
211             world_data["inventory"] += [line]
212         world_data["avatar_position"][0] = int(worldstate_file.readline())
213         world_data["avatar_position"][1] = int(worldstate_file.readline())
214         if not world_data["look_mode"]:
215             world_data["map_center"][0] = world_data["avatar_position"][0]
216             world_data["map_center"][1] = world_data["avatar_position"][1]
217         world_data["map_size"] = int(worldstate_file.readline())
218         world_data["fov_map"] = ""
219         for i in range(world_data["map_size"]):
220             line = worldstate_file.readline().replace("\n", "")
221             world_data["fov_map"] += line
222         world_data["mem_map"] = ""
223         for i in range(world_data["map_size"]):
224             line = worldstate_file.readline().replace("\n", "")
225             world_data["mem_map"] += line
226     worldstate_file.close()
227 read_worldstate.last_checked_mtime = -1
228
229
230 def read_message_queue():
231     while (len(message_queue["messages"]) > 1
232         or (len(message_queue["messages"]) == 1
233             and not message_queue["open_end"])):
234         message = message_queue["messages"].pop(0)
235         if message == "THINGS_HERE START":
236             read_message_queue.parse_thingshere = True
237             world_data["look"] = []
238         elif message == "THINGS_HERE END":
239             read_message_queue.parse_thingshere = False
240             if world_data["look"] == []:
241                 world_data["look"] = ["(none known)"]
242             cursed_main.redraw = True
243         elif read_message_queue.parse_thingshere:
244             world_data["look"] += [message]
245         elif message[0:4] == "LOG ":
246             world_data["log"] += [message[4:]]
247             cursed_main.redraw = True
248         elif message == "WORLD_UPDATED":
249             query_mapcell()
250 read_message_queue.parse_thingshere = False
251
252
253 def query_mapcell():
254    command_sender("THINGS_HERE " + str(world_data["map_center"][0]) + " "
255         + str(world_data["map_center"][1]))()
256    world_data["look"] = ["(polling)"]
257
258
259 def cursed_main(stdscr):
260
261     def ping_test():
262         half_wait_time = 5
263         if len(new_data_from_server) > 0:
264             ping_test.sent = False
265         elif ping_test.wait_start + half_wait_time < time.time():
266             if not ping_test.sent:
267                 io["file_out"].write("PING\n")
268                 io["file_out"].flush()
269                 ping_test.sent = True
270                 ping_test.wait_start = time.time()
271             elif ping_test.sent:
272                 raise SystemExit("Server not answering anymore.")
273     ping_test.wait_start = 0
274
275     def read_into_message_queue():
276         if new_data_from_server == "":
277             return
278         new_open_end = False
279         if new_data_from_server[-1] is not "\n":
280             new_open_end = True
281         new_messages = new_data_from_server.splitlines()
282         if message_queue["open_end"]:
283             message_queue["messages"][-1] += new_messages[0]
284             del new_messages[0]
285         message_queue["messages"] += new_messages
286         if new_open_end:
287             message_queue["open_end"] = True
288
289     curses.noecho()
290     curses.curs_set(False)
291     # stdscr.keypad(True)
292     signal.signal(signal.SIGWINCH,
293         lambda ignore_1, ignore_2: set_window_geometries())
294     set_window_geometries()
295     delay = 1
296     while True:
297         stdscr.timeout(int(delay))
298         delay = delay * 1.1 if delay < 1000 else delay
299         if cursed_main.redraw:
300             delay = 1
301             draw_screen()
302             cursed_main.redraw = False
303         char = stdscr.getch()
304         if char >= 0:
305             char = chr(char)
306             if char in commands:
307                 if len(commands[char]) == 1 or not world_data["look_mode"]:
308                     commands[char][0]()
309                     cursed_main.redraw = True
310                 else:
311                     commands[char][1]()
312                     cursed_main.redraw = True
313         new_data_from_server = io["file_in"].read()
314         ping_test()
315         read_into_message_queue()
316         read_worldstate()
317         read_message_queue()
318
319
320 def win_map():
321     win_size = next(win["size"] for win in windows if win["func"] == win_map)
322     offset = [0, 0]
323     for i in range(2):
324         if world_data["map_center"][i] * (i + 1) > win_size[i] / 2:
325             if world_data["map_center"][i] * (i + 1) \
326                 < world_data["map_size"] * (i + 1) - win_size[i] / 2:
327                 offset[i] = world_data["map_center"][i] * (i + 1) \
328                     - int(win_size[i] / 2)
329                 if i == 1:
330                     offset[1] = offset[1] + world_data["map_center"][0] % 2
331             else:
332                 offset[i] = world_data["map_size"] * (i + 1) - win_size[i] + i
333     winmap_size = [world_data["map_size"], world_data["map_size"] * 2 + 1]
334     winmap = []
335     curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
336     curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
337     for y in range(world_data["map_size"]):
338         for x in range(world_data["map_size"]):
339             char = world_data["fov_map"][y * world_data["map_size"] + x]
340             if world_data["look_mode"] and y == world_data["map_center"][0] \
341                     and x == world_data["map_center"][1]:
342                 if char == " ":
343                     char = \
344                         world_data["mem_map"][y * world_data["map_size"] + x]
345                 winmap += [(char, curses.A_REVERSE), (" ", curses.A_REVERSE)]
346                 continue
347             if char == " ":
348                 char = world_data["mem_map"][y * world_data["map_size"] + x]
349                 attribute = curses.color_pair(1) if char == " " \
350                     else curses.color_pair(2)
351                 winmap += [(char, attribute), (" ", attribute)]
352             else:
353                 winmap += char + " "
354         if y % 2 == 0:
355             winmap += "  "
356     return offset, winmap_size, winmap
357
358
359 def win_inventory():
360     winmap = ""
361     winmap_size = [0, 0]
362     for line in world_data["inventory"]:
363         winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
364             else len(line)
365     for line in world_data["inventory"]:
366         padding_size = winmap_size[1] - len(line)
367         winmap += line + (" " * padding_size)
368         winmap_size[0] = winmap_size[0] + 1
369     offset = [0, 0]
370     return offset, winmap_size, winmap
371
372
373 def win_look():
374     winmap = ""
375     winmap_size = [0, 0]
376     for line in world_data["look"]:
377         winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
378             else len(line)
379     for line in world_data["look"]:
380         padding_size = winmap_size[1] - len(line)
381         winmap += line + (" " * padding_size)
382         winmap_size[0] = winmap_size[0] + 1
383     offset = [0, 0]
384     return offset, winmap_size, winmap
385
386
387 def win_info():
388     winmap = "T: " + str(world_data["turn"]) \
389         + " H: " + str(world_data["lifepoints"]) \
390         + " S: " + str(world_data["satiation"])
391     winmap_size = [1, len(winmap)]
392     offset = [0, 0]
393     return offset, winmap_size, winmap
394
395
396 def win_log():
397     win_size = next(win["size"] for win in windows if win["func"] == win_log)
398     offset = [0, 0]
399     winmap = ""
400     number_of_lines = 0
401     for line in world_data["log"]:
402         number_of_lines += math.ceil(len(line) / win_size[1])
403         padding_size = win_size[1] - (len(line) % win_size[1])
404         winmap += line + (padding_size * " ")
405     if number_of_lines < win_size[0]:
406         winmap = (" " * win_size[1] * (win_size[0] - number_of_lines)) + winmap
407         number_of_lines = win_size[0]
408     elif number_of_lines > win_size[0]:
409         offset[0] = number_of_lines - win_size[0]
410     winmap_size = [number_of_lines, win_size[1]]
411     return offset, winmap_size, winmap
412
413
414 def command_quit():
415     command_sender("QUIT")()
416     raise SystemExit("Received QUIT command, forwarded to server, leaving.")
417
418
419 def command_toggle_look_mode():
420     if not world_data["look_mode"]:
421         world_data["look_mode"] = True
422     else:
423         world_data["look_mode"] = False
424         world_data["map_center"] = world_data["avatar_position"]
425         query_mapcell()
426
427
428 def command_sender(string):
429     def command_send():
430         io["file_out"].write(string + "\n")
431         io["file_out"].flush()
432     return command_send
433
434
435 def command_looker(string):
436     def command_look():
437         if string == "west" \
438                 and world_data["map_center"][1] > 0:
439             world_data["map_center"][1] -= 1
440         elif string == "east" \
441                 and world_data["map_center"][1] < world_data["map_size"] - 1:
442             world_data["map_center"][1] += 1
443         else:
444             y_unevenness = world_data["map_center"][0] % 2
445             y_evenness = int(not(y_unevenness))
446             if string[6:] == "west" and \
447                     world_data["map_center"][1] > -y_unevenness:
448                 if string[:5] == "north" and world_data["map_center"][0] > 0:
449                     world_data["map_center"][0] -= 1
450                     world_data["map_center"][1] -= y_evenness
451                 if string[:5] == "south" and world_data["map_center"][0] \
452                         < world_data["map_size"] - 1:
453                     world_data["map_center"][0] += 1
454                     world_data["map_center"][1] -= y_evenness
455             elif string[6:] == "east" and world_data["map_center"][1] \
456                     < world_data["map_size"] - y_unevenness:
457                 if string[:5] == "north" and world_data["map_center"][0] > 0:
458                     world_data["map_center"][0] -= 1
459                     world_data["map_center"][1] += y_unevenness
460                 if string[:5] == "south" and world_data["map_center"][0] \
461                         < world_data["map_size"] - 1:
462                     world_data["map_center"][0] += 1
463                     world_data["map_center"][1] += y_unevenness
464         query_mapcell()
465     return command_look
466
467
468 windows = [
469     {"config": [1, 33], "func": win_info},
470     {"config": [-7, 33], "func": win_log},
471     {"config": [4, 16], "func": win_inventory},
472     {"config": [4, 16], "func": win_look},
473     {"config": [0, -34], "func": win_map}
474 ]
475 io = {
476     "path_out": "server/in",
477     "path_in": "server/out",
478     "path_worldstate": "server/worldstate"
479 }
480 commands = {
481     "P": (command_sender("pick_up"),),
482     "Q": (command_quit,),
483     "W": (command_sender("wait"),),
484     "c": (command_sender("move south-east"), command_looker("south-east")),
485     "d": (command_sender("move east"), command_looker("east")),
486     "e": (command_sender("move north-east"), command_looker("north-east")),
487     "l": (command_toggle_look_mode,),
488     "s": (command_sender("move west"), command_looker("west")),
489     "w": (command_sender("move north-west"), command_looker("north-west")),
490     "x": (command_sender("move south-west"), command_looker("south-west")),
491 }
492 message_queue = {
493     "open_end": False,
494     "messages": []
495 }
496 world_data = {
497     "avatar_position": [-1, -1],
498     "fov_map": "",
499     "inventory": [],
500     "lifepoints": -1,
501     "look": [],
502     "look_mode": False,
503     "log": [],
504     "map_center": [-1, -1],
505     "map_size": 0,
506     "mem_map": "",
507     "satiation": -1,
508     "turn": -1
509 }
510 sep_size = 1  # Width of inter-window borders and title bars.
511 stdscr = None
512 screen_size = [0,0]
513
514
515 try:
516     if (not os.access(io["path_out"], os.F_OK)):
517         msg = "No server input file found at " + io["path_out"] + "."
518         raise SystemExit(msg)
519     io["file_out"] = open(io["path_out"], "a")
520     io["file_in"] = open(io["path_in"], "r")
521     curses.wrapper(cursed_main)
522 except SystemExit as exit:
523     print("ABORTING: " + exit.args[0])
524 except:
525     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
526     raise
527 finally:
528     if "file_out" in io:
529         io["file_out"].close()
530     if "file_in" in io:
531         io["file_in"].close()