X-Git-Url: https://plomlompom.com/repos/foo.html?a=blobdiff_plain;f=client-curses.py;h=f65d3a0e242c022e1266a3d97c6a27526eaa6532;hb=3d0f035d4a276fd53b767e2be8b481a678a7360b;hp=a18d8af59a8435fa2a9b553a55a0874192ee1ecb;hpb=05aae1b6380c5bea2d69ee001f64f93dbff2b0c1;p=plomrogue2-experiments
diff --git a/client-curses.py b/client-curses.py
index a18d8af..f65d3a0 100755
--- a/client-curses.py
+++ b/client-curses.py
@@ -1,44 +1,83 @@
#!/usr/bin/env python3
import curses
-import plom_socket_io
+import plom_socket
import socket
import threading
from parser import ArgError, Parser
import game_common
-class MapSquare(game_common.Map):
+class Map(game_common.Map):
- def list_terrain_to_lines(self, terrain_as_list):
- terrain = ''.join(terrain_as_list)
- map_lines = []
- start_cut = 0
- while start_cut < len(terrain):
- limit = start_cut + self.size[1]
- map_lines += [terrain[start_cut:limit]]
- start_cut = limit
- return map_lines
+ def y_cut(self, map_lines, center_y, view_height):
+ map_height = len(map_lines)
+ if map_height > view_height and center_y > view_height / 2:
+ if center_y > map_height - view_height / 2:
+ map_lines[:] = map_lines[map_height - view_height:]
+ else:
+ start = center_y - int(view_height / 2) - 1
+ map_lines[:] = map_lines[start:start + view_height]
+
+ def x_cut(self, map_lines, center_x, view_width, map_width):
+ if map_width > view_width and center_x > view_width / 2:
+ if center_x > map_width - view_width / 2:
+ cut_start = map_width - view_width
+ cut_end = None
+ else:
+ cut_start = center_x - int(view_width / 2)
+ cut_end = cut_start + view_width
+ map_lines[:] = [line[cut_start:cut_end] for line in map_lines]
+
+
+class MapSquare(Map):
+ def format_to_view(self, map_string, center, size):
-class MapHex(game_common.Map):
+ def map_string_to_lines(map_string):
+ map_lines = []
+ start_cut = 0
+ while start_cut < len(map_string):
+ limit = start_cut + self.size[1]
+ map_lines += [map_string[start_cut:limit]]
+ start_cut = limit
+ return map_lines
- def list_terrain_to_lines(self, terrain_as_list):
- new_terrain_list = [' ']
- x = 0
- y = 0
- for c in terrain_as_list:
- new_terrain_list += [c, ' ']
- x += 1
- if x == self.size[1]:
- new_terrain_list += ['\n']
- x = 0
- y += 1
- if y % 2 == 0:
- new_terrain_list += [' ']
- return ''.join(new_terrain_list).split('\n')
+ map_lines = map_string_to_lines(map_string)
+ self.y_cut(map_lines, center[0], size[0])
+ self.x_cut(map_lines, center[1], size[1], self.size[1])
+ return map_lines
+
+
+class MapHex(Map):
+
+ def format_to_view(self, map_string, center, size):
+
+ def map_string_to_lines(map_string):
+ map_view_chars = ['0']
+ x = 0
+ y = 0
+ for c in map_string:
+ map_view_chars += [c, ' ']
+ x += 1
+ if x == self.size[1]:
+ map_view_chars += ['\n']
+ x = 0
+ y += 1
+ if y % 2 == 0:
+ map_view_chars += ['0']
+ if y % 2 == 0:
+ map_view_chars = map_view_chars[:-1]
+ map_view_chars = map_view_chars[:-1]
+ return ''.join(map_view_chars).split('\n')
+
+ map_lines = map_string_to_lines(map_string)
+ self.y_cut(map_lines, center[0], size[0])
+ map_width = self.size[1] * 2 + 1
+ self.x_cut(map_lines, center[1] * 2, size[1], map_width)
+ return map_lines
-map_manager = game_common.MapManager(globals())
+map_manager = game_common.MapManager((MapHex, MapSquare))
class World(game_common.World):
@@ -52,6 +91,7 @@ class World(game_common.World):
super().__init__(*args, **kwargs)
self.game = game
self.map_ = self.game.map_manager.get_map_class('Hex')()
+ self.player_position = (0, 0)
class Game(game_common.CommonCommandsMixin):
@@ -61,10 +101,47 @@ class Game(game_common.CommonCommandsMixin):
self.parser = Parser(self)
self.world = World(self)
self.log_text = ''
+ self.to_update = {
+ 'log': True,
+ 'map': True,
+ 'turn': True,
+ }
+ self.do_quit = False
+
+ def get_command_signature(self, command_name):
+ method_candidate = 'cmd_' + command_name
+ method = None
+ argtypes = ''
+ if hasattr(self, method_candidate):
+ method = getattr(self, method_candidate)
+ if hasattr(method, 'argtypes'):
+ argtypes = method.argtypes
+ return method, argtypes
+
+ def get_string_options(self, string_option_type):
+ if string_option_type == 'geometry':
+ return self.map_manager.get_map_geometries()
+ return None
+
+ def handle_input(self, msg):
+ if msg == 'BYE':
+ self.do_quit = True
+ return
+ try:
+ command, args = self.parser.parse(msg)
+ if command is None:
+ self.log('UNHANDLED INPUT: ' + msg)
+ self.to_update['log'] = True
+ else:
+ command(*args)
+ except ArgError as e:
+ self.log('ARGUMENT ERROR: ' + msg + '\n' + str(e))
+ self.to_update['log'] = True
def log(self, msg):
"""Prefix msg plus newline to self.log_text."""
self.log_text = msg + '\n' + self.log_text
+ self.to_update['log'] = True
def symbol_for_type(self, type_):
symbol = '?'
@@ -84,37 +161,47 @@ class Game(game_common.CommonCommandsMixin):
pass
cmd_TURN_FINISHED.argtypes = 'int:nonneg'
- def cmd_NEW_TURN(self, n):
+ def cmd_TURN(self, n):
"""Set self.turn to n, empty self.things."""
self.world.turn = n
self.world.things = []
- cmd_NEW_TURN.argtypes = 'int:nonneg'
+ self.to_update['turn'] = False
+ self.to_update['map'] = False
+ cmd_TURN.argtypes = 'int:nonneg'
def cmd_VISIBLE_MAP_LINE(self, y, terrain_line):
self.world.map_.set_line(y, terrain_line)
cmd_VISIBLE_MAP_LINE.argtypes = 'int:nonneg string'
+ def cmd_PLAYER_POS(self, yx):
+ self.world.player_position = yx
+ cmd_PLAYER_POS.argtypes = 'yx_tuple:pos'
+
+ def cmd_GAME_STATE_COMPLETE(self):
+ self.to_update['turn'] = True
+ self.to_update['map'] = True
+
ASCII_printable = ' !"#$%&\'\(\)*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWX'\
'YZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~'
-def recv_loop(server_output):
- for msg in plom_socket_io.recv(s):
- while len(server_output) > 0:
- pass
- server_output += [msg]
+def recv_loop(plom_socket, game):
+ for msg in plom_socket.recv():
+ game.handle_input(msg)
class Widget:
- def __init__(self, tui, start, size):
+ def __init__(self, tui, start, size, check_game=[], check_tui=[]):
+ self.check_game = check_game
+ self.check_tui = check_tui
self.tui = tui
self.start = start
self.win = curses.newwin(1, 1, self.start[0], self.start[1])
self.size_def = size # store for re-calling .size on SIGWINCH
self.size = size
- self.update = True
+ self.do_update = True
@property
def size(self):
@@ -142,10 +229,7 @@ class Widget:
part_string = part[0]
attr = part[1]
if len(part_string) > 0:
- chars_with_attrs = []
- for char in part_string:
- chars_with_attrs += [(char, attr)]
- return chars_with_attrs
+ return [(char, attr) for char in part_string]
elif len(part_string) == 1:
return [part]
return []
@@ -170,10 +254,21 @@ class Widget:
for char_with_attr in cut:
self.win.addstr(char_with_attr[0], char_with_attr[1])
- def draw_and_refresh(self):
- self.win.erase()
- self.draw()
- self.win.refresh()
+ def ensure_freshness(self, do_refresh=False):
+ if not do_refresh:
+ for key in self.check_game:
+ if self.tui.game.to_update[key]:
+ do_refresh = True
+ break
+ if not do_refresh:
+ for key in self.check_tui:
+ if self.tui.to_update[key]:
+ do_refresh = True
+ break
+ if do_refresh:
+ self.win.erase()
+ self.draw()
+ self.win.refresh()
class EditWidget(Widget):
@@ -199,36 +294,55 @@ class LogWidget(Widget):
class MapWidget(Widget):
def draw(self):
- to_join = []
- if len(self.tui.game.world.map_.terrain) > 0:
+
+ def terrain_with_objects():
terrain_as_list = list(self.tui.game.world.map_.terrain[:])
for t in self.tui.game.world.things:
pos_i = self.tui.game.world.map_.get_position_index(t.position)
terrain_as_list[pos_i] = self.tui.game.symbol_for_type(t.type_)
- lines = self.tui.game.world.map_.list_terrain_to_lines(terrain_as_list)
+ return ''.join(terrain_as_list)
+
+ def pad_or_cut_x(lines):
line_width = self.size[1]
- for line in lines:
+ for y in range(len(lines)):
+ line = lines[y]
if line_width > len(line):
to_pad = line_width - (len(line) % line_width)
- to_join += [line + '0' * to_pad]
+ lines[y] = line + '0' * to_pad
else:
- to_join += [line[:line_width]]
- if len(to_join) < self.size[0]:
- to_pad = self.size[0] - len(to_join)
- to_join += to_pad * ['0' * self.size[1]]
- text = ''.join(to_join)
- text_as_list = []
- for c in text:
- if c in {'@', 'm'}:
- text_as_list += [(c, curses.color_pair(1))]
- elif c == '.':
- text_as_list += [(c, curses.color_pair(2))]
- elif c in {'x', 'X', '#'}:
- text_as_list += [(c, curses.color_pair(3))]
- else:
- text_as_list += [c]
- #self.safe_write(''.join(to_join))
- self.safe_write(text_as_list)
+ lines[y] = line[:line_width]
+
+ def pad_y(lines):
+ if len(lines) < self.size[0]:
+ to_pad = self.size[0] - len(lines)
+ lines += to_pad * ['0' * self.size[1]]
+
+ def lines_to_colored_chars(lines):
+ chars_with_attrs = []
+ for c in ''.join(lines):
+ if c in {'@', 'm'}:
+ chars_with_attrs += [(c, curses.color_pair(1))]
+ elif c == '.':
+ chars_with_attrs += [(c, curses.color_pair(2))]
+ elif c in {'x', 'X', '#'}:
+ chars_with_attrs += [(c, curses.color_pair(3))]
+ else:
+ chars_with_attrs += [c]
+ return chars_with_attrs
+
+ if self.tui.game.world.map_.terrain == '':
+ lines = []
+ pad_y(lines)
+ self.safe_write(''.join(lines))
+ return
+
+ terrain_with_objects = terrain_with_objects()
+ center = self.tui.game.world.player_position
+ lines = self.tui.game.world.map_.format_to_view(terrain_with_objects,
+ center, self.size)
+ pad_or_cut_x(lines)
+ pad_y(lines)
+ self.safe_write(lines_to_colored_chars(lines))
class TurnWidget(Widget):
@@ -239,10 +353,11 @@ class TurnWidget(Widget):
class TUI:
- def __init__(self, server_output):
- self.server_output = server_output
- self.game = Game()
+ def __init__(self, plom_socket, game):
+ self.socket = plom_socket
+ self.game = game
self.parser = Parser(self.game)
+ self.to_update = {'edit': False}
curses.wrapper(self.loop)
def setup_screen(self, stdscr):
@@ -259,61 +374,73 @@ class TUI:
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLUE)
curses.curs_set(False) # hide cursor
self.to_send = []
- edit_line = EditWidget(self, (0, 6), (1, 14))
- turn_line = TurnWidget(self, (2, 6), (1, 14))
- log_display = LogWidget(self, (4, 0), (None, 20))
- map_view = MapWidget(self, (0, 21), (None, None))
- map_view.update = True
- widgets = [edit_line, turn_line, log_display, map_view]
- do_update = True
+ self.edit = EditWidget(self, (0, 6), (1, 14), check_tui = ['edit'])
+ self.turn = TurnWidget(self, (2, 6), (1, 14), ['turn'])
+ self.log = LogWidget(self, (4, 0), (None, 20), ['log'])
+ self.map_ = MapWidget(self, (0, 21), (None, None), ['map'])
+ widgets = (self.edit, self.turn, self.log, self.map_)
+ map_mode = False
while True:
- if do_update:
- for w in widgets:
- w.draw_and_refresh()
- do_update = False
+ for w in widgets:
+ w.ensure_freshness()
+ for key in self.game.to_update:
+ self.game.to_update[key] = False
+ for key in self.to_update:
+ self.to_update[key] = False
try:
key = self.stdscr.getkey()
- do_update = True
- if len(key) == 1 and key in ASCII_printable and \
- len(self.to_send) < len(edit_line):
- self.to_send += [key]
- elif key == 'KEY_BACKSPACE':
- self.to_send[:] = self.to_send[:-1]
- elif key == '\n':
- plom_socket_io.send(s, ''.join(self.to_send))
- self.to_send[:] = []
- elif key == 'KEY_RESIZE':
+ if key == 'KEY_RESIZE':
curses.endwin()
self.setup_screen(curses.initscr())
for w in widgets:
w.size = w.size_def
+ w.ensure_freshness(True)
+ elif key == '\t': # Tabulator key.
+ map_mode = False if map_mode else True
+ elif map_mode:
+ if type(self.game.world.map_) == MapSquare:
+ if key == 'a':
+ self.socket.send('TASK:MOVE LEFT')
+ elif key == 'd':
+ self.socket.send('TASK:MOVE RIGHT')
+ elif key == 'w':
+ self.socket.send('TASK:MOVE UP')
+ elif key == 's':
+ self.socket.send('TASK:MOVE DOWN')
+ elif type(self.game.world.map_) == MapHex:
+ if key == 'w':
+ self.socket.send('TASK:MOVE UPLEFT')
+ elif key == 'e':
+ self.socket.send('TASK:MOVE UPRIGHT')
+ if key == 's':
+ self.socket.send('TASK:MOVE LEFT')
+ elif key == 'd':
+ self.socket.send('TASK:MOVE RIGHT')
+ if key == 'x':
+ self.socket.send('TASK:MOVE DOWNLEFT')
+ elif key == 'c':
+ self.socket.send('TASK:MOVE DOWNRIGHT')
else:
- do_update = False
+ if len(key) == 1 and key in ASCII_printable and \
+ len(self.to_send) < len(self.edit):
+ self.to_send += [key]
+ self.to_update['edit'] = True
+ elif key == 'KEY_BACKSPACE':
+ self.to_send[:] = self.to_send[:-1]
+ self.to_update['edit'] = True
+ elif key == '\n': # Return key
+ self.socket.send(''.join(self.to_send))
+ self.to_send[:] = []
+ self.to_update['edit'] = True
except curses.error:
pass
- if len(self.server_output) > 0:
- do_quit = self.handle_input(self.server_output[0])
- if do_quit:
- break
- self.server_output[:] = []
- do_update = True
-
- def handle_input(self, msg):
- if msg == 'BYE':
- return True
- try:
- command = self.parser.parse(msg)
- if command is None:
- self.game.log('UNHANDLED INPUT: ' + msg)
- else:
- command()
- except ArgError as e:
- self.game.log('ARGUMENT ERROR: ' + msg + '\n' + str(e))
- return False
+ if self.game.do_quit:
+ break
-server_output = []
s = socket.create_connection(('127.0.0.1', 5000))
-t = threading.Thread(target=recv_loop, args=(server_output,))
+plom_socket = plom_socket.PlomSocket(s)
+game = Game()
+t = threading.Thread(target=recv_loop, args=(plom_socket, game))
t.start()
-TUI(server_output)
+TUI(plom_socket, game)