data/menugui.py (view raw)
1# -*- coding: utf-8 -*-
2
3"""
4This class controls all the GUI for the player
5menu screen.
6"""
7import sys
8import pygame as pg
9from . import setup, observer
10from . import constants as c
11from . import tools
12
13#Python 2/3 compatibility.
14if sys.version_info[0] == 2:
15 range = xrange
16
17class SmallArrow(pg.sprite.Sprite):
18 """Small arrow for menu"""
19 def __init__(self, info_box):
20 super(SmallArrow, self).__init__()
21 self.image = setup.GFX['smallarrow']
22 self.rect = self.image.get_rect()
23 self.state = 'selectmenu'
24 self.state_dict = self.make_state_dict()
25 self.slots = info_box.slots
26 self.pos_list = []
27
28 def make_state_dict(self):
29 """Make state dictionary"""
30 state_dict = {'selectmenu': self.navigate_select_menu,
31 'itemsubmenu': self.navigate_item_submenu,
32 'magicsubmenu': self.navigate_magic_submenu}
33
34 return state_dict
35
36 def navigate_select_menu(self, pos_index):
37 """Nav the select menu"""
38 self.pos_list = self.make_select_menu_pos_list()
39 self.rect.topleft = self.pos_list[pos_index]
40
41 def navigate_item_submenu(self, pos_index):
42 """Nav the item submenu"""
43 self.pos_list = self.make_item_menu_pos_list()
44 self.rect.topleft = self.pos_list[pos_index]
45
46 def navigate_magic_submenu(self, pos_index):
47 """Nav the magic submenu"""
48 self.pos_list = self.make_magic_menu_pos_list()
49 self.rect.topleft = self.pos_list[pos_index]
50
51 def make_magic_menu_pos_list(self):
52 """
53 Make the list of possible arrow positions for magic submenu.
54 """
55 pos_list = [(310, 119),
56 (310, 169)]
57
58 return pos_list
59
60 def make_select_menu_pos_list(self):
61 """Make the list of possible arrow positions"""
62 pos_list = []
63
64 for i in range(3):
65 pos = (35, 443 + (i * 45))
66 pos_list.append(pos)
67
68 return pos_list
69
70 def make_item_menu_pos_list(self):
71 """Make the list of arrow positions in the item submenu"""
72 pos_list = [(300, 173),
73 (300, 223),
74 (300, 323),
75 (300, 373),
76 (300, 478),
77 (300, 528),
78 (535, 478),
79 (535, 528)]
80
81 return pos_list
82
83 def update(self, pos_index):
84 """Update arrow position"""
85 state_function = self.state_dict[self.state]
86 state_function(pos_index)
87
88 def draw(self, surface):
89 """Draw to surface"""
90 surface.blit(self.image, self.rect)
91
92
93class QuickStats(pg.sprite.Sprite):
94 def __init__(self, game_data):
95 self.inventory = game_data['player inventory']
96 self.game_data = game_data
97 self.health = game_data['player stats']['health']
98 self.stats = self.game_data['player stats']
99 self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
100 self.small_font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 18)
101 self.image, self.rect = self.make_image()
102
103 def make_image(self):
104 """
105 Make the surface for the gold box.
106 """
107 stat_list = ['GOLD', 'health', 'magic']
108 magic_health_list = ['health', 'magic']
109 image = setup.GFX['goldbox']
110 rect = image.get_rect(left=10, top=244)
111
112 surface = pg.Surface(rect.size)
113 surface.set_colorkey(c.BLACK)
114 surface.blit(image, (0, 0))
115
116 for i, stat in enumerate(stat_list):
117 first_letter = stat[0].upper()
118 rest_of_letters = stat[1:]
119 if stat in magic_health_list:
120 current = self.stats[stat]['current']
121 max = self.stats[stat]['maximum']
122 text = "{}{}: {}/{}".format(first_letter, rest_of_letters, current, max)
123 elif stat == 'GOLD':
124 text = "Gold: {}".format(self.inventory[stat]['quantity'])
125 render = self.small_font.render(text, True, c.NEAR_BLACK)
126 x = 26
127 y = 45 + (i*30)
128 text_rect = render.get_rect(x=x,
129 centery=y)
130 surface.blit(render, text_rect)
131
132 return surface, rect
133
134 def update(self):
135 """
136 Update gold.
137 """
138 self.image, self.rect = self.make_image()
139
140 def draw(self, surface):
141 """
142 Draw to surface.
143 """
144 surface.blit(self.image, self.rect)
145
146
147class InfoBox(pg.sprite.Sprite):
148 def __init__(self, inventory, player_stats):
149 super(InfoBox, self).__init__()
150 self.inventory = inventory
151 self.player_stats = player_stats
152 self.attack_power = self.get_attack_power()
153 self.defense_power = self.get_defense_power()
154 self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
155 self.big_font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 24)
156 self.title_font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 28)
157 self.title_font.set_underline(True)
158 self.get_tile = tools.get_tile
159 self.sword = self.get_tile(48, 0, setup.GFX['shopsigns'], 16, 16, 2)
160 self.shield = self.get_tile(32, 0, setup.GFX['shopsigns'], 16, 16, 2)
161 self.potion = self.get_tile(16, 0, setup.GFX['shopsigns'], 16, 16, 2)
162 self.possible_potions = ['Healing Potion', 'ELIXIR', 'Ether Potion']
163 self.possible_armor = ['Wooden Shield', 'Chain Mail']
164 self.possible_weapons = ['Long Sword', 'Rapier']
165 self.possible_magic = ['Fire Blast', 'Cure']
166 self.quantity_items = ['Healing Potion', 'ELIXIR', 'Ether Potion']
167 self.slots = {}
168 self.state = 'stats'
169 self.state_dict = self.make_state_dict()
170 self.print_slots = True
171
172 def get_attack_power(self):
173 """
174 Calculate the current attack power based on equipped weapons.
175 """
176 weapon = self.inventory['equipped weapon']
177 weapon_power = self.inventory[weapon]['power']
178 return weapon_power + (self.player_stats['Level'] * 5)
179
180 def get_defense_power(self):
181 """
182 Calculate the current defense power based on equipped weapons.
183 """
184 defense_power = 0
185 for armor in self.inventory['equipped armor']:
186 defense_power += self.inventory[armor]['power']
187
188 return defense_power
189
190 def make_state_dict(self):
191 """Make the dictionary of state methods"""
192 state_dict = {'stats': self.show_player_stats,
193 'items': self.show_items,
194 'magic': self.show_magic}
195
196 return state_dict
197
198
199 def show_player_stats(self):
200 """Show the player's main stats"""
201 title = 'STATS'
202 stat_list = ['Level', 'experience to next level',
203 'health', 'magic', 'Attack Power',
204 'Defense Power', 'gold']
205 attack_power = 5
206 surface, rect = self.make_blank_info_box(title)
207
208 for i, stat in enumerate(stat_list):
209 if stat == 'health' or stat == 'magic':
210 text = "{}{}: {} / {}".format(stat[0].upper(),
211 stat[1:],
212 str(self.player_stats[stat]['current']),
213 str(self.player_stats[stat]['maximum']))
214 elif stat == 'experience to next level':
215 text = "{}{}: {}".format(stat[0].upper(),
216 stat[1:],
217 self.player_stats[stat])
218 elif stat == 'Attack Power':
219 text = "{}: {}".format(stat, self.get_attack_power())
220 elif stat == 'Defense Power':
221 text = "{}: {}".format(stat, self.get_defense_power())
222 elif stat == 'gold':
223 text = "Gold: {}".format(self.inventory['GOLD']['quantity'])
224 else:
225 text = "{}: {}".format(stat, str(self.player_stats[stat]))
226 text_image = self.font.render(text, True, c.NEAR_BLACK)
227 text_rect = text_image.get_rect(x=50, y=80+(i*50))
228 surface.blit(text_image, text_rect)
229
230 self.image = surface
231 self.rect = rect
232
233
234 def show_items(self):
235 """Show list of items the player has"""
236 title = 'ITEMS'
237 potions = ['POTIONS']
238 weapons = ['WEAPONS']
239 armor = ['ARMOR']
240 for i, item in enumerate(self.inventory):
241 if item in self.possible_weapons:
242 if item == self.inventory['equipped weapon']:
243 item += " (E)"
244 weapons.append(item)
245 elif item in self.possible_armor:
246 if item in self.inventory['equipped armor']:
247 item += " (E)"
248 armor.append(item)
249 elif item in self.possible_potions:
250 potions.append(item)
251
252 self.slots = {}
253 self.assign_slots(weapons, 85)
254 self.assign_slots(armor, 235)
255 self.assign_slots(potions, 390)
256
257 surface, rect = self.make_blank_info_box(title)
258
259 self.blit_item_lists(surface)
260
261 self.sword['rect'].topleft = 40, 80
262 self.shield['rect'].topleft = 40, 230
263 self.potion['rect'].topleft = 40, 385
264 surface.blit(self.sword['surface'], self.sword['rect'])
265 surface.blit(self.shield['surface'], self.shield['rect'])
266 surface.blit(self.potion['surface'], self.potion['rect'])
267
268 self.image = surface
269 self.rect = rect
270
271
272 def assign_slots(self, item_list, starty, weapon_or_armor=False):
273 """Assign each item to a slot in the menu"""
274 if len(item_list) > 3:
275 for i, item in enumerate(item_list[:3]):
276 posx = 80
277 posy = starty + (i * 50)
278 self.slots[(posx, posy)] = item
279 for i, item in enumerate(item_list[3:]):
280 posx = 315
281 posy = (starty + 50) + (i * 5)
282 self.slots[(posx, posy)] = item
283 else:
284 for i, item in enumerate(item_list):
285 posx = 80
286 posy = starty + (i * 50)
287 self.slots[(posx, posy)] = item
288
289 def assign_magic_slots(self, magic_list, starty):
290 """
291 Assign each magic spell to a slot in the menu.
292 """
293 for i, spell in enumerate(magic_list):
294 posx = 120
295 posy = starty + (i * 50)
296 self.slots[(posx, posy)] = spell
297
298 def blit_item_lists(self, surface):
299 """Blit item list to info box surface"""
300 for coord in self.slots:
301 item = self.slots[coord]
302
303 if item in self.possible_potions:
304 text = "{}: {}".format(self.slots[coord],
305 self.inventory[item]['quantity'])
306 else:
307 text = "{}".format(self.slots[coord])
308 text_image = self.font.render(text, True, c.NEAR_BLACK)
309 text_rect = text_image.get_rect(topleft=coord)
310 surface.blit(text_image, text_rect)
311
312 def show_magic(self):
313 """Show list of magic spells the player knows"""
314 title = 'MAGIC'
315 item_list = []
316 for item in self.inventory:
317 if item in self.possible_magic:
318 item_list.append(item)
319 item_list = sorted(item_list)
320
321 self.slots = {}
322 self.assign_magic_slots(item_list, 80)
323
324 surface, rect = self.make_blank_info_box(title)
325
326 for i, item in enumerate(item_list):
327 text_image = self.font.render(item, True, c.NEAR_BLACK)
328 text_rect = text_image.get_rect(x=100, y=80+(i*50))
329 surface.blit(text_image, text_rect)
330
331 self.image = surface
332 self.rect = rect
333
334
335 def make_blank_info_box(self, title):
336 """Make an info box with title, otherwise blank"""
337 image = setup.GFX['playerstatsbox']
338 rect = image.get_rect(left=285, top=35)
339 centerx = rect.width / 2
340
341 surface = pg.Surface(rect.size)
342 surface.set_colorkey(c.BLACK)
343 surface.blit(image, (0,0))
344
345 title_image = self.title_font.render(title, True, c.NEAR_BLACK)
346 title_rect = title_image.get_rect(centerx=centerx, y=30)
347 surface.blit(title_image, title_rect)
348
349 return surface, rect
350
351
352 def update(self):
353 state_function = self.state_dict[self.state]
354 state_function()
355
356
357 def draw(self, surface):
358 """Draw to surface"""
359 surface.blit(self.image, self.rect)
360
361
362class SelectionBox(pg.sprite.Sprite):
363 def __init__(self):
364 self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
365 self.image, self.rect = self.make_image()
366
367 def make_image(self):
368 choices = ['Stats', 'Items', 'Magic']
369 image = setup.GFX['goldbox']
370 rect = image.get_rect(left=10, top=425)
371
372 surface = pg.Surface(rect.size)
373 surface.set_colorkey(c.BLACK)
374 surface.blit(image, (0, 0))
375
376 for i, choice in enumerate(choices):
377 choice_image = self.font.render(choice, True, c.NEAR_BLACK)
378 choice_rect = choice_image.get_rect(x=100, y=(15 + (i * 45)))
379 surface.blit(choice_image, choice_rect)
380
381 return surface, rect
382
383 def draw(self, surface):
384 """Draw to surface"""
385 surface.blit(self.image, self.rect)
386
387
388class MenuGui(object):
389 def __init__(self, level, inventory, stats):
390 self.level = level
391 self.game_data = self.level.game_data
392 self.sfx_observer = observer.SoundEffects()
393 self.observers = [self.sfx_observer]
394 self.inventory = inventory
395 self.stats = stats
396 self.info_box = InfoBox(inventory, stats)
397 self.gold_box = QuickStats(self.game_data)
398 self.selection_box = SelectionBox()
399 self.arrow = SmallArrow(self.info_box)
400 self.arrow_index = 0
401 self.allow_input = False
402
403
404
405 def check_for_input(self, keys):
406 """Check for input"""
407 if self.allow_input:
408 if keys[pg.K_DOWN]:
409 if self.arrow_index < len(self.arrow.pos_list) - 1:
410 self.notify(c.CLICK)
411 self.arrow_index += 1
412 self.allow_input = False
413 elif keys[pg.K_UP]:
414 if self.arrow_index > 0:
415 self.notify(c.CLICK)
416 self.arrow_index -= 1
417 self.allow_input = False
418 elif keys[pg.K_RIGHT]:
419 if self.info_box.state == 'items':
420 if not self.arrow.state == 'itemsubmenu':
421 self.notify(c.CLICK)
422 self.arrow_index = 0
423 self.arrow.state = 'itemsubmenu'
424 elif self.info_box.state == 'magic':
425 if not self.arrow.state == 'magicsubmenu':
426 self.notify(c.CLICK)
427 self.arrow_index = 0
428 self.arrow.state = 'magicsubmenu'
429 self.allow_input = False
430
431 elif keys[pg.K_LEFT]:
432 self.notify(c.CLICK)
433 self.arrow.state = 'selectmenu'
434 self.arrow_index = 0
435 self.allow_input = False
436 elif keys[pg.K_SPACE]:
437 self.notify(c.CLICK2)
438 if self.arrow.state == 'selectmenu':
439 if self.arrow_index == 0:
440 self.info_box.state = 'stats'
441 elif self.arrow_index == 1:
442 self.info_box.state = 'items'
443 elif self.arrow_index == 2:
444 self.info_box.state = 'magic'
445 elif self.arrow.state == 'itemsubmenu':
446 self.select_item()
447 elif self.arrow.state == 'magicsubmenu':
448 self.select_magic()
449
450 self.allow_input = False
451 elif keys[pg.K_RETURN]:
452 self.level.state = 'normal'
453 self.info_box.state = 'stats'
454 self.allow_input = False
455 self.arrow_index = 0
456 self.arrow.state = 'selectmenu'
457
458 if (not keys[pg.K_DOWN]
459 and not keys[pg.K_UP]
460 and not keys[pg.K_RETURN]
461 and not keys[pg.K_SPACE]
462 and not keys[pg.K_RIGHT]
463 and not keys[pg.K_LEFT]):
464 self.allow_input = True
465
466 def notify(self, event):
467 """
468 Notify all observers of event.
469 """
470 for observer in self.observers:
471 observer.on_notify(event)
472
473 def select_item(self):
474 """
475 Select item from item menu.
476 """
477 health = self.game_data['player stats']['health']
478 posx = self.arrow.rect.x - 220
479 posy = self.arrow.rect.y - 38
480
481 if (posx, posy) in self.info_box.slots:
482 if self.info_box.slots[(posx, posy)][:7] == 'Healing':
483 potion = 'Healing Potion'
484 value = 30
485 self.drink_potion(potion, health, value)
486 elif self.info_box.slots[(posx, posy)][:5] == 'Ether':
487 potion = 'Ether Potion'
488 stat = self.game_data['player stats']['magic']
489 value = 30
490 self.drink_potion(potion, stat, value)
491 elif self.info_box.slots[(posx, posy)][:10] == 'Long Sword':
492 self.inventory['equipped weapon'] = 'Long Sword'
493 elif self.info_box.slots[(posx, posy)][:6] == 'Rapier':
494 self.inventory['equipped weapon'] = 'Rapier'
495 elif self.info_box.slots[(posx, posy)][:13] == 'Wooden Shield':
496 if 'Wooden Shield' in self.inventory['equipped armor']:
497 self.inventory['equipped armor'].remove('Wooden Shield')
498 else:
499 self.inventory['equipped armor'].append('Wooden Shield')
500 elif self.info_box.slots[(posx, posy)][:10] == 'Chain Mail':
501 if 'Chain Mail' in self.inventory['equipped armor']:
502 self.inventory['equipped armor'].remove('Chain Mail')
503 else:
504 self.inventory['equipped armor'].append('Chain Mail')
505
506 def select_magic(self):
507 """
508 Select spell from magic menu.
509 """
510 health = self.game_data['player stats']['health']
511 magic = self.game_data['player stats']['magic']
512 posx = self.arrow.rect.x - 190
513 posy = self.arrow.rect.y - 39
514
515 if (posx, posy) in self.info_box.slots:
516 if self.info_box.slots[(posx, posy)][:4] == 'Cure':
517 self.use_cure_spell()
518
519 def use_cure_spell(self):
520 """
521 Use cure spell to heal player.
522 """
523 health = self.game_data['player stats']['health']
524 magic = self.game_data['player stats']['magic']
525 inventory = self.game_data['player inventory']
526
527 if magic['current'] >= inventory['Cure']['magic points']:
528 magic['current'] -= inventory['Cure']['magic points']
529 health['current'] += inventory['Cure']['power']
530 if health['current'] > health['maximum']:
531 health['current'] = health['maximum']
532
533 def drink_potion(self, potion, stat, value):
534 """
535 Drink potion and change player stats.
536 """
537 self.inventory[potion]['quantity'] -= 1
538 stat['current'] += value
539 if stat['current'] > stat['maximum']:
540 stat['current'] = stat['maximum']
541 if not self.inventory[potion]['quantity']:
542 del self.inventory[potion]
543
544 def update(self, keys):
545 self.info_box.update()
546 self.gold_box.update()
547 self.arrow.update(self.arrow_index)
548 self.check_for_input(keys)
549
550
551 def draw(self, surface):
552 self.gold_box.draw(surface)
553 self.info_box.draw(surface)
554 self.selection_box.draw(surface)
555 self.arrow.draw(surface)