allow vim keybindings and add pause key
authorGeoffrey Allott <geoff@Geoffreys-MacBook-Air.local>
Fri, 2 Dec 2022 20:14:36 +0000 (20:14 +0000)
committerGeoffrey Allott <geoff@Geoffreys-MacBook-Air.local>
Fri, 2 Dec 2022 20:14:36 +0000 (20:14 +0000)
snake.py

index b70afa8f885ce5d2a0120a281ad20369eae24e2d..ebf842d8b5aace3b374df410626bf6b5ab843cb2 100644 (file)
--- a/snake.py
+++ b/snake.py
@@ -81,27 +81,29 @@ class GameArea:
     
     def getch(self):
         ch = self.win.getch()
-        if ch == curses.KEY_LEFT:
+        if ch == curses.KEY_LEFT or ch == ord('h'):
             if self.dir == Direction.Right:
                 print('\a', end='')
             else:
                 self.dir = Direction.Left
-        if ch == curses.KEY_RIGHT:
+        if ch == curses.KEY_RIGHT or ch == ord('l'):
             if self.dir == Direction.Left:
                 print('\a', end='')
             else:
                 self.dir = Direction.Right
-        if ch == curses.KEY_UP:
+        if ch == curses.KEY_UP or ch == ord('k'):
             if self.dir == Direction.Down:
                 print('\a', end='')
             else:
                 self.dir = Direction.Up
-        if ch == curses.KEY_DOWN:
+        if ch == curses.KEY_DOWN or ch == ord('j'):
             if self.dir == Direction.Up:
                 print('\a', end='')
             else:
                 self.dir = Direction.Down
-        if ch == 27 or ch == ord('q'):
+        if ch == 27 or ch == ord('p'):
+            self.pause()
+        if ch == ord('q'):
             curses.endwin()
             sys.exit(0)
 
@@ -150,6 +152,23 @@ class GameArea:
         os.makedirs(os.path.dirname(self.highscore_file), exist_ok=True)
         with open(self.highscore_file, 'w') as f:
             f.write(f'{self.highscore}\n')
+
+    def pause(self):
+        self.paint()
+        height, width = self.win.getmaxyx()
+        self.win.addstr(height // 2, (width - 6) // 2, 'PAUSED')
+        self.win.refresh()
+        sleep(1)
+        self.win.nodelay(False)
+        while True:
+            ch = self.win.getch()
+            if ch == 27 or ch == ord('p'):
+                break
+            if ch == ord('q'):
+                curses.endwin()
+                sys.exit(0)
+        self.win.nodelay(True)
+        self.paint()
     
     def game_over(self):
         self.paint()