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