summaryrefslogtreecommitdiff
path: root/menu.py
blob: 84e522c2687b6e1ffdfb6e22dbf5e60fc39c81c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import re

from font import Font
from game import Game, GameSprite
from sprite import Sprite


class MenuItem(GameSprite):
    """A selectable item in a menu"""

    def __init__(self, game: Game, text, callback):
        """Initialise the item

        :param game: The game which this belongs to
        :type game: Game
        :param text: Text to display for this item
        :param callback: function to call when this item is selected
        """
        image = Font.load_text(game.texture_factory, text)
        self.text = text
        self.callback = callback
        super().__init__(game, image)

    def set_text(self, text):
        """Update the text of an entry

        :param text:
        """
        self.text = text
        image = Font.load_text(self.game.texture_factory, text)
        self.set_image(image)


class Menu():
    """Menu object with selectable entries"""

    def __init__(self, game: Game, title) -> None:
        """Initialise the menu object

        :param game: The game which this belongs to
        :type game: Game
        :param title: The title of this menu
        """
        self.game = game
        self.title = title
        self.padding = 5

        self.game.inputs.add_keypress_handler(self.on_key)

        self.menu_items = []

        self.selection = 0

        carret_image = Font.load_text(game.texture_factory, ">")
        self.carret = GameSprite(self.game, carret_image)

        title_image = Font.load_text(game.texture_factory, title)

        position = ((self.game.w - len(title)*Font.FONT_WIDTH)//2, 5*2)
        self.title = GameSprite(self.game, title_image)
        self.title.set_pos(position)

        self.hidden = True

        self.alpha = 0

    def on_key(self, _):
        """Handle Key press events


        :param event: The key press event to handle
        """
        if not self.hidden:
            inp = self.game.inputs

            if inp.k_down or inp.k_right:
                self.selection += 1

            if inp.k_up or inp.k_left:
                self.selection -= 1

            self.selection %= len(self.menu_items)
            self.update_carret()

            if inp.k_action:
                self.menu_items[self.selection].callback()

            return True

        return False

    def update_carret(self):
        """Move the carret to the correct location"""
        selected = self.menu_items[self.selection]
        x = selected.x - Font.FONT_SIZE
        y = selected.y
        self.carret.set_pos((x, y))

    def arrange_items(self):
        """Move the menu items to their correct positions"""
        cy = self.game.h // 2

        max_height = sum(item.h for item in self.menu_items
                         ) + self.padding*(len(self.menu_items)-1)
        top = cy - max_height//2

        y = top

        for item in self.menu_items:
            item_x = (self.game.w - item.w) // 2
            item_y = y
            y += item.h + self.padding
            item.set_pos((item_x, item_y))
        self.update_carret()

    def add_item(self, text: str, callback, index=-1):
        """Add a menu item

        :param text: Label of this item
        :type text: str
        :param callback: Function to call when it is selected
        :param index: Where to insert this item
        """
        if index == -1:
            index = len(self.menu_items)
        self.menu_items.insert(index, MenuItem(self.game, text, callback))
        self.arrange_items()

    def show(self):
        """Make this object visible"""
        if self.hidden:
            for m in self.menu_items:
                m.show()
                m.send_to_front()
            self.carret.show()
            self.carret.send_to_front()

            self.title.show()
            self.title.send_to_front()

            self.hidden = False

    def hide(self):
        """Make this object invisible"""
        if not self.hidden:
            for m in self.menu_items:
                m.hide()
            self.carret.hide()

            self.title.hide()

            self.hidden = True

    def tick(self):
        """Update this object"""
        self.alpha += 1
        if not self.hidden:
            if (self.alpha//15) % 2 == 0:
                self.carret.show()
            else:
                self.carret.hide()
        else:
            self.carret.hide()

    def has_item(self, text):
        """Return true if matching item is found

        :param text: Label text to match
        """
        for entry in self.menu_items:
            if entry.text == text:
                return True

        return False

    def get_item(self, regex) -> MenuItem:
        """Return an item that is matched

        :param regex: regular expression to match item text to
        :rtype: MenuItem
        """
        for entry in self.menu_items:
            if re.match(regex, entry.text):
                return entry

        return self.menu_items[0]

    def edit_item(self, regex, new_text):
        """Edit the text of a menu item

        :param regex: Regular expression to use to match the item's text to
        :param new_text: Text to replace to
        """
        for entry in self.menu_items:
            if re.match(regex, entry.text):
                entry.set_text(new_text)

        self.arrange_items()

    def del_item(self, text):
        """Remove an item

        :param text: Label text to match
        """
        for entry in self.menu_items:
            if entry.text == text:
                entry.destroy()
        self.menu_items = Sprite.remove_destroyed(self.menu_items)
        self.arrange_items()

        return False


class KeybindsMenu(Menu):
    """A menu for selecting keybinds on"""

    def __init__(self, game: Game, title):
        """Initialise the menu

        :param game: The game which this belongs to
        :type game: Game
        :param title: The title of this menu
        """
        super().__init__(game, title)
        self.key_selecting = ""

        image = Font.load_text(game.texture_factory, "press any key")
        self.press_key_sprite = GameSprite(self.game, image)
        self.press_key_sprite.set_pos(
            ((self.game.w - self.press_key_sprite.w) // 2, self.game.h // 2))

    def on_key(self, event):
        """Handle Key press events


        :param event: The key press event to handle
        """
        if self.key_selecting:
            key = event.keysym
            self.set_keybind(self.key_selecting, key)
            self.press_key_sprite.hide()
            self.show()
            return True
        return super().on_key(event)

    def set_keybind(self, name, key):
        """set_keybind.

        :param name:
        :param key:
        """
        setattr(self.game.inputs.settings, self.key_selecting, key)
        self.game.inputs.settings.save_inputs()
        self.key_selecting = ""
        self.edit_item(f"{name}\\s*<.*>", self.get_label(name, key))

    def select_keybind(self, keyname):
        """Allow the user to press a key to decide their keybind

        :param keyname:
        """
        self.hide()
        self.press_key_sprite.show()
        self.key_selecting = keyname

    def get_set_keybind(self, keyname):
        """Return a function that sets the keybind of a particular keyname

        :param keyname:
        """
        return lambda: self.select_keybind(keyname)

    def get_label(self, name, value):
        """Get a label for a keybind item

        :param name:
        :param value:
        """
        available_width = (self.game.w - Font.FONT_SIZE*2) // Font.FONT_WIDTH
        num_spaces = available_width - (len(name) + len(value) + 2) - 1
        spaces = " " * num_spaces
        return f"{name} {spaces}<{value}>"