all repos — Legends-RPG @ 771a9169fe092728fcd9519c5a9f76f2fd9cb035

A fantasy mini-RPG built with Python and Pygame.

data/shopgui.py (view raw)

  1"""
  2This class controls the textbox GUI for any shop state.
  3A Gui object is created and updated by the shop state.
  4"""
  5
  6import pygame as pg
  7from . import setup, observer
  8from . components import textbox
  9from . import constants as c
 10
 11
 12class Gui(object):
 13    """Class that controls the GUI of the shop state"""
 14    def __init__(self, level):
 15        self.level = level
 16        self.game_data = self.level.game_data
 17        self.level.game_data['last direction'] = 'down'
 18        self.SFX_observer = observer.SoundEffects()
 19        self.observers = [self.SFX_observer]
 20        self.sellable_items = level.sell_items
 21        self.player_inventory = level.game_data['player inventory']
 22        self.name = level.name
 23        self.state = 'dialogue'
 24        self.no_selling = ['Inn', 'Magic Shop']
 25        self.weapon_list = ['Long Sword', 'Rapier']
 26        self.armor_list = ['Chain Mail', 'Wooden Shield']
 27        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
 28        self.index = 0
 29        self.timer = 0.0
 30        self.allow_input = False
 31        self.items = level.items
 32        self.item_to_be_sold = None
 33        self.item_to_be_purchased = None
 34        self.dialogue = level.dialogue
 35        self.accept_dialogue = level.accept_dialogue
 36        self.accept_sale_dialogue = level.accept_sale_dialogue
 37        self.arrow = textbox.NextArrow()
 38        self.selection_arrow = textbox.NextArrow()
 39        self.arrow_pos1 = (50, 475)
 40        self.arrow_pos2 = (50, 515)
 41        self.arrow_pos3 = (50, 555)
 42        self.arrow_pos4 = (50, 495)
 43        self.arrow_pos5 = (50, 535)
 44        self.arrow_pos_list = [self.arrow_pos1, self.arrow_pos2, self.arrow_pos3]
 45        self.two_arrow_pos_list = [self.arrow_pos4, self.arrow_pos5]
 46        self.arrow_index = 0
 47        self.selection_arrow.rect.topleft = self.arrow_pos1
 48        self.dialogue_box = self.make_dialogue_box(self.dialogue, self.index)
 49        self.gold_box = self.make_gold_box()
 50        if self.name in self.no_selling:
 51            choices = self.items[0]['dialogue']
 52        else:
 53            choices = ['Buy', 'Sell', 'Leave']
 54        self.selection_box = self.make_selection_box(choices)
 55        self.state_dict = self.make_state_dict()
 56
 57    def notify(self, event):
 58        """
 59        Notify all observers of event.
 60        """
 61        for observer in self.observers:
 62            observer.on_notify(event)
 63
 64    def make_dialogue_box(self, dialogue_list, index):
 65        """
 66        Make the sprite that controls the dialogue.
 67        """
 68        image = setup.GFX['dialoguebox']
 69        rect = image.get_rect()
 70        surface = pg.Surface(rect.size)
 71        surface.set_colorkey(c.BLACK)
 72        surface.blit(image, rect)
 73        dialogue = self.font.render(dialogue_list[index],
 74                                    True,
 75                                    c.NEAR_BLACK)
 76        dialogue_rect = dialogue.get_rect(left=50, top=50)
 77        surface.blit(dialogue, dialogue_rect)
 78        sprite = pg.sprite.Sprite()
 79        sprite.image = surface
 80        sprite.rect = rect
 81        self.check_to_draw_arrow(sprite)
 82
 83        return sprite
 84
 85    def check_to_draw_arrow(self, sprite):
 86        """
 87        Blink arrow if more text needs to be read.
 88        """
 89        if self.index < len(self.dialogue) - 1:
 90            sprite.image.blit(self.arrow.image, self.arrow.rect)
 91
 92    def make_gold_box(self):
 93        """Make the box to display total gold"""
 94        image = setup.GFX['goldbox']
 95        rect = image.get_rect(bottom=608, right=800)
 96
 97        surface = pg.Surface(rect.size)
 98        surface.set_colorkey(c.BLACK)
 99        surface.blit(image, (0, 0))
100        gold = self.player_inventory['GOLD']['quantity']
101        text = 'Gold: ' + str(gold)
102        text_render = self.font.render(text, True, c.NEAR_BLACK)
103        text_rect = text_render.get_rect(x=80, y=60)
104
105        surface.blit(text_render, text_rect)
106
107        sprite = pg.sprite.Sprite()
108        sprite.image = surface
109        sprite.rect = rect
110
111        return sprite
112
113    def make_selection_box(self, choices):
114        """Make the box for the player to select options"""
115        image = setup.GFX['shopbox']
116        rect = image.get_rect(bottom=608)
117
118        surface = pg.Surface(rect.size)
119        surface.set_colorkey(c.BLACK)
120        surface.blit(image, (0, 0))
121
122        if len(choices) == 2:
123            choice1 = self.font.render(choices[0], True, c.NEAR_BLACK)
124            choice1_rect = choice1.get_rect(x=200, y=35)
125            choice2 = self.font.render(choices[1], True, c.NEAR_BLACK)
126            choice2_rect = choice2.get_rect(x=200, y=75)
127
128            surface.blit(choice1, choice1_rect)
129            surface.blit(choice2, choice2_rect)
130
131        elif len(choices) == 3:
132            choice1 = self.font.render(choices[0], True, c.NEAR_BLACK)
133            choice1_rect = choice1.get_rect(x=200, y=15)
134            choice2 = self.font.render(choices[1], True, c.NEAR_BLACK)
135            choice2_rect = choice2.get_rect(x=200, y=55)
136            choice3 = self.font.render(choices[2], True, c.NEAR_BLACK)
137            choice3_rect = choice3.get_rect(x=200, y=95)
138
139            surface.blit(choice1, choice1_rect)
140            surface.blit(choice2, choice2_rect)
141            surface.blit(choice3, choice3_rect)
142
143        sprite = pg.sprite.Sprite()
144        sprite.image = surface
145        sprite.rect = rect
146
147        return sprite
148
149
150    def make_state_dict(self):
151        """Make the state dictionary for the GUI behavior"""
152        state_dict = {'dialogue': self.control_dialogue,
153                      'select': self.make_selection,
154                      'confirmpurchase': self.confirm_purchase,
155                      'confirmsell': self.confirm_sell,
156                      'reject': self.reject_insufficient_gold,
157                      'accept': self.accept_purchase,
158                      'acceptsell': self.accept_sale,
159                      'hasitem': self.has_item,
160                      'buysell': self.buy_sell,
161                      'sell': self.sell_items,
162                      'cantsell': self.cant_sell,
163                      'cantsellequippedweapon': self.cant_sell_equipped_weapon,
164                      'cantsellequippedarmor': self.cant_sell_equipped_armor}
165
166        return state_dict
167
168    def control_dialogue(self, keys, current_time):
169        """Control the dialogue boxes"""
170        self.dialogue_box = self.make_dialogue_box(self.dialogue, self.index)
171
172        if self.index < (len(self.dialogue) - 1) and self.allow_input:
173            if keys[pg.K_SPACE]:
174                self.index += 1
175                self.allow_input = False
176
177                if self.index == (len(self.dialogue) - 1):
178                    self.state = self.begin_new_transaction()
179
180        if not keys[pg.K_SPACE]:
181            self.allow_input = True
182
183    def begin_new_transaction(self):
184        """Set state to buysell or select, depending if the shop
185        is a Inn/Magic shop or not"""
186        if self.level.name in self.no_selling:
187            state = 'select'
188        else:
189            state = 'buysell'
190
191        return state
192
193
194    def make_selection(self, keys, current_time):
195        """Control the selection"""
196        choices = []
197        for item in self.items:
198            choices.append(item['dialogue'])
199        if self.name in self.no_selling:
200            choices.append('Leave')
201        else:
202            choices.append('Cancel')
203        self.dialogue_box = self.make_dialogue_box(self.dialogue, self.index)
204        self.selection_box = self.make_selection_box(choices)
205        self.gold_box = self.make_gold_box()
206
207        if len(choices) == 2:
208            arrow_list = self.two_arrow_pos_list
209        elif len(choices) == 3:
210            arrow_list = self.arrow_pos_list
211        else:
212            arrow_list = None
213            AssertionError('Only two items supported')
214
215        self.selection_arrow.rect.topleft = arrow_list[self.arrow_index]
216
217
218        if keys[pg.K_DOWN] and self.allow_input:
219            if self.arrow_index < (len(choices) - 1):
220                self.arrow_index += 1
221                self.allow_input = False
222                self.notify(c.CLICK)
223        elif keys[pg.K_UP] and self.allow_input:
224            if self.arrow_index > 0:
225                self.arrow_index -= 1
226                self.allow_input = False
227                self.notify(c.CLICK)
228        elif keys[pg.K_SPACE] and self.allow_input:
229            if self.arrow_index == 0:
230                self.state = 'confirmpurchase'
231                self.item_to_be_purchased = self.items[0]
232
233            elif self.arrow_index == 1 and len(choices) == 3:
234                self.state = 'confirmpurchase'
235                self.item_to_be_purchased = self.items[1]
236
237            else:
238                if self.level.name in self.no_selling:
239                    self.level.state = 'transition out'
240                    self.game_data['last state'] = self.level.name
241                else:
242                    self.state = 'buysell'
243
244            self.notify(c.CLICK2)
245            self.arrow_index = 0
246            self.allow_input = False
247
248        if not keys[pg.K_SPACE] and not keys[pg.K_UP] and not keys[pg.K_DOWN]:
249            self.allow_input = True
250
251
252
253    def confirm_purchase(self, keys, current_time):
254        """Confirm selection state for GUI"""
255        dialogue = ['Are you sure?']
256        choices = ['Yes', 'No']
257        self.selection_box = self.make_selection_box(choices)
258        self.gold_box = self.make_gold_box()
259        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
260        self.selection_arrow.rect.topleft = self.two_arrow_pos_list[self.arrow_index]
261
262        if keys[pg.K_DOWN] and self.allow_input:
263            if self.arrow_index < (len(choices) - 1):
264                self.arrow_index += 1
265                self.allow_input = False
266                self.notify(c.CLICK)
267        elif keys[pg.K_UP] and self.allow_input:
268            if self.arrow_index > 0:
269                self.arrow_index -= 1
270                self.allow_input = False
271                self.notify(c.CLICK)
272        elif keys[pg.K_SPACE] and self.allow_input:
273            if self.arrow_index == 0:
274                self.buy_item()
275            elif self.arrow_index == 1:
276                self.state = self.begin_new_transaction()
277            self.notify(c.CLICK2)
278            self.arrow_index = 0
279            self.allow_input = False
280
281        if not keys[pg.K_SPACE] and not keys[pg.K_DOWN] and not keys[pg.K_UP]:
282            self.allow_input = True
283
284
285    def buy_item(self):
286        """Attempt to allow player to purchase item"""
287        item = self.item_to_be_purchased
288
289        self.player_inventory['GOLD']['quantity'] -= item['price']
290
291        if self.player_inventory['GOLD']['quantity'] < 0:
292            self.player_inventory['GOLD']['quantity'] += item['price']
293            self.state = 'reject'
294        else:
295            if (item['type'] in self.player_inventory and
296                        not self.name == c.POTION_SHOP):
297                self.state = 'hasitem'
298                self.player_inventory['GOLD']['quantity'] += item['price']
299            else:
300                self.notify(c.CLOTH_BELT)
301                self.state = 'accept'
302                self.add_player_item(item)
303
304
305    def add_player_item(self, item):
306        """Add item to player's inventory"""
307        item_type = item['type']
308        quantity = item['quantity']
309        value = item['price']
310        power = item['power']
311        magic_list = ['Cure', 'Fire Blast']
312        player_armor = ['Chain Mail', 'Wooden Shield']
313        player_items = self.level.game_data['player inventory']
314        player_health = self.level.game_data['player stats']['health']
315        player_magic = self.level.game_data['player stats']['magic']
316        equipped_armor = self.level.game_data['player inventory']['equipped armor']
317
318        item_to_add = {'quantity': quantity,
319                       'value': value,
320                       'power': power}
321
322        if item_type in magic_list:
323            item_to_add = {'magic points': item['magic points'],
324                           'power': item['power']}
325            player_items[item_type] = item_to_add
326        if item_type in player_armor:
327            equipped_armor.append(item_type)
328        if item_type in player_items:
329            player_items[item_type]['quantity'] += quantity
330        elif quantity > 0:
331            player_items[item_type] = item_to_add
332        elif item_type == 'room':
333            player_health['current'] = player_health['maximum']
334            player_magic['current'] = player_magic['maximum']
335
336
337    def confirm_sell(self, keys, current_time):
338        """Confirm player wants to sell item"""
339        dialogue = ['Are you sure?']
340        choices = ['Yes', 'No']
341        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
342        self.selection_box = self.make_selection_box(choices)
343        self.selection_arrow.rect.topleft = self.two_arrow_pos_list[self.arrow_index]
344
345        if keys[pg.K_DOWN] and self.allow_input:
346            if self.arrow_index < (len(choices) - 1):
347                self.arrow_index += 1
348                self.allow_input = False
349                self.notify(c.CLICK)
350        elif keys[pg.K_UP] and self.allow_input:
351            if self.arrow_index > 0:
352                self.arrow_index -= 1
353                self.allow_input = False
354                self.notify(c.CLICK)
355        elif keys[pg.K_SPACE] and self.allow_input:
356            if self.arrow_index == 0:
357                self.sell_item_from_inventory()
358            elif self.arrow_index == 1:
359                self.state = self.begin_new_transaction()
360                self.notify(c.CLICK2)
361            self.allow_input = False
362            self.arrow_index = 0
363
364        if not keys[pg.K_SPACE] and not keys[pg.K_UP] and not keys[pg.K_DOWN]:
365            self.allow_input = True
366
367
368    def sell_item_from_inventory(self):
369        """
370        Allow player to sell item to shop.
371        """
372        item_price = self.item_to_be_sold['price']
373        item_name = self.item_to_be_sold['type']
374
375        if item_name in self.weapon_list:
376            if item_name == self.game_data['player inventory']['equipped weapon']:
377                self.state = 'cantsellequippedweapon'
378            else:
379                self.notify(c.CLOTH_BELT)
380                self.sell_inventory_data_adjust(item_price, item_name)
381
382        elif item_name in self.armor_list:
383            if item_name in self.game_data['player inventory']['equipped armor']:
384                self.state = 'cantsellequippedarmor'
385            else:
386                self.notify(c.CLOTH_BELT)
387                self.sell_inventory_data_adjust(item_price, item_name)
388        else:
389            self.notify(c.CLOTH_BELT)
390            self.sell_inventory_data_adjust(item_price, item_name)
391
392    def sell_inventory_data_adjust(self, item_price, item_name):
393        """
394        Add gold and subtract item during sale.
395        """
396        self.player_inventory['GOLD']['quantity'] += (item_price / 2)
397        self.state = 'acceptsell'
398        if self.player_inventory[item_name]['quantity'] > 1:
399            self.player_inventory[item_name]['quantity'] -= 1
400        else:
401            del self.player_inventory[self.item_to_be_sold['type']]
402
403    def reject_insufficient_gold(self, keys, current_time):
404        """Reject player selection if they do not have enough gold"""
405        dialogue = ["You don't have enough gold!"]
406        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
407
408        if keys[pg.K_SPACE] and self.allow_input:
409            self.notify(c.CLICK2)
410            self.state = self.begin_new_transaction()
411            self.selection_arrow.rect.topleft = self.arrow_pos1
412            self.allow_input = False
413
414        if not keys[pg.K_SPACE]:
415            self.allow_input = True
416
417    def accept_purchase(self, keys, current_time):
418        """Accept purchase and confirm with message"""
419        self.dialogue_box = self.make_dialogue_box(self.accept_dialogue, 0)
420        self.gold_box = self.make_gold_box()
421
422        if keys[pg.K_SPACE] and self.allow_input:
423            self.notify(c.CLICK2)
424            self.state = self.begin_new_transaction()
425            self.selection_arrow.rect.topleft = self.arrow_pos1
426            self.allow_input = False
427
428        if not keys[pg.K_SPACE]:
429            self.allow_input = True
430
431    def accept_sale(self, keys, current_time):
432        """Confirm to player that item was sold"""
433        self.dialogue_box = self.make_dialogue_box(self.accept_sale_dialogue, 0)
434        self.gold_box = self.make_gold_box()
435
436        if keys[pg.K_SPACE] and self.allow_input:
437            self.notify(c.CLICK2)
438            self.state = self.begin_new_transaction()
439            self.selection_arrow.rect.topleft = self.arrow_pos1
440            self.allow_input = False
441
442        if not keys[pg.K_SPACE]:
443            self.allow_input = True
444
445
446    def has_item(self, keys, current_time):
447        """Tell player he has item already"""
448        dialogue = ["You have that item already."]
449        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
450
451        if keys[pg.K_SPACE] and self.allow_input:
452            self.state = self.begin_new_transaction()
453            self.selection_arrow.rect.topleft = self.arrow_pos1
454            self.allow_input = False
455            self.notify(c.CLICK2)
456
457        if not keys[pg.K_SPACE]:
458            self.allow_input = True
459
460
461    def buy_sell(self, keys, current_time):
462        """Ask player if they want to buy or sell something"""
463        dialogue = ["Would you like to buy or sell an item?"]
464        choices = ['Buy', 'Sell', 'Leave']
465        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
466        self.selection_box = self.make_selection_box(choices)
467        self.selection_arrow.rect.topleft = self.arrow_pos_list[self.arrow_index]
468
469        if keys[pg.K_DOWN] and self.allow_input:
470            if self.arrow_index < (len(self.arrow_pos_list) - 1):
471                self.arrow_index += 1
472                self.allow_input = False
473                self.notify(c.CLICK)
474
475        elif keys[pg.K_UP] and self.allow_input:
476            if self.arrow_index > 0:
477                self.arrow_index -= 1
478                self.allow_input = False
479                self.notify(c.CLICK)
480        elif keys[pg.K_SPACE] and self.allow_input:
481            if self.arrow_index == 0:
482                self.state = 'select'
483                self.allow_input = False
484                self.arrow_index = 0
485            elif self.arrow_index == 1:
486                if self.check_for_sellable_items():
487                    self.state = 'sell'
488                    self.allow_input = False
489                    self.arrow_index = 0
490                else:
491                    self.state = 'cantsell'
492                    self.allow_input = False
493                    self.arrow_index = 0
494            else:
495                self.level.state = 'transition out'
496                self.game_data['last state'] = self.level.name
497
498            self.arrow_index = 0
499            self.notify(c.CLICK2)
500
501        if not keys[pg.K_SPACE] and not keys[pg.K_DOWN] and not keys[pg.K_UP]:
502            self.allow_input = True
503
504    def check_for_sellable_items(self):
505        """Check for sellable items"""
506        for item in self.player_inventory:
507            if item in self.sellable_items:
508                return True
509        else:
510            return False
511
512    def sell_items(self, keys, current_time):
513        """Have player select items to sell"""
514        dialogue = ["What would you like to sell?"]
515        choices = []
516        item_list = []
517        for item in self.items:
518            if item['type'] in self.player_inventory:
519                name = item['type']
520                price = " (" + str(item['price'] / 2) + " gold)"
521                choices.append(name + price)
522                item_list.append(name)
523        choices.append('Cancel')
524        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
525        self.selection_box = self.make_selection_box(choices)
526
527        if len(choices) == 2:
528            self.selection_arrow.rect.topleft = self.two_arrow_pos_list[self.arrow_index]
529        elif len(choices) == 3:
530            self.selection_arrow.rect.topleft = self.arrow_pos_list[self.arrow_index]
531
532        if keys[pg.K_DOWN] and self.allow_input:
533            if self.arrow_index < (len(self.arrow_pos_list) - 1):
534                self.arrow_index += 1
535                self.allow_input = False
536                self.notify(c.CLICK)
537        elif keys[pg.K_UP] and self.allow_input:
538            if self.arrow_index > 0:
539                self.arrow_index -= 1
540                self.allow_input = False
541                self.notify(c.CLICK)
542        elif keys[pg.K_SPACE] and self.allow_input:
543            if self.arrow_index == 0:
544                self.state = 'confirmsell'
545                self.allow_input = False
546                for item in self.items:
547                    if item['type'] == item_list[0]:
548                        self.item_to_be_sold = item
549
550            elif self.arrow_index == 1 and len(choices) == 3:
551                self.state = 'confirmsell'
552                self.allow_input = False
553                for item in self.items:
554                    if item['type'] == item_list[1]:
555                        self.item_to_be_sold = item
556            else:
557                self.state = 'buysell'
558                self.allow_input = False
559            self.arrow_index = 0
560            self.notify(c.CLICK2)
561
562        if not keys[pg.K_SPACE] and not keys[pg.K_DOWN] and not keys[pg.K_UP]:
563            self.allow_input = True
564
565
566    def cant_sell(self, keys, current_time):
567        """Do not allow player to sell anything"""
568        dialogue = ["You don't have anything to sell!"]
569        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
570
571        if keys[pg.K_SPACE] and self.allow_input:
572            self.state = 'buysell'
573            self.allow_input = False
574            self.notify(c.CLICK2)
575
576
577        if not keys[pg.K_SPACE]:
578            self.allow_input = True
579
580    def cant_sell_equipped_weapon(self, keys, *args):
581        """
582        Do not sell weapon the player has equipped.
583        """
584        dialogue = ["You can't sell an equipped weapon."]
585        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
586
587        if keys[pg.K_SPACE] and self.allow_input:
588            self.state = 'buysell'
589            self.allow_input = False
590            self.notify(c.CLICK2)
591
592        if not keys[pg.K_SPACE]:
593            self.allow_input = True
594
595    def cant_sell_equipped_armor(self, keys, *args):
596        """
597        Do not sell armor the player has equipped.
598        """
599        dialogue = ["You can't sell equipped armor."]
600        self.dialogue_box = self.make_dialogue_box(dialogue, 0)
601
602        if keys[pg.K_SPACE] and self.allow_input:
603            self.state = 'buysell'
604            self.allow_input = False
605
606        if not keys[pg.K_SPACE]:
607            self.allow_input = True
608
609
610
611    def update(self, keys, current_time):
612        """Updates the shop GUI"""
613        state_function = self.state_dict[self.state]
614        state_function(keys, current_time)
615
616
617    def draw(self, surface):
618        """Draw GUI to level surface"""
619        state_list1 = ['dialogue', 'reject', 'accept', 'hasitem']
620        state_list2 = ['select', 'confirmpurchase', 'buysell', 'sell', 'confirmsell']
621
622        surface.blit(self.dialogue_box.image, self.dialogue_box.rect)
623        surface.blit(self.gold_box.image, self.gold_box.rect)
624        if self.state in state_list2:
625            surface.blit(self.selection_box.image, self.selection_box.rect)
626            surface.blit(self.selection_arrow.image, self.selection_arrow.rect)
627