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