common.py (2636B)
1 import json 2 import os 3 4 from enum import Enum 5 6 7 WIDTH, HEIGHT = 500, 800 8 9 HELP_CONTENTS = ( 10 'Controls:\n' 11 'w: move player ship up\n' 12 'a: move player ship left\n' 13 's: move player ship down\n' 14 'd: move player ship right\n' 15 'j: primary attack\n' 16 'k: secondary attack\n' 17 'Escape: pause menu\n' 18 'Space: boss key' 19 ) 20 21 BOSS_KEY_IMAGE_FPATH = 'assets/out/boss_image_v2.gif' 22 SCORE_FPATH = 'scores.scr' 23 24 STATE_FPATH = 'state.stt' 25 26 27 def gamestate_is_valid(state): 28 if state is None or \ 29 state.get('score', None) is None or state.get('lives', None) is None: 30 return False 31 32 return True 33 34 35 def pack_gamestate(score, lives): 36 if score is None or lives is None: 37 return None 38 39 return {'score': int(score), 'lives': int(lives)} 40 41 42 def load_gamestate(fpath): 43 if not os.path.isfile(fpath): 44 return None 45 46 try: 47 with open(fpath, 'r') as f: 48 serialised = f.read() 49 d = json.loads(serialised) 50 51 score = d.get('score', None) 52 lives = d.get('lives', None) 53 54 return pack_gamestate(score, lives) 55 56 except Exception as err: 57 print(err) 58 59 return None 60 61 62 def save_gamestate(fpath, score, lives): 63 with open(fpath, 'w') as f: 64 serialised = json.dumps(pack_gamestate(score, lives)) 65 f.write(f'{serialised}\n') 66 67 68 BLACK = '#000000' 69 WHITE = '#ffffff' 70 RED = '#ff0000' 71 YELLOW = '#ffff00' 72 GREEN = '#00ff00' 73 CYAN = '#00ffff' 74 BLUE = '#0000ff' 75 MAGENTA = '#ff00ff' 76 77 #SEVERITY = 2 ## turns off no messages 78 #SEVERITY = 1 ## turns off debug messages 79 #SEVERITY = 0 ## turns off debug and warning messages 80 SEVERITY = -1 ## turns off all messages 81 82 83 def debug(msg): 84 if SEVERITY >= 2: 85 print(f'DEBUG: {msg}') 86 87 88 def warn(msg): 89 if SEVERITY >= 1: 90 print(f'WARNING: {msg}') 91 92 93 def critical(msg): 94 if SEVERITY >= 0: 95 print(f'!!!CRITICAL!!!: {msg}') 96 97 98 class AutoId: 99 """ 100 Implements a stateful decorator to assign each decorated class a unique id. 101 """ 102 _component_id = 0 103 _system_id = 0 104 105 106 @classmethod 107 def component(cls, wrapped_cls): 108 wrapped_cls.cid = cls._component_id 109 cls._component_id += 1 110 111 return wrapped_cls 112 113 114 @classmethod 115 def system(cls, wrapped_cls): 116 wrapped_cls.sid = cls._system_id 117 cls._system_id += 1 118 119 return wrapped_cls 120 121 122 class EcsContinuation(Enum): 123 """ 124 Whether the ECS system should continue to the next iteration or stop. 125 """ 126 Stop = 0 127 Continue = 1 128