all repos — Legends-RPG @ 05d9e3d3d1f5fd253dc04a612313eac3b634def0

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.slots = {}
191        self.assign_slots(weapons, 85)
192        self.assign_slots(armor, 235)
193        self.assign_slots(potions, 390)
194
195        surface, rect = self.make_blank_info_box(title)
196
197        self.blit_item_lists(surface)
198
199        self.sword['rect'].topleft = 40, 80
200        self.shield['rect'].topleft = 40, 230
201        self.potion['rect'].topleft = 40, 385
202        surface.blit(self.sword['surface'], self.sword['rect'])
203        surface.blit(self.shield['surface'], self.shield['rect'])
204        surface.blit(self.potion['surface'], self.potion['rect'])
205
206        self.image = surface
207        self.rect = rect
208
209
210    def assign_slots(self, item_list, starty):
211        """Assign each item to a slot in the menu"""
212        if len(item_list) > 3:
213            for i, item in enumerate(item_list[:3]):
214                posx = 80
215                posy = starty + (i * 50)
216                self.slots[(posx, posy)] = item
217            for i, item in enumerate(item_list[3:]):
218                posx = 315
219                posy = (starty + 50) + (i * 5)
220                self.slots[(posx, posy)] = item
221        else:
222            for i, item in enumerate(item_list):
223                posx = 80
224                posy = starty + (i * 50)
225                self.slots[(posx, posy)] = item
226
227
228    def blit_item_lists(self, surface):
229        """Blit item list to info box surface"""
230        for coord in self.slots:
231            item = self.slots[coord]
232            if item in self.inventory:
233                text = "{}: {}".format(self.slots[coord],
234                                       self.inventory[item]['quantity'])
235            else:
236                text = "{}".format(self.slots[coord])
237            text_image = self.font.render(text, True, c.NEAR_BLACK)
238            text_rect = text_image.get_rect(topleft=coord)
239            surface.blit(text_image, text_rect)
240
241
242
243    def show_magic(self):
244        """Show list of magic spells the player knows"""
245        title = 'MAGIC'
246        item_list = []
247        for item in self.inventory:
248            if item in self.possible_magic:
249                item_list.append(item)
250                item_list = sorted(item_list)
251
252        surface, rect = self.make_blank_info_box(title)
253
254        for i, item in enumerate(item_list):
255            text_image = self.font.render(item, True, c.NEAR_BLACK)
256            text_rect = text_image.get_rect(x=50, y=80+(i*50))
257            surface.blit(text_image, text_rect)
258
259        self.image = surface
260        self.rect = rect
261
262
263    def make_blank_info_box(self, title):
264        """Make an info box with title, otherwise blank"""
265        image = setup.GFX['playerstatsbox']
266        rect = image.get_rect(left=285, top=35)
267        centerx = rect.width / 2
268
269        surface = pg.Surface(rect.size)
270        surface.set_colorkey(c.BLACK)
271        surface.blit(image, (0,0))
272
273        title_image = self.title_font.render(title, True, c.NEAR_BLACK)
274        title_rect = title_image.get_rect(centerx=centerx, y=30)
275        surface.blit(title_image, title_rect)
276
277        return surface, rect
278
279
280    def update(self):
281        state_function = self.state_dict[self.state]
282        state_function()
283
284
285    def draw(self, surface):
286        """Draw to surface"""
287        surface.blit(self.image, self.rect)
288
289
290class SelectionBox(pg.sprite.Sprite):
291    def __init__(self):
292        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
293        self.image, self.rect = self.make_image()
294
295
296    def make_image(self):
297        choices = ['Stats', 'Items', 'Magic', 'Exit']
298        image = setup.GFX['selectionbox']
299        rect = image.get_rect(left=10, top=330)
300
301        surface = pg.Surface(rect.size)
302        surface.set_colorkey(c.BLACK)
303        surface.blit(image, (0, 0))
304
305        for i, choice in enumerate(choices):
306            choice_image = self.font.render(choice, True, c.NEAR_BLACK)
307            choice_rect = choice_image.get_rect(x=100, y=(25 + (i * 50)))
308            surface.blit(choice_image, choice_rect)
309
310        return surface, rect
311
312
313    def draw(self, surface):
314        """Draw to surface"""
315        surface.blit(self.image, self.rect)
316
317
318
319
320class MenuGui(object):
321    def __init__(self, level, inventory, stats):
322        self.level = level
323        self.game_data = self.level.game_data
324        self.inventory = inventory
325        self.stats = stats
326        self.info_box = InfoBox(inventory, stats)
327        self.gold_box = GoldBox(inventory)
328        self.selection_box = SelectionBox()
329        self.arrow = SmallArrow(self.info_box)
330        self.arrow_index = 0
331        self.allow_input = False
332        self.state = 'stats'
333
334
335    def check_for_input(self, keys):
336        """Check for input"""
337        if self.allow_input:
338            if keys[pg.K_DOWN]:
339                if self.arrow_index < len(self.arrow.pos_list) - 1:
340                    self.arrow_index += 1
341                    self.allow_input = False
342            elif keys[pg.K_UP]:
343                if self.arrow_index > 0:
344                    self.arrow_index -= 1
345                    self.allow_input = False
346            elif keys[pg.K_RIGHT]:
347                if self.info_box.state == 'items':
348                    if not self.arrow.state == 'itemsubmenu':
349                        self.arrow_index = 0
350                    self.arrow.state = 'itemsubmenu'
351
352            elif keys[pg.K_LEFT]:
353                self.arrow.state = 'selectmenu'
354                self.arrow_index = 0
355            elif keys[pg.K_SPACE]:
356                if self.arrow.state == 'selectmenu':
357                    if self.arrow_index == 0:
358                        self.info_box.state = 'stats'
359
360                    elif self.arrow_index == 1:
361                        self.info_box.state = 'items'
362
363                    elif self.arrow_index == 2:
364                        self.info_box.state = 'magic'
365
366                    elif self.arrow_index == 3:
367                        self.level.state = 'normal'
368                        self.arrow_index = 0
369                        self.info_box.state = 'stats'
370                elif self.arrow.state == 'itemsubmenu':
371                    self.select_item()
372
373                self.allow_input = False
374            elif keys[pg.K_RETURN]:
375                self.level.state = 'normal'
376                self.info_box.state = 'stats'
377                self.allow_input = False
378                self.arrow_index = 0
379                self.arrow.state = 'selectmenu'
380
381        if (not keys[pg.K_DOWN]
382                and not keys[pg.K_UP]
383                and not keys[pg.K_RETURN]
384                and not keys[pg.K_SPACE]):
385            self.allow_input = True
386
387    def select_item(self):
388        """
389        Select item from item menu.
390        """
391        health = self.game_data['player stats']['health']
392        posx = self.arrow.rect.x - 220
393        posy = self.arrow.rect.y - 38
394
395        if (posx, posy) in self.info_box.slots:
396            if self.info_box.slots[(posx, posy)][:7] == 'Healing':
397                potion = 'Healing Potion'
398                stat = self.game_data['player stats']['health']
399                value = 30
400                self.drink_potion(potion, stat, value)
401            elif self.info_box.slots[(posx, posy)][:5] == 'Ether':
402                potion = 'Ether Potion'
403                stat = self.game_data['player stats']['magic points']
404                value = 30
405                self.drink_potion(potion, stat, value)
406
407    def drink_potion(self, potion, stat, value):
408        """
409        Drink potion and change player stats.
410        """
411        self.inventory[potion]['quantity'] -= 1
412        stat['current'] += value
413        if stat['current'] > stat['maximum']:
414            stat['current'] = stat['maximum']
415        if not self.inventory[potion]['quantity']:
416            del self.inventory[potion]
417
418    def update(self, keys):
419        self.info_box.update()
420        self.gold_box.update()
421        self.arrow.update(self.arrow_index)
422        self.check_for_input(keys)
423
424
425    def draw(self, surface):
426        self.gold_box.draw(surface)
427        self.info_box.draw(surface)
428        self.selection_box.draw(surface)
429        self.arrow.draw(surface)