all repos — Legends-RPG @ 9e643337e6380fdb1ab32813bf8848ad7e7219c8

A fantasy mini-RPG built with Python and Pygame.

data/tools.py (view raw)

  1__author__ = 'justinarmstrong'
  2
  3import os, random
  4import pygame as pg
  5from . import constants as c
  6
  7class Control(object):
  8    """
  9    Control class for entire project.  Contains the game loop, and contains
 10    the event_loop which passes events to States as needed.  Logic for flipping
 11    states is also found here.
 12    """
 13    def __init__(self, caption):
 14        self.screen = pg.display.get_surface()
 15        self.done = False
 16        self.clock = pg.time.Clock()
 17        self.caption = caption
 18        self.fps = 60
 19        self.show_fps = False
 20        self.current_time = 0.0
 21        self.keys = pg.key.get_pressed()
 22        self.state_dict = {}
 23        self.state_name = None
 24        self.state = None
 25
 26    def setup_states(self, state_dict, start_state):
 27        self.state_dict = state_dict
 28        self.state_name = start_state
 29        self.state = self.state_dict[self.state_name]
 30        self.set_music()
 31
 32    def update(self):
 33        self.current_time = pg.time.get_ticks()
 34        if self.state.quit:
 35            self.done = True
 36        elif self.state.done:
 37            self.flip_state()
 38        self.state.update(self.screen, self.keys, self.current_time)
 39
 40    def flip_state(self):
 41        previous, self.state_name = self.state_name, self.state.next
 42        previous_music = self.state.music_title
 43        persist = self.state.cleanup()
 44        self.state = self.state_dict[self.state_name]
 45        self.state.previous = previous
 46        self.state.previous_music = previous_music
 47        self.state.startup(self.current_time, persist)
 48        self.set_music()
 49
 50    def set_music(self):
 51        """
 52        Set music for the new state.
 53        """
 54        if self.state.music_title == self.state.previous_music:
 55            pass
 56        elif self.state.music:
 57            pg.mixer.music.load(self.state.music)
 58            pg.mixer.music.set_volume(self.state.volume)
 59            pg.mixer.music.play(-1)
 60
 61    def event_loop(self):
 62        self.events = pg.event.get()
 63
 64        for event in self.events:
 65            if event.type == pg.QUIT:
 66                self.done = True
 67            elif event.type == pg.KEYDOWN:
 68                self.keys = pg.key.get_pressed()
 69                self.toggle_show_fps(event.key)
 70                self.state.get_event(event)
 71            elif event.type == pg.KEYUP:
 72                self.keys = pg.key.get_pressed()
 73                self.state.get_event(event)
 74
 75    def toggle_show_fps(self, key):
 76        if key == pg.K_F5:
 77            self.show_fps = not self.show_fps
 78            if not self.show_fps:
 79                pg.display.set_caption(self.caption)
 80
 81    def main(self):
 82        """Main loop for entire program"""
 83        while not self.done:
 84            self.event_loop()
 85            self.update()
 86            pg.display.update()
 87            self.clock.tick(self.fps)
 88            if self.show_fps:
 89                fps = self.clock.get_fps()
 90                with_fps = "{} - {:.2f} FPS".format(self.caption, fps)
 91                pg.display.set_caption(with_fps)
 92
 93
 94class _State(object):
 95    """Base class for all game states"""
 96    def __init__(self):
 97        self.start_time = 0.0
 98        self.current_time = 0.0
 99        self.done = False
100        self.quit = False
101        self.next = None
102        self.previous = None
103        self.game_data = {}
104        self.music = None
105        self.music_title = None
106        self.previous_music = None
107
108    def get_event(self, event):
109        pass
110
111    def startup(self, current_time, game_data):
112        self.game_data = game_data
113        self.start_time = current_time
114
115    def cleanup(self):
116        self.done = False
117        return self.game_data
118
119    def update(self, surface, keys, current_time):
120        pass
121
122
123def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', 'jpg', 'bmp')):
124    graphics = {}
125    for pic in os.listdir(directory):
126        name, ext = os.path.splitext(pic)
127        if ext.lower() in accept:
128            img = pg.image.load(os.path.join(directory, pic))
129            if img.get_alpha():
130                img = img.convert_alpha()
131            else:
132                img = img.convert()
133                img.set_colorkey(colorkey)
134            graphics[name] = img
135    return graphics
136
137
138def load_all_music(directory, accept=('.wav', '.mp3', '.ogg', '.mdi')):
139    songs = {}
140    for song in os.listdir(directory):
141        name, ext = os.path.splitext(song)
142        if ext.lower() in accept:
143            songs[name] = os.path.join(directory, song)
144    return songs
145
146
147def load_all_fonts(directory, accept=('.ttf')):
148    return load_all_music(directory, accept)
149
150
151def load_all_tmx(directory, accept=('.tmx')):
152    return load_all_music(directory, accept)
153
154
155def load_all_sfx(directory, accept=('.wav','.mp3','.ogg','.mdi')):
156    effects = {}
157    for fx in os.listdir(directory):
158        name, ext = os.path.splitext(fx)
159        if ext.lower() in accept:
160            effects[name] = pg.mixer.Sound(os.path.join(directory, fx))
161    return effects
162
163
164def get_image(x, y, width, height, sprite_sheet):
165    """Extracts image from sprite sheet"""
166    image = pg.Surface([width, height])
167    rect = image.get_rect()
168
169    image.blit(sprite_sheet, (0, 0), (x, y, width, height))
170    image.set_colorkey(c.BLACK)
171
172    return image
173
174def get_tile(x, y, tileset, width=16, height=16, scale=1):
175    """Gets the surface and rect for a tile"""
176    surface = get_image(x, y, width, height, tileset)
177    surface = pg.transform.scale(surface, (int(width*scale), int(height*scale)))
178    rect = surface.get_rect()
179
180    tile_dict = {'surface': surface,
181                 'rect': rect}
182
183    return tile_dict
184
185def notify_observers(self, event):
186    """
187    Notify all observers of events.
188    """
189    for each_observer in self.observers:
190        each_observer.on_notify(event)
191
192def create_game_data_dict():
193    """Create a dictionary of persistant values the player
194    carries between states"""
195
196    player_items = {'GOLD': dict([('quantity',100),
197                                  ('value',0)]),
198                    'Healing Potion': dict([('quantity',2),
199                                            ('value',15)]),
200                    'Ether Potion': dict([('quantity',1),
201                                          ('value', 15)]),
202                    'Rapier': dict([('quantity', 1),
203                                    ('value', 50),
204                                    ('power', 9)]),
205                    'equipped weapon': 'Rapier',
206                    'equipped armor': []}
207
208    player_health = {'current': 70,
209                     'maximum': 70}
210
211    player_magic = {'current': 70,
212                    'maximum': 70}
213
214    player_stats = {'health': player_health,
215                    'Level': 1,
216                    'experience to next level': 30,
217                    'magic': player_magic,
218                    'attack points': 10,
219                    'Defense Points': 10}
220
221
222    data_dict = {'last location': None,
223                 'last state': None,
224                 'last direction': 'down',
225                 'king item': 'GOLD',
226                 'old man item': {'ELIXIR': dict([('value',1000),
227                                                  ('quantity',1)])},
228                 'player inventory': player_items,
229                 'player stats': player_stats,
230                 'battle counter': 50,
231                 'treasure1': True,
232                 'treasure2': True,
233                 'treasure3': True,
234                 'treasure4': True,
235                 'treasure5': True,
236                 'start of game': True,
237                 'talked to king': False,
238                 'brother quest complete': False,
239                 'talked to sick brother': False,
240                 'has brother elixir': False,
241                 'elixir received': False,
242                 'old man gift': '',
243                 'battle type': '',
244                 'crown quest': False,
245                 'delivered crown': False,
246                 'brother item': 'ELIXIR'
247    }
248
249    return data_dict
250
251
252
253
254
255
256