all repos — Legends-RPG @ c6b5b5cb031ab81893532d4514cedf0cb3d0d70e

A fantasy mini-RPG built with Python and Pygame.

data/menugui.py (view raw)

  1# -*- coding: utf-8 -*-
  2"""
  3This class controls all the GUI for the player
  4menu screen.
  5"""
  6import pygame as pg
  7from . import setup
  8from . import constants as c
  9from . import tools
 10
 11
 12class SmallArrow(pg.sprite.Sprite):
 13    """Small arrow for menu"""
 14    def __init__(self, info_box):
 15        super(SmallArrow, self).__init__()
 16        self.image = setup.GFX['smallarrow']
 17        self.rect = self.image.get_rect()
 18        self.state = 'selectmenu'
 19        self.state_dict = self.make_state_dict()
 20        self.slots = info_box.slots
 21        self.pos_list = []
 22
 23
 24    def make_state_dict(self):
 25        """Make state dictionary"""
 26        state_dict = {'selectmenu': self.navigate_select_menu,
 27                      'itemsubmenu': self.navigate_item_submenu}
 28
 29        return state_dict
 30
 31
 32    def navigate_select_menu(self, pos_index):
 33        """Nav the select menu"""
 34        self.pos_list = self.make_select_menu_pos_list()
 35        self.rect.topleft = self.pos_list[pos_index]
 36
 37
 38    def navigate_item_submenu(self, pos_index):
 39        """Nav the item submenu"""
 40        self.pos_list = self.make_item_menu_pos_list()
 41        self.rect.topleft = self.pos_list[pos_index]
 42
 43
 44    def make_select_menu_pos_list(self):
 45        """Make the list of possible arrow positions"""
 46        pos_list = []
 47
 48        for i in range(4):
 49            pos = (35, 356 + (i * 50))
 50            pos_list.append(pos)
 51
 52        return pos_list
 53
 54
 55    def make_item_menu_pos_list(self):
 56        """Make the list of arrow positions in the item submenu"""
 57        pos_list = [(300, 173),
 58                    (300, 223),
 59                    (300, 323),
 60                    (300, 373),
 61                    (300, 478),
 62                    (300, 528),
 63                    (535, 478),
 64                    (535, 528)]
 65
 66        return pos_list
 67
 68
 69    def update(self, pos_index):
 70        """Update arrow position"""
 71        state_function = self.state_dict[self.state]
 72        state_function(pos_index)
 73
 74
 75    def draw(self, surface):
 76        """Draw to surface"""
 77        surface.blit(self.image, self.rect)
 78
 79
 80
 81class GoldBox(pg.sprite.Sprite):
 82    def __init__(self, inventory):
 83        self.inventory = inventory
 84        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
 85        self.image, self.rect = self.make_image()
 86
 87    def make_image(self):
 88        """Make the surface for the gold box"""
 89        image = setup.GFX['goldbox2']
 90        rect = image.get_rect(left=10, top=234)
 91
 92        surface = pg.Surface(rect.size)
 93        surface.set_colorkey(c.BLACK)
 94        surface.blit(image, (0, 0))
 95
 96        text = "Gold: " + str(self.inventory['GOLD']['quantity'])
 97        text_render = self.font.render(text, True, c.NEAR_BLACK)
 98        text_rect = text_render.get_rect(centerx=130,
 99                                         centery=35)
100        surface.blit(text_render, text_rect)
101
102        return surface, rect
103
104
105    def update(self):
106        """Update gold"""
107        self.image, self.rect = self.make_image()
108
109
110    def draw(self, surface):
111        """Draw to surface"""
112        surface.blit(self.image, self.rect)
113
114
115
116class InfoBox(pg.sprite.Sprite):
117    def __init__(self, inventory, player_stats):
118        super(InfoBox, self).__init__()
119        self.inventory = inventory
120        self.player_stats = player_stats
121        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
122        self.big_font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 24)
123        self.title_font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 28)
124        self.title_font.set_underline(True)
125        self.get_tile = tools.get_tile
126        self.sword = self.get_tile(48, 0, setup.GFX['shopsigns'], 16, 16, 2)
127        self.shield = self.get_tile(32, 0, setup.GFX['shopsigns'], 16, 16, 2)
128        self.potion = self.get_tile(16, 0, setup.GFX['shopsigns'], 16, 16, 2)
129        self.possible_potions = ['Healing Potion', 'ELIXIR', 'Ether Potion']
130        self.possible_armor = ['Wooden Shield', 'Chain Mail']
131        self.possible_weapons = ['Long Sword', 'Rapier']
132        self.possible_magic = ['Fire Blast', 'Cure']
133        self.quantity_items = ['Healing Potion', 'ELIXIR', 'Ether Potion']
134        self.slots = {}
135        self.state = 'stats'
136        self.state_dict = self.make_state_dict()
137        self.print_slots = True
138
139
140    def make_state_dict(self):
141        """Make the dictionary of state methods"""
142        state_dict = {'stats': self.show_player_stats,
143                      'items': self.show_items,
144                      'magic': self.show_magic}
145
146        return state_dict
147
148
149    def show_player_stats(self):
150        """Show the player's main stats"""
151        title = 'STATS'
152        stat_list = ['Level', 'health',
153                     'magic points', 'experience to next level']
154        surface, rect = self.make_blank_info_box(title)
155
156        for i, stat in enumerate(stat_list):
157            if stat == 'health' or stat == 'magic points':
158                text = "{}{}: {} / {}".format(stat[0].upper(),
159                                              stat[1:],
160                                              str(self.player_stats[stat]['current']),
161                                              str(self.player_stats[stat]['maximum']))
162            elif stat == 'experience to next level':
163                text = "{}{}: {}".format(stat[0].upper(),
164                                         stat[1:],
165                                         self.player_stats[stat])
166            else:
167                text = "{}: {}".format(stat, str(self.player_stats[stat]))
168            text_image = self.font.render(text, True, c.NEAR_BLACK)
169            text_rect = text_image.get_rect(x=50, y=80+(i*50))
170            surface.blit(text_image, text_rect)
171
172        self.image = surface
173        self.rect = rect
174
175
176    def show_items(self):
177        """Show list of items the player has"""
178        title = 'ITEMS'
179        potions = ['POTIONS']
180        weapons = ['WEAPONS']
181        armor = ['ARMOR']
182        for i, item in enumerate(self.inventory):
183            if item in self.possible_weapons:
184                weapons.append(item)
185            elif item in self.possible_armor:
186                armor.append(item)
187            elif item in self.possible_potions:
188                potions.append(item)
189
190        self.assign_slots(weapons, 85)
191        self.assign_slots(armor, 235)
192        self.assign_slots(potions, 390)
193
194        surface, rect = self.make_blank_info_box(title)
195
196        self.blit_item_lists(surface)
197
198        self.sword['rect'].topleft = 40, 80
199        self.shield['rect'].topleft = 40, 230
200        self.potion['rect'].topleft = 40, 385
201        surface.blit(self.sword['surface'], self.sword['rect'])
202        surface.blit(self.shield['surface'], self.shield['rect'])
203        surface.blit(self.potion['surface'], self.potion['rect'])
204
205        self.image = surface
206        self.rect = rect
207
208
209    def assign_slots(self, item_list, starty):
210        """Assign each item to a slot in the menu"""
211        if len(item_list) > 3:
212            for i, item in enumerate(item_list[:3]):
213                posx = 80
214                posy = starty + (i * 50)
215                self.slots[(posx, posy)] = item
216            for i, item in enumerate(item_list[3:]):
217                posx = 315
218                posy = (starty + 50) + (i * 5)
219                self.slots[(posx, posy)] = item
220        else:
221            for i, item in enumerate(item_list):
222                posx = 80
223                posy = starty + (i * 50)
224                self.slots[(posx, posy)] = item
225
226
227    def blit_item_lists(self, surface):
228        """Blit item list to info box surface"""
229        for coord in self.slots:
230            item = self.slots[coord]
231            if item in self.inventory:
232                text = "{}: {}".format(self.slots[coord],
233                                       self.inventory[item]['quantity'])
234            else:
235                text = "{}".format(self.slots[coord])
236            text_image = self.font.render(text, True, c.NEAR_BLACK)
237            text_rect = text_image.get_rect(topleft=coord)
238            surface.blit(text_image, text_rect)
239
240
241
242    def show_magic(self):
243        """Show list of magic spells the player knows"""
244        title = 'MAGIC'
245        item_list = []
246        for item in self.inventory:
247            if item in self.possible_magic:
248                item_list.append(item)
249                item_list = sorted(item_list)
250
251        surface, rect = self.make_blank_info_box(title)
252
253        for i, item in enumerate(item_list):
254            text_image = self.font.render(item, True, c.NEAR_BLACK)
255            text_rect = text_image.get_rect(x=50, y=80+(i*50))
256            surface.blit(text_image, text_rect)
257
258        self.image = surface
259        self.rect = rect
260
261
262    def make_blank_info_box(self, title):
263        """Make an info box with title, otherwise blank"""
264        image = setup.GFX['playerstatsbox']
265        rect = image.get_rect(left=285, top=35)
266        centerx = rect.width / 2
267
268        surface = pg.Surface(rect.size)
269        surface.set_colorkey(c.BLACK)
270        surface.blit(image, (0,0))
271
272        title_image = self.title_font.render(title, True, c.NEAR_BLACK)
273        title_rect = title_image.get_rect(centerx=centerx, y=30)
274        surface.blit(title_image, title_rect)
275
276        return surface, rect
277
278
279    def update(self):
280        state_function = self.state_dict[self.state]
281        state_function()
282
283
284    def draw(self, surface):
285        """Draw to surface"""
286        surface.blit(self.image, self.rect)
287
288
289class SelectionBox(pg.sprite.Sprite):
290    def __init__(self):
291        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
292        self.image, self.rect = self.make_image()
293
294
295    def make_image(self):
296        choices = ['Stats', 'Items', 'Magic', 'Exit']
297        image = setup.GFX['selectionbox']
298        rect = image.get_rect(left=10, top=330)
299
300        surface = pg.Surface(rect.size)
301        surface.set_colorkey(c.BLACK)
302        surface.blit(image, (0, 0))
303
304        for i, choice in enumerate(choices):
305            choice_image = self.font.render(choice, True, c.NEAR_BLACK)
306            choice_rect = choice_image.get_rect(x=100, y=(25 + (i * 50)))
307            surface.blit(choice_image, choice_rect)
308
309        return surface, rect
310
311
312    def draw(self, surface):
313        """Draw to surface"""
314        surface.blit(self.image, self.rect)
315
316
317
318
319class MenuGui(object):
320    def __init__(self, level, inventory, stats):
321        self.level = level
322        self.inventory = inventory
323        self.stats = stats
324        self.info_box = InfoBox(inventory, stats)
325        self.gold_box = GoldBox(inventory)
326        self.selection_box = SelectionBox()
327        self.arrow = SmallArrow(self.info_box)
328        self.arrow_index = 0
329        self.allow_input = False
330        self.state = 'stats'
331
332
333    def check_for_input(self, keys):
334        """Check for input"""
335        if self.allow_input:
336            if keys[pg.K_DOWN]:
337                if self.arrow_index < len(self.arrow.pos_list) - 1:
338                    self.arrow_index += 1
339                    self.allow_input = False
340            elif keys[pg.K_UP]:
341                if self.arrow_index > 0:
342                    self.arrow_index -= 1
343                    self.allow_input = False
344            elif keys[pg.K_RIGHT]:
345                if self.info_box.state == 'items':
346                    if not self.arrow.state == 'itemsubmenu':
347                        self.arrow_index = 0
348                    self.arrow.state = 'itemsubmenu'
349
350            elif keys[pg.K_LEFT]:
351                self.arrow.state = 'selectmenu'
352                self.arrow_index = 0
353            elif keys[pg.K_SPACE]:
354                if self.arrow.state == 'selectmenu':
355                    if self.arrow_index == 0:
356                        self.info_box.state = 'stats'
357
358                    elif self.arrow_index == 1:
359                        self.info_box.state = 'items'
360
361                    elif self.arrow_index == 2:
362                        self.info_box.state = 'magic'
363
364                    elif self.arrow_index == 3:
365                        self.level.state = 'normal'
366                        self.arrow_index = 0
367                        self.info_box.state = 'stats'
368
369
370                self.allow_input = False
371            elif keys[pg.K_RETURN]:
372                self.level.state = 'normal'
373                self.info_box.state = 'stats'
374                self.allow_input = False
375                self.arrow_index = 0
376
377        if (not keys[pg.K_DOWN]
378                and not keys[pg.K_UP]
379                and not keys[pg.K_RETURN]
380                and not keys[pg.K_SPACE]):
381            self.allow_input = True
382
383
384    def update(self, keys):
385        self.info_box.update()
386        self.gold_box.update()
387        self.arrow.update(self.arrow_index)
388        self.check_for_input(keys)
389
390
391    def draw(self, surface):
392        self.gold_box.draw(surface)
393        self.info_box.draw(surface)
394        self.selection_box.draw(surface)
395        self.arrow.draw(surface)