Commits

masci  committed 0aea9a5

handle gameover and IDLE state

  • Participants
  • Parent commits 49c8421

Comments (0)

Files changed (2)

             for dice in row.dicelist:
                 dice.blit(surface)
 
+    def clear(self):
+        self._rows = []
+
     def drop_row(self):
         """Instance a row of 5 dices and drop it into the board
 
 
 
 class Game(object):
+    """
+    
+    """
+    class GameState:
+        IDLE=0
+        RUNNING=1
+        QUITTING=2
+
     def __init__(self):
         self._running = False
         self._board = board.Board((0,0))
         self._bg = pygame.Surface((1280,960))
         self._clock = pygame.time.Clock()
-        self._dropspeed = 5000
-    
-    def start(self):
+        self._dropspeed = 500
+        self._state = self.GameState.IDLE
         pygame.init()
-        self._running = True
-        self._board.drop_row()
-        pygame.time.set_timer(pygame.USEREVENT, self._dropspeed)
+
+    def run(self):
+        """ Game Loop
         
-        while self._running:
-            pygame.key.set_repeat()
+        """
+        while self._state != self.GameState.QUITTING:
             event = pygame.event.poll()
-            if event.type == pygame.QUIT:
-                self._running = False
-            elif event.type == pygame.USEREVENT:
-                if not self._board.drop_row():
-                    self._gameover()
             self._handle_event(event)
-            self._board.check_line()
             self._draw_scene(screen)
             self._clock.tick(15)
 
+    def _handle_event(self, event):
+        """Handle events considering game state
+
+        """
+        if event.type == pygame.QUIT:
+            self._state = self.GameState.QUITTING
+        elif self._state == self.GameState.RUNNING:
+            if event.type == pygame.USEREVENT:
+                if not self._board.drop_row():
+                    self._gameover()
+            self._board.handle_event(event)
+            self._board.check_line()
+        elif self._state == self.GameState.IDLE:
+            if event.type == pygame.KEYDOWN:
+                self._start()
+        else:
+            assert 0
+
+    def _start(self):
+        """Init game and put it in RUNNING state
+
+        """
+        self._state = self.GameState.RUNNING
+        #self._running = True
+        self._board.drop_row()
+        pygame.time.set_timer(pygame.USEREVENT, self._dropspeed)
+
     def _gameover(self):
-        self._running = False
-        print 'GAME OVER!'
+        """Put game in IDLE state
 
-    def _handle_event(self, event):
-        self._board.handle_event(event)
+        """
+        self._state = self.GameState.IDLE
+        self._board.clear()
 
     def _draw_scene(self, surface):
         surface.fill(pygame.Color('black'))
 if __name__ == '__main__':
     screen = pygame.display.set_mode((1280, 960))
     pygame.display.set_caption("Five in a Row")
-
     g = Game()
-    g.start()
+    g.run()