9 from client.config.world_data import world_data
10 from client.config.io import io
11 from client.config.commands import commands
12 from client.config.windows import windows_config
13 from client.query_mapcell import query_mapcell
18 def __init__(self, title, draw_function, size):
20 self.draw = types.MethodType(draw_function, self)
24 def set_window_geometries():
26 def size_window(config):
30 size[0] = screen_size[0] - sep_size
32 size[0] = screen_size[0] + config[0] - sep_size
35 size[1] = screen_size[1]
37 size[1] = screen_size[1] + config[1]
40 def place_window(win):
41 win_i = windows.index(win)
43 # If win is first window, it goes into the top left corner.
44 win.start = [0 + sep_size, 0]
47 # If not, get win's closest predecessor starting a new stack on the
48 # screen top,fit win's top left to that win_top's top right corner.
50 for i in range(win_i - 1, -1, -1):
52 if (win_top.start[0] == 0 + sep_size):
54 win.start[1] = win_top.start[1] + win_top.size[1] + sep_size
56 # If enough space is found below win's predecessor, fit win's top
57 # left corner to that predecessor's bottom left corner.
58 win_prev = windows[win_i - 1]
59 next_free_y = win_prev.start[0] + win_prev.size[0] + sep_size
60 if (win.size[1] <= win_prev.size[1] and
61 win.size[0] <= screen_size[0] - next_free_y):
62 win.start[1] = win_prev.start[1]
63 win.start[0] = next_free_y
65 # If that fails, try to fit win's top left corner to the top right
66 # corner of its closest predecessor win_test 1) below win_top (see
67 # above) 2) and with enough space open to its right between its
68 # right edge and the lower edge of a win_high located directly
69 # above win_test to fit win there (without growing further to the
70 # right than win_high does or surpassing the screen's lower edge).
74 while (win_test != win_top):
75 for i in range(win_i - 2, -1, -1):
77 if win_test.start[0] > win_high.start[0]:
79 next_free_y = win_high.start[0] + win_high.size[0] \
81 first_free_x = win_test.start[1] + win_test.size[1] \
83 last_free_x = win_high.start[1] + win_high.size[1]
84 if (win.size[0] <= screen_size[0] - next_free_y and
85 win.size[1] <= last_free_x - first_free_x):
86 win.start[1] = first_free_x
87 win.start[0] = next_free_y
91 global screen_size, stdscr
93 stdscr = curses.initscr()
94 screen_size = stdscr.getmaxyx()
95 for config in windows_config:
96 size = size_window(config["config"])
97 window = Window(config["title"], config["func"], size)
98 windows.append(window)
100 cursed_main.redraw = True
105 def healthy_addch(y, x, char, attr=0):
106 """Workaround for <http://stackoverflow.com/questions/7063128/>."""
107 if y == screen_size[0] - 1 and x == screen_size[1] - 1:
108 char_before = stdscr.inch(y, x - 1)
109 stdscr.addch(y, x - 1, char, attr)
110 stdscr.insstr(y, x - 1, " ")
111 stdscr.addch(y, x - 1, char_before)
113 stdscr.addch(y, x, char, attr)
115 def draw_window_border_lines():
118 j = win.start[int(k == 0)] - sep_size
119 if (j >= 0 and j < screen_size[int(k == 0)]):
121 end = win.start[k] + win.size[k]
122 end = end if end < screen_size[k] else screen_size[k]
124 [healthy_addch(j, i, '-') for i in range(start, end)]
126 [healthy_addch(i, j, '|') for i in range(start, end)]
128 def draw_window_border_corners():
130 up = win.start[0] - sep_size
131 down = win.start[0] + win.size[0]
132 left = win.start[1] - sep_size
133 right = win.start[1] + win.size[1]
134 if (up >= 0 and up < screen_size[0]):
135 if (left >= 0 and left < screen_size[1]):
136 healthy_addch(up, left, '+')
137 if (right >= 0 and right < screen_size[1]):
138 healthy_addch(up, right, '+')
139 if (down >= 0 and down < screen_size[0]):
140 if (left >= 0 and left < screen_size[1]):
141 healthy_addch(down, left, '+')
142 if (right >= 0 and right < screen_size[1]):
143 healthy_addch(down, right, '+')
145 def draw_window_titles():
147 title = " " + win.title + " "
148 if len(title) <= win.size[1]:
150 start_x = win.start[1] + int((win.size[1] - len(title))/2)
151 for x in range(len(title)):
152 healthy_addch(y, start_x + x, title[x])
154 def draw_window_contents():
156 """Draw winmap in area delimited by offset, winmap_size.
158 The individuall cell of a winmap is interpreted as either a single
159 character element, or as a tuple of character and attribute,
160 depending on the size len(cell) spits out.
164 stop[i] = win.size[i] + offset[i]
165 if stop[i] >= winmap_size[i]:
166 stop[i] = winmap_size[i]
167 for y in range(offset[0], stop[0]):
168 for x in range(offset[1], stop[1]):
169 cell = winmap[y * winmap_size[1] + x]
174 y_in_screen = win.start[0] + (y - offset[0])
175 x_in_screen = win.start[1] + (x - offset[1])
176 if (y_in_screen < screen_size[0]
177 and x_in_screen < screen_size[1]):
178 healthy_addch(y_in_screen, x_in_screen, cell, attr)
179 def draw_scroll_hints():
180 def draw_scroll_string(n_lines_outside):
181 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
182 if len(hint) <= win.size[ni]:
183 non_hint_space = win.size[ni] - len(hint)
184 hint_offset = int(non_hint_space / 2)
185 for j in range(win.size[ni] - non_hint_space):
186 pos_2 = win.start[ni] + hint_offset + j
187 x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
188 healthy_addch(y, x, hint[j], curses.A_REVERSE)
189 def draw_scroll_arrows(ar1, ar2):
190 for j in range(win.size[ni]):
191 pos_2 = win.start[ni] + j
192 x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
193 healthy_addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
196 unit = 'rows' if ni else 'columns'
199 draw_scroll_arrows('^', '<')
200 draw_scroll_string(offset[i])
201 if (winmap_size[i] > offset[i] + win.size[i]):
202 pos_1 = win.start[i] + win.size[i] - 1
203 draw_scroll_arrows('v', '>')
204 draw_scroll_string(winmap_size[i] - offset[i]
207 offset, winmap_size, winmap = win.draw()
212 draw_window_border_lines()
213 draw_window_border_corners()
215 draw_window_contents()
219 def read_worldstate():
220 if not os.access(io["path_worldstate"], os.F_OK):
221 msg = "No world state file found at " + io["path_worldstate"] + "."
222 raise SystemExit(msg)
224 worldstate_file = open(io["path_worldstate"], "r")
225 turn_string = worldstate_file.readline()
226 if int(turn_string) != world_data["turn"]:
228 if not read_anew: # In rare cases, world may change, but not turn number.
229 mtime = os.stat(io["path_worldstate"])
230 if mtime != read_worldstate.last_checked_mtime:
231 read_worldstate.last_checked_mtime = mtime
234 cursed_main.redraw = True
235 world_data["turn"] = int(turn_string)
236 world_data["lifepoints"] = int(worldstate_file.readline())
237 world_data["satiation"] = int(worldstate_file.readline())
238 world_data["inventory"] = []
240 line = worldstate_file.readline().replace("\n", "")
243 world_data["inventory"] += [line]
244 world_data["avatar_position"][0] = int(worldstate_file.readline())
245 world_data["avatar_position"][1] = int(worldstate_file.readline())
246 if not world_data["look_mode"]:
247 world_data["map_center"][0] = world_data["avatar_position"][0]
248 world_data["map_center"][1] = world_data["avatar_position"][1]
249 world_data["map_size"] = int(worldstate_file.readline())
250 world_data["fov_map"] = ""
251 for i in range(world_data["map_size"]):
252 line = worldstate_file.readline().replace("\n", "")
253 world_data["fov_map"] += line
254 world_data["mem_map"] = ""
255 for i in range(world_data["map_size"]):
256 line = worldstate_file.readline().replace("\n", "")
257 world_data["mem_map"] += line
258 worldstate_file.close()
259 read_worldstate.last_checked_mtime = -1
262 def read_message_queue():
263 while (len(message_queue["messages"]) > 1
264 or (len(message_queue["messages"]) == 1
265 and not message_queue["open_end"])):
266 message = message_queue["messages"].pop(0)
267 if message == "THINGS_HERE START":
268 read_message_queue.parse_thingshere = True
269 world_data["look"] = []
270 elif message == "THINGS_HERE END":
271 read_message_queue.parse_thingshere = False
272 if world_data["look"] == []:
273 world_data["look"] = ["(none known)"]
274 cursed_main.redraw = True
275 elif read_message_queue.parse_thingshere:
276 world_data["look"] += [message]
277 elif message[0:4] == "LOG ":
278 world_data["log"] += [message[4:]]
279 cursed_main.redraw = True
280 elif message == "WORLD_UPDATED":
282 read_message_queue.parse_thingshere = False
285 def cursed_main(stdscr):
289 if len(new_data_from_server) > 0:
290 ping_test.sent = False
291 elif ping_test.wait_start + half_wait_time < time.time():
292 if not ping_test.sent:
293 io["file_out"].write("PING\n")
294 io["file_out"].flush()
295 ping_test.sent = True
296 ping_test.wait_start = time.time()
298 raise SystemExit("Server not answering anymore.")
299 ping_test.wait_start = 0
301 def read_into_message_queue():
302 if new_data_from_server == "":
305 if new_data_from_server[-1] is not "\n":
307 new_messages = new_data_from_server.splitlines()
308 if message_queue["open_end"]:
309 message_queue["messages"][-1] += new_messages[0]
311 message_queue["messages"] += new_messages
313 message_queue["open_end"] = True
316 curses.curs_set(False)
317 signal.signal(signal.SIGWINCH,
318 lambda ignore_1, ignore_2: set_window_geometries())
319 set_window_geometries()
322 stdscr.timeout(int(delay))
323 delay = delay * 1.1 if delay < 1000 else delay
324 if cursed_main.redraw:
327 cursed_main.redraw = False
328 char = stdscr.getch()
332 if len(commands[char]) == 1 or not world_data["look_mode"]:
334 cursed_main.redraw = True
337 cursed_main.redraw = True
338 new_data_from_server = io["file_in"].read()
340 read_into_message_queue()
349 sep_size = 1 # Width of inter-window borders and title bars.
355 if (not os.access(io["path_out"], os.F_OK)):
356 msg = "No server input file found at " + io["path_out"] + "."
357 raise SystemExit(msg)
358 io["file_out"] = open(io["path_out"], "a")
359 io["file_in"] = open(io["path_in"], "r")
360 curses.wrapper(cursed_main)
361 except SystemExit as exit:
362 print("ABORTING: " + exit.args[0])
364 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
368 io["file_out"].close()
370 io["file_in"].close()