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