add "r" to restart
authorGeoffrey Allott <geoffrey@allott.email>
Tue, 6 Dec 2022 19:27:01 +0000 (19:27 +0000)
committerGeoffrey Allott <geoffrey@allott.email>
Tue, 6 Dec 2022 19:27:01 +0000 (19:27 +0000)
snake.py

index dd1ec29a1812032aa787296ae1bc36dc9dfecd69..0a22166f40b22f659eaaa61db9d96b0554658605 100644 (file)
--- a/snake.py
+++ b/snake.py
@@ -8,6 +8,9 @@ from time import sleep
 class ExitGameException(BaseException):
     pass
 
+class RestartGameException(BaseException):
+    pass
+
 class TileContents(Enum):
     Empty = "Empty"
     Wall = "Wall"
@@ -110,6 +113,8 @@ class GameArea:
             self.pause()
         if ch == ord('q'):
             raise ExitGameException()
+        if ch == ord('r'):
+            raise RestartGameException()
 
     def random_empty_tile(self):
         return self.random.choice([
@@ -166,6 +171,8 @@ class GameArea:
                 break
             if ch == ord('q'):
                 raise ExitGameException()
+            if ch == ord('r'):
+                raise RestartGameException()
         self.win.nodelay(True)
         self.paint()
     
@@ -180,6 +187,8 @@ class GameArea:
             ch = self.win.getch()
             if ch == 27 or ch == ord('q'):
                 break
+            if ch == ord('r'):
+                raise RestartGameException()
         raise ExitGameException()
 
     def update(self):
@@ -255,19 +264,22 @@ def setup():
     return win
 
 if __name__ == '__main__':
-    win = setup()
-    gamearea = GameArea(win=win, highscore_file=os.path.expanduser('~/.local/snake/highscore'))
-    try:
-        while True:
-            gamearea.paint()
-            if not gamearea.turbo:
-                sleep(0.1)
-            else:
-                sleep(0.05)
-            gamearea.getch()
-            gamearea.update()
-    except ExitGameException:
-        pass
-    finally:
-        curses.endwin()
+    while True:
+        win = setup()
+        gamearea = GameArea(win=win, highscore_file=os.path.expanduser('~/.local/snake/highscore'))
+        try:
+            while True:
+                gamearea.paint()
+                if not gamearea.turbo:
+                    sleep(0.1)
+                else:
+                    sleep(0.05)
+                gamearea.getch()
+                gamearea.update()
+        except ExitGameException:
+            break
+        except RestartGameException:
+            continue
+        finally:
+            curses.endwin()