8 def set_window_geometries():
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]
24 win_i = windows.index(win)
26 # If win is first window, it goes into the top left corner.
27 win["start"][0] = 0 + sep_size
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.
34 for i in range(win_i - 1, -1, -1):
36 if (win_top["start"][0] == 0 + sep_size):
38 win["start"][1] = win_top["start"][1] + win_top["size"][1] \
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
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).
59 while (win_test != win_top):
60 for i in range(win_i - 2, -1, -1):
62 if win_test["start"][0] > win_high["start"][0]:
64 next_free_y = win_high["start"][0] + win_high["size"][0] \
66 first_free_x = win_test["start"][1] + win_test["size"][1] \
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
76 global screen_size, stdscr
78 stdscr = curses.initscr()
79 screen_size = stdscr.getmaxyx()
83 cursed_main.redraw = True
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)
96 stdscr.addch(y, x, char, attr)
98 def draw_window_border_lines():
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]
108 [healthy_addch(j, i, '-') for i in range(start, end)]
110 [healthy_addch(i, j, '|') for i in range(start, end)]
112 def draw_window_border_corners():
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, '+')
129 def draw_window_contents():
131 """Draw winmap in area delimited by offset, winmap_size.
133 The individuall cell of a winmap is interpreted as either a single
134 character element, or as a tuple of character and attribute,
135 depending on the size len(cell) spits out.
139 stop[i] = win["size"][i] + offset[i]
140 if stop[i] >= winmap_size[i]:
141 stop[i] = winmap_size[i]
142 for y in range(offset[0], stop[0]):
143 for x in range(offset[1], stop[1]):
144 cell = winmap[y * winmap_size[1] + x]
149 y_in_screen = win["start"][0] + (y - offset[0])
150 x_in_screen = win["start"][1] + (x - offset[1])
151 if (y_in_screen < screen_size[0]
152 and x_in_screen < screen_size[1]):
153 healthy_addch(y_in_screen, x_in_screen, cell, attr)
154 def draw_scroll_hints():
155 def draw_scroll_string(n_lines_outside):
156 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
157 if len(hint) <= win["size"][ni]:
158 non_hint_space = win["size"][ni] - len(hint)
159 hint_offset = int(non_hint_space / 2)
160 for j in range(win["size"][ni] - non_hint_space):
161 pos_2 = win["start"][ni] + hint_offset + j
162 x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
163 healthy_addch(y, x, hint[j], curses.A_REVERSE)
164 def draw_scroll_arrows(ar1, ar2):
165 for j in range(win["size"][ni]):
166 pos_2 = win["start"][ni] + j
167 x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
168 healthy_addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
171 unit = 'rows' if ni else 'columns'
173 pos_1 = win["start"][i]
174 draw_scroll_arrows('^', '<')
175 draw_scroll_string(offset[i])
176 if (winmap_size[i] > offset[i] + win["size"][i]):
177 pos_1 = win["start"][i] + win["size"][i] - 1
178 draw_scroll_arrows('v', '>')
179 draw_scroll_string(winmap_size[i] - offset[i]
182 offset, winmap_size, winmap = win["func"]()
187 draw_window_border_lines()
188 draw_window_border_corners()
189 draw_window_contents()
193 def read_worldstate():
194 if not os.access(io["path_worldstate"], os.F_OK):
195 msg = "No world state file found at " + io["path_worldstate"] + "."
196 raise SystemExit(msg)
198 worldstate_file = open(io["path_worldstate"], "r")
199 turn_string = worldstate_file.readline()
200 if int(turn_string) != world_data["turn"]:
202 if not read_anew: # In rare cases, world may change, but not turn number.
203 mtime = os.stat(io["path_worldstate"])
204 if mtime != read_worldstate.last_checked_mtime:
205 read_worldstate.last_checked_mtime = mtime
208 cursed_main.redraw = True
209 world_data["turn"] = int(turn_string)
210 world_data["lifepoints"] = int(worldstate_file.readline())
211 world_data["satiation"] = int(worldstate_file.readline())
212 world_data["inventory"] = []
214 line = worldstate_file.readline().replace("\n", "")
217 world_data["inventory"] += [line]
218 world_data["avatar_position"][0] = int(worldstate_file.readline())
219 world_data["avatar_position"][1] = int(worldstate_file.readline())
220 if not world_data["look_mode"]:
221 world_data["map_center"][0] = world_data["avatar_position"][0]
222 world_data["map_center"][1] = world_data["avatar_position"][1]
223 world_data["map_size"] = int(worldstate_file.readline())
224 world_data["fov_map"] = ""
225 for i in range(world_data["map_size"]):
226 line = worldstate_file.readline().replace("\n", "")
227 world_data["fov_map"] += line
228 world_data["mem_map"] = ""
229 for i in range(world_data["map_size"]):
230 line = worldstate_file.readline().replace("\n", "")
231 world_data["mem_map"] += line
232 worldstate_file.close()
233 read_worldstate.last_checked_mtime = -1
236 def read_message_queue():
237 while (len(message_queue["messages"]) > 1
238 or (len(message_queue["messages"]) == 1
239 and not message_queue["open_end"])):
240 message = message_queue["messages"].pop(0)
241 if message == "THINGS_HERE START":
242 read_message_queue.parse_thingshere = True
243 world_data["look"] = []
244 elif message == "THINGS_HERE END":
245 read_message_queue.parse_thingshere = False
246 if world_data["look"] == []:
247 world_data["look"] = ["(none known)"]
248 cursed_main.redraw = True
249 elif read_message_queue.parse_thingshere:
250 world_data["look"] += [message]
251 elif message[0:4] == "LOG ":
252 world_data["log"] += [message[4:]]
253 cursed_main.redraw = True
254 elif message == "WORLD_UPDATED":
256 read_message_queue.parse_thingshere = False
260 command_sender("THINGS_HERE " + str(world_data["map_center"][0]) + " "
261 + str(world_data["map_center"][1]))()
262 world_data["look"] = ["(polling)"]
265 def cursed_main(stdscr):
269 if len(new_data_from_server) > 0:
270 ping_test.sent = False
271 elif ping_test.wait_start + half_wait_time < time.time():
272 if not ping_test.sent:
273 io["file_out"].write("PING\n")
274 io["file_out"].flush()
275 ping_test.sent = True
276 ping_test.wait_start = time.time()
278 raise SystemExit("Server not answering anymore.")
279 ping_test.wait_start = 0
281 def read_into_message_queue():
282 if new_data_from_server == "":
285 if new_data_from_server[-1] is not "\n":
287 new_messages = new_data_from_server.splitlines()
288 if message_queue["open_end"]:
289 message_queue["messages"][-1] += new_messages[0]
291 message_queue["messages"] += new_messages
293 message_queue["open_end"] = True
296 curses.curs_set(False)
297 # stdscr.keypad(True)
298 signal.signal(signal.SIGWINCH,
299 lambda ignore_1, ignore_2: set_window_geometries())
300 set_window_geometries()
303 stdscr.timeout(int(delay))
304 delay = delay * 1.1 if delay < 1000 else delay
305 if cursed_main.redraw:
308 cursed_main.redraw = False
309 char = stdscr.getch()
313 if len(commands[char]) == 1 or not world_data["look_mode"]:
315 cursed_main.redraw = True
318 cursed_main.redraw = True
319 new_data_from_server = io["file_in"].read()
321 read_into_message_queue()
327 win_size = next(win["size"] for win in windows if win["func"] == win_map)
330 if world_data["map_center"][i] * (i + 1) > win_size[i] / 2:
331 if world_data["map_center"][i] * (i + 1) \
332 < world_data["map_size"] * (i + 1) - win_size[i] / 2:
333 offset[i] = world_data["map_center"][i] * (i + 1) \
334 - int(win_size[i] / 2)
336 offset[1] = offset[1] + world_data["map_center"][0] % 2
338 offset[i] = world_data["map_size"] * (i + 1) - win_size[i] + i
339 winmap_size = [world_data["map_size"], world_data["map_size"] * 2 + 1]
341 curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
342 curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
343 for y in range(world_data["map_size"]):
344 for x in range(world_data["map_size"]):
345 char = world_data["fov_map"][y * world_data["map_size"] + x]
346 if world_data["look_mode"] and y == world_data["map_center"][0] \
347 and x == world_data["map_center"][1]:
350 world_data["mem_map"][y * world_data["map_size"] + x]
351 winmap += [(char, curses.A_REVERSE), (" ", curses.A_REVERSE)]
354 char = world_data["mem_map"][y * world_data["map_size"] + x]
355 attribute = curses.color_pair(1) if char == " " \
356 else curses.color_pair(2)
357 winmap += [(char, attribute), (" ", attribute)]
362 return offset, winmap_size, winmap
366 win_size = next(win["size"] for win in windows
367 if win["func"] == win_inventory)
369 winmap_size = [0, win_size[1]]
370 for line in world_data["inventory"]:
371 winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
374 for line in world_data["inventory"]:
375 padding_size = winmap_size[1] - len(line)
376 line += (" " * padding_size)
377 if count == world_data["inventory_selection"]:
379 for x in range(len(line)):
380 line_new += [(line[x], curses.A_REVERSE)]
383 winmap_size[0] = winmap_size[0] + 1
386 if world_data["inventory_selection"] > win_size[0]/2:
387 if world_data["inventory_selection"] < len(world_data["inventory"]) \
389 offset[0] = world_data["inventory_selection"] - int(win_size[0]/2)
391 offset[0] = len(world_data["inventory"]) - win_size[0]
392 return offset, winmap_size, winmap
398 for line in world_data["look"]:
399 winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
401 for line in world_data["look"]:
402 padding_size = winmap_size[1] - len(line)
403 winmap += line + (" " * padding_size)
404 winmap_size[0] = winmap_size[0] + 1
406 return offset, winmap_size, winmap
410 winmap = "T: " + str(world_data["turn"]) \
411 + " H: " + str(world_data["lifepoints"]) \
412 + " S: " + str(world_data["satiation"])
413 winmap_size = [1, len(winmap)]
415 return offset, winmap_size, winmap
419 win_size = next(win["size"] for win in windows if win["func"] == win_log)
423 for line in world_data["log"]:
424 number_of_lines += math.ceil(len(line) / win_size[1])
425 padding_size = win_size[1] - (len(line) % win_size[1])
426 winmap += line + (padding_size * " ")
427 if number_of_lines < win_size[0]:
428 winmap = (" " * win_size[1] * (win_size[0] - number_of_lines)) + winmap
429 number_of_lines = win_size[0]
430 elif number_of_lines > win_size[0]:
431 offset[0] = number_of_lines - win_size[0]
432 winmap_size = [number_of_lines, win_size[1]]
433 return offset, winmap_size, winmap
437 command_sender("QUIT")()
438 raise SystemExit("Received QUIT command, forwarded to server, leaving.")
441 def command_toggle_look_mode():
442 if not world_data["look_mode"]:
443 world_data["look_mode"] = True
445 world_data["look_mode"] = False
446 world_data["map_center"] = world_data["avatar_position"]
450 def command_sender(string):
452 io["file_out"].write(string + "\n")
453 io["file_out"].flush()
457 def command_looker(string):
459 if string == "west" \
460 and world_data["map_center"][1] > 0:
461 world_data["map_center"][1] -= 1
462 elif string == "east" \
463 and world_data["map_center"][1] < world_data["map_size"] - 1:
464 world_data["map_center"][1] += 1
466 y_unevenness = world_data["map_center"][0] % 2
467 y_evenness = int(not(y_unevenness))
468 if string[6:] == "west" and \
469 world_data["map_center"][1] > -y_unevenness:
470 if string[:5] == "north" and world_data["map_center"][0] > 0:
471 world_data["map_center"][0] -= 1
472 world_data["map_center"][1] -= y_evenness
473 if string[:5] == "south" and world_data["map_center"][0] \
474 < world_data["map_size"] - 1:
475 world_data["map_center"][0] += 1
476 world_data["map_center"][1] -= y_evenness
477 elif string[6:] == "east" and world_data["map_center"][1] \
478 < world_data["map_size"] - y_unevenness:
479 if string[:5] == "north" and world_data["map_center"][0] > 0:
480 world_data["map_center"][0] -= 1
481 world_data["map_center"][1] += y_unevenness
482 if string[:5] == "south" and world_data["map_center"][0] \
483 < world_data["map_size"] - 1:
484 world_data["map_center"][0] += 1
485 world_data["map_center"][1] += y_unevenness
490 def command_inventory_selector(string):
491 def command_inventory_select():
492 logfile = open("logfile", "a")
493 logfile.write(string + "\n")
495 if string == "up" and world_data["inventory_selection"] > 0:
496 world_data["inventory_selection"] -= 1
497 elif string == "down" and world_data["inventory_selection"] \
498 < len(world_data["inventory"]) - 1:
499 world_data["inventory_selection"] += 1
500 return command_inventory_select
504 {"config": [1, 33], "func": win_info},
505 {"config": [-7, 33], "func": win_log},
506 {"config": [4, 16], "func": win_inventory},
507 {"config": [4, 16], "func": win_look},
508 {"config": [0, -34], "func": win_map}
511 "path_out": "server/in",
512 "path_in": "server/out",
513 "path_worldstate": "server/worldstate"
516 "P": (command_sender("pick_up"),),
517 "Q": (command_quit,),
518 "W": (command_sender("wait"),),
519 "c": (command_sender("move south-east"), command_looker("south-east")),
520 "d": (command_sender("move east"), command_looker("east")),
521 "e": (command_sender("move north-east"), command_looker("north-east")),
522 "j": (command_inventory_selector("down"),),
523 "k": (command_inventory_selector("up"),),
524 "l": (command_toggle_look_mode,),
525 "s": (command_sender("move west"), command_looker("west")),
526 "w": (command_sender("move north-west"), command_looker("north-west")),
527 "x": (command_sender("move south-west"), command_looker("south-west")),
534 "avatar_position": [-1, -1],
537 "inventory_selection": 0,
542 "map_center": [-1, -1],
548 sep_size = 1 # Width of inter-window borders and title bars.
554 if (not os.access(io["path_out"], os.F_OK)):
555 msg = "No server input file found at " + io["path_out"] + "."
556 raise SystemExit(msg)
557 io["file_out"] = open(io["path_out"], "a")
558 io["file_in"] = open(io["path_in"], "r")
559 curses.wrapper(cursed_main)
560 except SystemExit as exit:
561 print("ABORTING: " + exit.args[0])
563 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
567 io["file_out"].close()
569 io["file_in"].close()