1 /* 2 Copyright © 2020, Luna Nielsen 3 Distributed under the 2-Clause BSD License, see LICENSE file. 4 5 Authors: Luna Nielsen 6 */ 7 module engine.core.state; 8 9 /** 10 Manager of game states 11 */ 12 class GameStateManager { 13 private static: 14 GameState[] states; 15 16 public static: 17 18 /** 19 Update the current game state 20 */ 21 void update() { 22 if (states.length == 0) return; 23 states[$-1].update(); 24 } 25 26 /** 27 Draw the current game state 28 29 Offset sets the offset from the top of the stack to draw 30 */ 31 void draw(size_t offset = 1) { 32 if (states.length == 0) return; 33 34 // Handle drawing passthrough, this allows us to draw game boards with game over screen overlayed. 35 if (states[$-offset].drawPassthrough && states.length > offset) { 36 states[$-offset].draw(); 37 } 38 39 // Draw the current state 40 states[$-offset].draw(); 41 } 42 43 /** 44 Push a game state on to the stack 45 */ 46 void push(GameState state) { 47 states ~= state; 48 states[$-1].onActivate(); 49 } 50 51 /** 52 Pop a game state from the stack 53 */ 54 void pop() { 55 if (canPop) { 56 states[$-1].onDeactivate(); 57 states.length--; 58 } 59 } 60 61 /** 62 Gets whether an element can be popped from the game state stack 63 */ 64 bool canPop() { 65 return states.length > 0; 66 } 67 68 /** 69 Pop a game state from the stack 70 */ 71 void popAll() { 72 while (canPop) pop(); 73 } 74 75 } 76 77 /** 78 A game state 79 */ 80 abstract class GameState { 81 public: 82 /** 83 Wether drawing should pass-through to the previous game state (if any) 84 This allows overlaying a gamr state over an other 85 */ 86 bool drawPassthrough; 87 88 /** 89 Update the game state 90 */ 91 abstract void update(); 92 93 /** 94 Draw the game state 95 */ 96 abstract void draw(); 97 98 /** 99 When a state is pushed 100 */ 101 void onActivate() { } 102 103 /** 104 Called when a state is popped 105 */ 106 void onDeactivate() { } 107 }