Beispiel #1
0
class Description(Layer):
    """..."""

    bottom_color = (31, 15, 15)
    top_color = (0, 0, 0)

    def __init__(self, parent, rect):
        """..."""
        super().__init__(rect=rect)
        fname = os.path.join(dnf_path(), 'data', 'descriptions.bzp')
        self.db = packer.unpack_json(fname)
        # self.create_solid_surface(color=(31, 0, 63))
        self.create_text()

    def selection(self):
        return

    def create_text(self, group=None, key="character creation"):
        if group:
            text = self.db[group][key]
        else:
            text = self.db[key]

        try:
            old_text = self.sftext.text
        except AttributeError:
            old_text = None

        if old_text != text:
            manager = self.manager
            self.sftext = SFText(text=text,
                                 rect=self,
                                 fonts=manager.fonts,
                                 manager=manager)

    def on_update(self):
        """..."""
        super().on_update()
        self.sftext.on_update()

    def on_key_press(self, event, mod):
        """Called on keyboard input, when a key is held down."""
        self.sftext.on_key_press(event, mod)

    def on_mouse_scroll(self, event, offset_x, offset_y):
        """Called when the mouse wheel is scrolled."""
        self.sftext.on_mouse_scroll(event, offset_x, offset_y)
class LayerDescription(Layer):
    """..."""
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)

        self.content = ""

        self.db = self.parent.db

        self.create_text()

    def create_text(self, header_rect=None):
        """..."""
        try:
            tab = self.sftext.default_style['h'] * 2
        except AttributeError:
            tab = 6

        manager = self.manager

        y = header_rect.bottom + tab if header_rect else self.y
        self.y = y
        self.height = self.parent.height - self.y

        self.sftext = SFText(text=self.content,
                             rect=self,
                             fonts=manager.fonts,
                             manager=manager)

    def on_update(self):
        """..."""
        super().on_update()
        self.sftext.on_update()

    def on_key_press(self, event, mod):
        """Called on keyboard input, when a key is held down."""
        self.sftext.on_key_press(event, mod)

    def on_mouse_scroll(self, event, offset_x, offset_y):
        """Called when the mouse wheel is scrolled."""
        self.sftext.on_mouse_scroll(event, offset_x, offset_y)
class LayerNavigator(Layer):
    """..."""
    def __init__(self, tab_y=10, **kwargs):
        """..."""
        super().__init__(**kwargs)

        self.db = self.parent.db
        self.create_text("")

        self.abs_position = []
        self.key_index_historic = []
        self.current_level = dict(self.db)
        self.previous_level = dict(self.current_level)
        self.keys = sorted(list(self.current_level.keys()))
        self.current_key_index = 0

    def list(self):
        """..."""
        current_key = self.keys[self.current_key_index]
        current_item = self.current_level[current_key]

        document = ("{style}\\" * 2)
        for i in range(len(self.abs_position)):
            level = self.abs_position[i].capitalize()
            if i > 0:
                document += "\\"
            document += level

        str_keys = []
        for i, key in enumerate(self.keys):

            if isinstance(self.current_level[key], dict):
                s = "[{}]".format(key.capitalize())
            else:
                s = key.capitalize()

            if key == current_key:
                s = "{style}{underline True}" + YELLOW + s.upper() + "{style}"

            str_keys.append(s)

        document += "\n[ {} ]".format(", ".join(s for s in str_keys))

        self.create_text(document)

        if isinstance(current_item, dict):
            self.parent.desc_layer.content = self.db['Help']
        else:
            self.parent.desc_layer.content = current_item
        # self.height = self.sftext.sum_height()
        # self.y = 0
        header_rect = Rect(self)
        header_rect.y = 0
        header_rect.height = self.sftext.sum_height()
        self.parent.desc_layer.create_text(header_rect=header_rect)

    def create_text(self, text):
        """..."""
        manager = self.manager
        nav_style = "{size 18}" + WHITE
        self.sftext = SFText(text=text,
                             style=nav_style,
                             rect=self,
                             fonts=manager.fonts,
                             manager=manager)

    def previous_item(self):
        """..."""
        self.current_key_index -= 1
        self.current_key_index = self.current_key_index % len(self.keys)
        self.list()

    def next_item(self):
        """..."""
        self.current_key_index += 1
        self.current_key_index = self.current_key_index % len(self.keys)
        self.list()

    def go_down(self):
        """..."""
        current_item = self.current_level[self.keys[self.current_key_index]]
        if isinstance(current_item, dict):
            current_key = self.keys[self.current_key_index]
            self.abs_position.append(current_key)

            self.previous_level = dict(self.current_level)
            self.current_level = dict(self.current_level[current_key])
            self.keys = sorted(list(self.current_level.keys()))

            self.key_index_historic.append(self.current_key_index)
            self.current_key_index = 0
            self.list()

    def go_up(self):
        """..."""
        if len(self.abs_position) > 0:
            self.abs_position.pop()
            self.current_key_index = self.key_index_historic.pop()

            self.current_level = self.fetch_previous()
            self.keys = sorted(list(self.current_level.keys()))

            self.list()

    def fetch_previous(self):
        """..."""
        previous = dict(self.db)
        abs_path = list(self.abs_position)
        for key in abs_path:
            previous = dict(previous[abs_path.pop(0)])
        return previous

    def on_update(self):
        """..."""
        super().on_update()
        self.sftext.on_update()

    def on_key_press(self, event, mod):
        """super__doc__."""
        sym = event.key.keysym.sym
        if sym == sdl2.SDLK_LEFT:
            self.previous_item()
        elif sym == sdl2.SDLK_RIGHT:
            self.next_item()
        elif sym == sdl2.SDLK_BACKSPACE:
            self.go_up()
        elif sym == sdl2.SDLK_RETURN:
            self.go_down()
        else:
            if 97 <= sym <= 122:
                self.search(chr(sym))

    def search(self, _s):
        """Search for a key that matches the imput."""
        def set_i(i):
            self.current_key_index = i
            self.list()

        s = _s.lower()
        matches = []
        for i in range(len(self.keys)):
            if self.keys[i][0].lower() == s:
                matches.append(i)

        if not matches:
            return
        elif len(matches) == 1:
            set_i(matches[0])
        elif self.current_key_index in matches:
            cur_i = matches.index(self.current_key_index)
            j = (cur_i + 1) % len(matches)
            set_i(matches[j])
        else:
            set_i(matches[0])
Beispiel #4
0
class Stats(Layer):
    """..."""
    bottom_color = (15, 15, 31)
    top_color = (0, 0, 0)

    def __init__(self, parent, rect):
        """..."""
        super().__init__(rect=rect)
        self.character = creatures.Character()
        self.create_structure()
        self.create_text()

    def create_structure(self):
        """..."""
        self.selection = 0

        self.att_names = char_roll.att_names
        self.fields = [
            'name', 'gender', 'race', 'class', 'alignment', 'age', 'height',
            'weight'
        ]
        self.fields.extend(self.att_names)

    def change_selection(self, value):
        """..."""
        selection = self.selection + value
        selection = selection % len(self.fields)
        self.selection = selection
        self.create_text()
        # print(self.fields[selection])

        if selection > 7:
            group = 'stats'
            key = self.fields[selection]
        elif selection == 2:
            group = 'races'
            key = self.character.race
        elif selection == 3:
            group = 'classes'
            key = self.character._class
        elif selection == 4:
            group = 'alignment'
            key = '*'
        else:
            self.desc_layer.create_text()
            return

        self.desc_layer.create_text(group=group, key=key)

    def change_value(self, v):
        """Handle the change if the player attemp to modify a field.

        Age, Height and Weight can't be changed.
        """
        selection = self.selection

        if selection == 0:
            self.character.change_name()
        elif selection == 1:
            self.character.change_gender()
            self.character.change_height_weight()
        elif selection == 2:
            self.character.change_race(v)
        elif selection == 3:
            self.character.change_class(v)
        elif selection == 4:
            self.character.change_alignment(v)
        elif selection > 7:
            self.change_stats(v)
        else:
            return

        self.create_text()
        self.change_selection(0)

    def change_stats(self, v):
        """Swap attributes."""
        i0 = (self.selection - 8) % 6
        i1 = (self.selection + v - 8) % 6
        att = self.character._base_att
        att[i0], att[i1] = att[i1], att[i0]

    @property
    def desc_layer(self):
        return self.parent.desc_layer

    @property
    def available_alignments(self):
        return char_roll.alignments[self.character._class]

    @property
    def available_classes(self):
        return sorted(self.character.classes)

    @property
    def current_alignment_i(self):
        return self.available_alignments.index(self.character.alignment)

    @property
    def current_class_i(self):
        return self.available_classes.index(self.character._class)

    def create_text(self):
        """..."""
        def fancy_field(string):
            return string[:1].upper() + string[1:]

        def name():
            if self.selection == 0:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Name:" + ul + c + "{style}" +
                    " {}".format(self.character.name) + "\n\n")

        def gender():
            if self.selection == 1:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Gender:" + ul + c + "{style}" +
                    " {}".format(fancy_field(self.character.gender)) + "\n\n")

        def race():
            if self.selection == 2:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Race:" + ul + c + "{style}" +
                    " {}".format(fancy_field(self.character.race)) + "\n\n")

        def _class():
            if self.selection == 3:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Class:" + ul + c + "{style}" +
                    " {}".format(fancy_field(self.character._class)) + "\n\n")

        def alignment():
            if self.selection == 4:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Alignment:" + ul + c + "{style}" +
                    " {}".format(self.character.alignment) + "\n\n")

        def age():
            if self.selection == 5:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Age:" + ul + c + "{style}" +
                    " {}".format(str(self.character.age)) + "\n\n")

        def height():
            if self.selection == 6:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Height:" + ul + c + "{style}" +
                    " {:.2f}".format(self.character.height, 2) + 'm.' + "\n\n")

        def weight():
            if self.selection == 7:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""
            return ("Weight:" + ul + c + "{style}" +
                    " {:.2f}".format(self.character.weight, 2) + 'kg.' +
                    "\n\n")

        def att(i):
            character = self.character
            if self.selection == 8 + i:
                ul = "{underline True}"
                c = "{color (255, 255, 0)}"
            else:
                ul = ""
                c = ""

            v = self.character.attributes[i]
            if v > 11:
                c2 = "{color (0, 255, 0)}"
            elif v < 10:
                c2 = "{color (255, 0, 0)}"
            else:
                c2 = ""
            bonus = ""
            if character.race_mod[i]:
                if character.race_mod[i] > 0:
                    bonus = "+{}={}".format(character.race_mod[i], v)
                else:
                    bonus = "{}={}".format(character.race_mod[i], v)

            return ("{}:".format(fancy_field(self.att_names[i])) + ul + c +
                    "{style}" + " {}{}".format(character._base_att[i], bonus) +
                    c2 + "\n\n")

        mystyle = {'size': 18, 'color': (223, 223, 255)}

        text = ''.join([
            t for t in [
                "\n",
                name(),
                gender(),
                race(),
                _class(),
                alignment(),
                age(),
                height(),
                weight(), ''.join([att(i) for i in range(len(self.att_names))])
            ]
        ])
        manager = self.manager

        self.sftext = SFText(text=text,
                             style=mystyle,
                             rect=self,
                             fonts=manager.fonts,
                             manager=manager)

    def on_update(self):
        """..."""
        super().on_update()
        self.sftext.on_update()

    def post_update(self):
        """..."""
        # self.sftext.post_update()
        pass

    def on_key_press(self, event, mod):
        """Called on keyboard input, when a key is held down."""
        sym = event.key.keysym.sym
        if sym == sdl2.SDLK_UP:
            self.change_selection(-1)
            return
        elif sym == sdl2.SDLK_DOWN:
            self.change_selection(+1)
            return
        elif sym == sdl2.SDLK_LEFT:
            self.change_value(-1)
            return
        elif sym == sdl2.SDLK_RIGHT:
            self.change_value(+1)
            return
        elif sym == sdl2.SDLK_F2:
            self.character = creatures.Character()

        if self.selection is 0:
            if sym == sdl2.SDLK_BACKSPACE:
                self.character.name = self.character.name[:-1]
            elif 97 <= sym <= 122:
                input_text = get_mod_case(event)
                self.character.name += input_text

        self.create_text()
        self.change_selection(0)