home · contact · privacy
1fd3061a23b62bc468b14a702d9a0188835f9318
[plomrogue] / client_prototype.py
1 import curses
2 import math
3 import os
4 import signal
5 import time
6
7
8 def set_window_geometries():
9
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]
22
23     def place_window():
24         win_i = windows.index(win)
25
26         # If win is first window, it goes into the top left corner.
27         win["start"][0] = 0 + sep_size
28         win["start"][1] = 0
29         if (win_i > 0):
30
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.
33             win_top = None
34             for i in range(win_i - 1, -1, -1):
35                 win_top = windows[i]
36                 if (win_top["start"][0] == 0 + sep_size):
37                     break
38             win["start"][1] = win_top["start"][1] + win_top["size"][1] \
39                 + sep_size
40
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
49
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).
56             else:
57                 win_test = win_prev
58                 win_high = None
59                 while (win_test != win_top):
60                     for i in range(win_i - 2, -1, -1):
61                         win_high = windows[i]
62                         if win_test["start"][0] > win_high["start"][0]:
63                             break
64                     next_free_y = win_high["start"][0] + win_high["size"][0] \
65                         + sep_size
66                     first_free_x = win_test["start"][1] + win_test["size"][1] \
67                         + sep_size
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
73                         break
74                     win_test = win_high
75
76     global screen_size, stdscr
77     curses.endwin()
78     stdscr = curses.initscr()
79     screen_size = stdscr.getmaxyx()
80     for win in windows:
81         set_window_size()
82         place_window()
83     cursed_main.redraw = True
84
85
86 def draw_screen():
87
88     def healthy_addch(y, x, char, attr=0):
89     """Bizarre 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)
95         else:
96             stdscr.addch(y, x, char, attr)
97
98     def draw_window_border_lines():
99         for win in windows:
100             for k in range(2):
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]
107                     if k:
108                         [healthy_addch(j, i, '-') for i in range(start, end)]
109                     else:
110                         [healthy_addch(i, j, '|') for i in range(start, end)]
111
112     def draw_window_border_corners():
113         for win in windows:
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, '+')
128
129     def draw_window_contents():
130         def draw_winmap():
131             stop = [0, 0]
132             for i in range(2):
133                 stop[i] = win["size"][i] + offset[i]
134                 if stop[i] >= winmap_size[i]:
135                     stop[i] = winmap_size[i]
136             for y in range(offset[0], stop[0]):
137                 for x in range(offset[1], stop[1]):
138                     cell = winmap[y * winmap_size[1] + x]
139                     y_in_screen = win["start"][0] + (y - offset[0])
140                     x_in_screen = win["start"][1] + (x - offset[1])
141                     if (y_in_screen < screen_size[0]
142                             and x_in_screen < screen_size[1]):
143                         healthy_addch(y_in_screen, x_in_screen, cell)
144         def draw_scroll_hints():
145             def draw_scroll_string(n_lines_outside):
146                 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
147                 if len(hint) <= win["size"][ni]:
148                     non_hint_space = win["size"][ni] - len(hint)
149                     hint_offset = int(non_hint_space / 2)
150                     for j in range(win["size"][ni] - non_hint_space):
151                         pos_2 = win["start"][ni] + hint_offset + j
152                         x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
153                         healthy_addch(y, x, hint[j], curses.A_REVERSE)
154             def draw_scroll_arrows(ar1, ar2):
155                 for j in range(win["size"][ni]):
156                     pos_2 = win["start"][ni] + j
157                     x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
158                     healthy_addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
159             for i in range(2):
160                 ni = int(i == 0)
161                 unit = 'rows' if ni else 'columns'
162                 if (offset[i] > 0):
163                     pos_1 = win["start"][i]
164                     draw_scroll_arrows('^', '<')
165                     draw_scroll_string(offset[i])
166                 if (winmap_size[i] > offset[i] + win["size"][i]):
167                     pos_1 = win["start"][i] + win["size"][i] - 1
168                     draw_scroll_arrows('v', '>')
169                     draw_scroll_string(winmap_size[i] - offset[i]
170                         - win["size"][i])
171         for win in windows:
172             offset, winmap_size, winmap = win["func"]()
173             draw_winmap()
174             draw_scroll_hints()
175
176     stdscr.clear()
177     draw_window_border_lines()
178     draw_window_border_corners()
179     draw_window_contents()
180     stdscr.refresh()
181
182
183 def read_worldstate():
184     if not os.access(io["path_worldstate"], os.F_OK):
185         msg = "No world state file found at " + io["path_worldstate"] + "."
186         raise SystemExit(msg)
187     read_anew = False
188     worldstate_file = open(io["path_worldstate"], "r")
189     turn_string = worldstate_file.readline()
190     if int(turn_string) != world_data["turn"]:
191         read_anew = True
192     if not read_anew: # In rare cases, world may change, but not turn number.
193         mtime = os.stat(io["path_worldstate"])
194         if mtime != read_worldstate.last_checked_mtime:
195             read_worldstate.last_checked_mtime = mtime
196             read_anew = True
197     if read_anew:
198         cursed_main.redraw = True
199         world_data["turn"] = int(turn_string)
200         world_data["lifepoints"] = int(worldstate_file.readline())
201         world_data["satiation"] = int(worldstate_file.readline())
202         world_data["inventory"] = []
203         while True:
204             line = worldstate_file.readline().replace("\n", "")
205             if line == '%':
206                 break
207             world_data["inventory"] += [line]
208         world_data["position"][0] = int(worldstate_file.readline())
209         world_data["position"][1] = int(worldstate_file.readline())
210         world_data["map_size"] = int(worldstate_file.readline())
211     worldstate_file.close()
212 read_worldstate.last_checked_mtime = -1
213
214
215 def read_message_queue():
216     while (len(message_queue["messages"]) > 1
217         or (len(message_queue["messages"]) == 0
218             and not message_queue["open_end"])):
219         message = message_queue["messages"].pop(0)
220         if message[0:4] == "LOG ":
221             world_data["log"] += [message[4:]]
222             cursed_main.redraw = True
223
224
225 def cursed_main(stdscr):
226
227     def ping_test():
228         half_wait_time = 5
229         if len(new_data_from_server) > 0:
230             ping_test.sent = False
231         elif ping_test.wait_start + half_wait_time < time.time():
232             if not ping_test.sent:
233                 io["file_out"].write("PING\n")
234                 io["file_out"].flush()
235                 ping_test.sent = True
236                 ping_test.wait_start = time.time()
237             elif ping_test.sent:
238                 raise SystemExit("Server not answering anymore.")
239     ping_test.wait_start = 0
240
241     def read_into_message_queue():
242         if new_data_from_server == "":
243             return
244         new_open_end = False
245         if new_data_from_server[-1] is not "\n":
246             new_open_end = True
247         new_messages = new_data_from_server.splitlines()
248         if message_queue["open_end"]:
249             message_queue["messages"][-1] += new_messages[0]
250             del new_messages[0]
251         message_queue["messages"] += new_messages
252         if new_open_end:
253             message_queue["open_end"] = True
254
255     curses.noecho()
256     curses.curs_set(False)
257     # stdscr.keypad(True)
258     signal.signal(signal.SIGWINCH,
259         lambda ignore_1, ignore_2: set_window_geometries())
260     set_window_geometries()
261     delay = 1
262     while True:
263         stdscr.timeout(delay)
264         delay = delay * 2 if delay < 1000 else delay
265         if cursed_main.redraw:
266             delay = 1
267             draw_screen()
268             cursed_main.redraw = False
269         char = stdscr.getch()
270         if char >= 0 and chr(char) in commands:
271             commands[chr(char)]()
272             cursed_main.redraw = True
273         new_data_from_server = io["file_in"].read()
274         ping_test()
275         read_into_message_queue()
276         read_worldstate()
277         read_message_queue()
278
279
280 def win_foo():
281     winmap = ['.', 'o', '.', 'o', 'O', 'o', '.', 'o', '.', 'x', 'y', 'x']
282     winmap_size = [4, 3]
283     offset = [0, 0]
284     return offset, winmap_size, winmap
285
286
287 def win_inventory():
288     winmap = ""
289     winmap_size = [0, 0]
290     for line in world_data["inventory"]:
291         winmap_size[1] = winmap_size[1] if len(line) <= winmap_size[1] \
292             else len(line)
293     for line in world_data["inventory"]:
294         padding_size = winmap_size[1] - len(line)
295         winmap += line + (" " * padding_size)
296         winmap_size[0] = winmap_size[0] + 1
297     offset = [0, 0]
298     return offset, winmap_size, winmap
299
300
301 def win_info():
302     winmap = "T: " + str(world_data["turn"]) \
303         + " H: " + str(world_data["lifepoints"]) \
304         + " S: " + str(world_data["satiation"])
305     winmap_size = [1, len(winmap)]
306     offset = [0, 0]
307     return offset, winmap_size, winmap
308
309
310 def win_log():
311     win_size = next(win["size"] for win in windows if win["func"] == win_log)
312     offset = [0, 0]
313     winmap = ""
314     number_of_lines = 0
315     for line in world_data["log"]:
316         number_of_lines += math.ceil(len(line) / win_size[1])
317         padding_size = win_size[1] - (len(line) % win_size[1])
318         winmap += line + (padding_size * " ")
319     if number_of_lines < win_size[0]:
320         winmap = (" " * win_size[1] * (win_size[0] - number_of_lines)) + winmap
321         number_of_lines = win_size[0]
322     elif number_of_lines > win_size[0]:
323         offset[0] = number_of_lines - win_size[0]
324     winmap_size = [number_of_lines, win_size[1]]
325     return offset, winmap_size, winmap
326
327
328 def command_quit():
329     io["file_out"].write("QUIT\n")
330     io["file_out"].flush()
331     raise SystemExit("Received QUIT command, forwarded to server, leaving.")
332
333
334 windows = [
335     {"config": [1, 33], "func": win_info},
336     {"config": [-7, 33], "func": win_log},
337     {"config": [4, 16], "func": win_inventory},
338     {"config": [4, 16], "func": win_foo},
339     {"config": [0, -34], "func": win_foo}
340 ]
341 io = {
342     "path_out": "server/in",
343     "path_in": "server/out",
344     "path_worldstate": "server/worldstate"
345 }
346 commands = {
347     "Q": command_quit
348 }
349 message_queue = {
350     "open_end": False,
351     "messages": []
352 }
353 world_data = {
354     "inventory": [],
355     "lifepoints": -1,
356     "log": [],
357     "map_size": -1,
358     "position": [-1, -1],
359     "satiation": -1,
360     "turn": -1
361 }
362 sep_size = 1  # Width of inter-window borders and title bars.
363 stdscr = None
364 screen_size = [0,0]
365
366
367 try:
368     if (not os.access(io["path_out"], os.F_OK)):
369         msg = "No server input file found at " + io["path_out"] + "."
370         raise SystemExit(msg)
371     io["file_out"] = open(io["path_out"], "a")
372     io["file_in"] = open(io["path_in"], "r")
373     curses.wrapper(cursed_main)
374 except SystemExit as exit:
375     print("ABORTING: " + exit.args[0])
376 except:
377     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
378     raise
379 finally:
380     if "file_out" in io:
381         io["file_out"].close()
382     if "file_in" in io:
383         io["file_in"].close()