home · contact · privacy
Client: Remove debugging code, superfluous whitespace.
[plomrogue] / roguelike-client
1 #!/usr/bin/python3
2
3 import curses
4 import os
5 import signal
6 import time
7
8
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
14
15
16 import types
17 class Window:
18     def __init__(self, title, draw_function, size):
19         self.title = title
20         self.draw = types.MethodType(draw_function, self)
21         self.size = size
22
23
24 def set_window_geometries():
25
26     def size_window(config):
27         size = [0, 0]
28         size[0] = config[0]
29         if (config[0] == 0):
30             size[0] = screen_size[0] - sep_size
31         elif (config[0] < 0):
32             size[0] = screen_size[0] + config[0] - sep_size
33         size[1] = config[1]
34         if (config[1] == 0):
35             size[1] = screen_size[1]
36         elif (config[1] < 0):
37             size[1] = screen_size[1] + config[1]
38         return size
39
40     def place_window(win):
41         win_i = windows.index(win)
42
43         # If win is first window, it goes into the top left corner.
44         win.start = [0 + sep_size, 0]
45         if (win_i > 0):
46
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.
49             win_top = None
50             for i in range(win_i - 1, -1, -1):
51                 win_top = windows[i]
52                 if (win_top.start[0] == 0 + sep_size):
53                     break
54             win.start[1] = win_top.start[1] + win_top.size[1] + sep_size
55
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
64
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).
71             else:
72                 win_test = win_prev
73                 win_high = None
74                 while (win_test != win_top):
75                     for i in range(win_i - 2, -1, -1):
76                         win_high = windows[i]
77                         if win_test.start[0] > win_high.start[0]:
78                             break
79                     next_free_y = win_high.start[0] + win_high.size[0] \
80                         + sep_size
81                     first_free_x = win_test.start[1] + win_test.size[1] \
82                         + sep_size
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
88                         break
89                     win_test = win_high
90
91     global screen_size, stdscr
92     curses.endwin()
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)
99         place_window(window)
100     cursed_main.redraw = True
101
102
103 def draw_screen():
104
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)
112         else:
113             stdscr.addch(y, x, char, attr)
114
115     def draw_window_border_lines():
116         for win in windows:
117             for k in range(2):
118                 j = win.start[int(k == 0)] - sep_size
119                 if (j >= 0 and j < screen_size[int(k == 0)]):
120                     start = win.start[k]
121                     end = win.start[k] + win.size[k]
122                     end = end if end < screen_size[k] else screen_size[k]
123                     if k:
124                         [healthy_addch(j, i, '-') for i in range(start, end)]
125                     else:
126                         [healthy_addch(i, j, '|') for i in range(start, end)]
127
128     def draw_window_border_corners():
129         for win in windows:
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, '+')
144
145     def draw_window_titles():
146         for win in windows:
147             title = " " + win.title + " "
148             if len(title) <= win.size[1]:
149                 y = win.start[0] - 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])
153
154     def draw_window_contents():
155         def draw_winmap():
156             """Draw winmap in area delimited by offset, winmap_size.
157
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.
161             """
162             stop = [0, 0]
163             for i in range(2):
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]
170                     attr = 0
171                     if len(cell) > 1:
172                         attr = cell[1]
173                         cell = cell[0]
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)
194             for i in range(2):
195                 ni = int(i == 0)
196                 unit = 'rows' if ni else 'columns'
197                 if (offset[i] > 0):
198                     pos_1 = win.start[i]
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]
205                         - win.size[i])
206         for win in windows:
207             offset, winmap_size, winmap = win.draw()
208             draw_winmap()
209             draw_scroll_hints()
210
211     stdscr.erase()
212     draw_window_border_lines()
213     draw_window_border_corners()
214     draw_window_titles()
215     draw_window_contents()
216     stdscr.refresh()
217
218
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)
223     read_anew = False
224     worldstate_file = open(io["path_worldstate"], "r")
225     turn_string = worldstate_file.readline()
226     if int(turn_string) != world_data["turn"]:
227         read_anew = True
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
232             read_anew = True
233     if read_anew:
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"] = []
239         while True:
240             line = worldstate_file.readline().replace("\n", "")
241             if line == '%':
242                 break
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
260
261
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":
281             query_mapcell()
282 read_message_queue.parse_thingshere = False
283
284
285 def cursed_main(stdscr):
286
287     def ping_test():
288         half_wait_time = 5
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()
297             elif ping_test.sent:
298                 raise SystemExit("Server not answering anymore.")
299     ping_test.wait_start = 0
300
301     def read_into_message_queue():
302         if new_data_from_server == "":
303             return
304         new_open_end = False
305         if new_data_from_server[-1] is not "\n":
306             new_open_end = True
307         new_messages = new_data_from_server.splitlines()
308         if message_queue["open_end"]:
309             message_queue["messages"][-1] += new_messages[0]
310             del new_messages[0]
311         message_queue["messages"] += new_messages
312         if new_open_end:
313             message_queue["open_end"] = True
314
315     curses.noecho()
316     curses.curs_set(False)
317     signal.signal(signal.SIGWINCH,
318         lambda ignore_1, ignore_2: set_window_geometries())
319     set_window_geometries()
320     delay = 1
321     while True:
322         stdscr.timeout(int(delay))
323         delay = delay * 1.1 if delay < 1000 else delay
324         if cursed_main.redraw:
325             delay = 1
326             draw_screen()
327             cursed_main.redraw = False
328         char = stdscr.getch()
329         if char >= 0:
330             char = chr(char)
331             if char in commands:
332                 if len(commands[char]) == 1 or not world_data["look_mode"]:
333                     commands[char][0]()
334                     cursed_main.redraw = True
335                 else:
336                     commands[char][1]()
337                     cursed_main.redraw = True
338         new_data_from_server = io["file_in"].read()
339         ping_test()
340         read_into_message_queue()
341         read_worldstate()
342         read_message_queue()
343
344
345 message_queue = {
346     "open_end": False,
347     "messages": []
348 }
349 sep_size = 1  # Width of inter-window borders and title bars.
350 stdscr = None
351 screen_size = [0,0]
352 windows = []
353
354 try:
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])
363 except:
364     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
365     raise
366 finally:
367     if "file_out" in io:
368         io["file_out"].close()
369     if "file_in" in io:
370         io["file_in"].close()