home · contact · privacy
Client: Restructure into modules below client/.
[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             logfile = open("logfile", "a")
208             logfile.write(repr(Window) + "\n")
209             logfile.write(repr(win) + "\n")
210             logfile.close()
211             offset, winmap_size, winmap = win.draw()
212             draw_winmap()
213             draw_scroll_hints()
214
215     stdscr.erase()
216     draw_window_border_lines()
217     draw_window_border_corners()
218     draw_window_titles()
219     draw_window_contents()
220     stdscr.refresh()
221
222
223 def read_worldstate():
224     if not os.access(io["path_worldstate"], os.F_OK):
225         msg = "No world state file found at " + io["path_worldstate"] + "."
226         raise SystemExit(msg)
227     read_anew = False
228     worldstate_file = open(io["path_worldstate"], "r")
229     turn_string = worldstate_file.readline()
230     if int(turn_string) != world_data["turn"]:
231         read_anew = True
232     if not read_anew: # In rare cases, world may change, but not turn number.
233         mtime = os.stat(io["path_worldstate"])
234         if mtime != read_worldstate.last_checked_mtime:
235             read_worldstate.last_checked_mtime = mtime
236             read_anew = True
237     if read_anew:
238         cursed_main.redraw = True
239         world_data["turn"] = int(turn_string)
240         world_data["lifepoints"] = int(worldstate_file.readline())
241         world_data["satiation"] = int(worldstate_file.readline())
242         world_data["inventory"] = []
243         while True:
244             line = worldstate_file.readline().replace("\n", "")
245             if line == '%':
246                 break
247             world_data["inventory"] += [line]
248         world_data["avatar_position"][0] = int(worldstate_file.readline())
249         world_data["avatar_position"][1] = int(worldstate_file.readline())
250         if not world_data["look_mode"]:
251             world_data["map_center"][0] = world_data["avatar_position"][0]
252             world_data["map_center"][1] = world_data["avatar_position"][1]
253         world_data["map_size"] = int(worldstate_file.readline())
254         world_data["fov_map"] = ""
255         for i in range(world_data["map_size"]):
256             line = worldstate_file.readline().replace("\n", "")
257             world_data["fov_map"] += line
258         world_data["mem_map"] = ""
259         for i in range(world_data["map_size"]):
260             line = worldstate_file.readline().replace("\n", "")
261             world_data["mem_map"] += line
262     worldstate_file.close()
263 read_worldstate.last_checked_mtime = -1
264
265
266 def read_message_queue():
267     while (len(message_queue["messages"]) > 1
268         or (len(message_queue["messages"]) == 1
269             and not message_queue["open_end"])):
270         message = message_queue["messages"].pop(0)
271         if message == "THINGS_HERE START":
272             read_message_queue.parse_thingshere = True
273             world_data["look"] = []
274         elif message == "THINGS_HERE END":
275             read_message_queue.parse_thingshere = False
276             if world_data["look"] == []:
277                 world_data["look"] = ["(none known)"]
278             cursed_main.redraw = True
279         elif read_message_queue.parse_thingshere:
280             world_data["look"] += [message]
281         elif message[0:4] == "LOG ":
282             world_data["log"] += [message[4:]]
283             cursed_main.redraw = True
284         elif message == "WORLD_UPDATED":
285             query_mapcell()
286 read_message_queue.parse_thingshere = False
287
288
289 def cursed_main(stdscr):
290
291     def ping_test():
292         half_wait_time = 5
293         if len(new_data_from_server) > 0:
294             ping_test.sent = False
295         elif ping_test.wait_start + half_wait_time < time.time():
296             if not ping_test.sent:
297                 io["file_out"].write("PING\n")
298                 io["file_out"].flush()
299                 ping_test.sent = True
300                 ping_test.wait_start = time.time()
301             elif ping_test.sent:
302                 raise SystemExit("Server not answering anymore.")
303     ping_test.wait_start = 0
304
305     def read_into_message_queue():
306         if new_data_from_server == "":
307             return
308         new_open_end = False
309         if new_data_from_server[-1] is not "\n":
310             new_open_end = True
311         new_messages = new_data_from_server.splitlines()
312         if message_queue["open_end"]:
313             message_queue["messages"][-1] += new_messages[0]
314             del new_messages[0]
315         message_queue["messages"] += new_messages
316         if new_open_end:
317             message_queue["open_end"] = True
318
319     curses.noecho()
320     curses.curs_set(False)
321     signal.signal(signal.SIGWINCH,
322         lambda ignore_1, ignore_2: set_window_geometries())
323     set_window_geometries()
324     delay = 1
325     while True:
326         stdscr.timeout(int(delay))
327         delay = delay * 1.1 if delay < 1000 else delay
328         if cursed_main.redraw:
329             delay = 1
330             draw_screen()
331             cursed_main.redraw = False
332         char = stdscr.getch()
333         if char >= 0:
334             char = chr(char)
335             if char in commands:
336                 if len(commands[char]) == 1 or not world_data["look_mode"]:
337                     commands[char][0]()
338                     cursed_main.redraw = True
339                 else:
340                     commands[char][1]()
341                     cursed_main.redraw = True
342         new_data_from_server = io["file_in"].read()
343         ping_test()
344         read_into_message_queue()
345         read_worldstate()
346         read_message_queue()
347
348
349 message_queue = {
350     "open_end": False,
351     "messages": []
352 }
353 sep_size = 1  # Width of inter-window borders and title bars.
354 stdscr = None
355 screen_size = [0,0]
356 windows = []
357
358 try:
359     if (not os.access(io["path_out"], os.F_OK)):
360         msg = "No server input file found at " + io["path_out"] + "."
361         raise SystemExit(msg)
362     io["file_out"] = open(io["path_out"], "a")
363     io["file_in"] = open(io["path_in"], "r")
364     curses.wrapper(cursed_main)
365 except SystemExit as exit:
366     print("ABORTING: " + exit.args[0])
367 except:
368     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
369     raise
370 finally:
371     if "file_out" in io:
372         io["file_out"].close()
373     if "file_in" in io:
374         io["file_in"].close()