diff options
| author | Joel Kronqvist <joel.kronqvist@iki.fi> | 2025-10-26 12:52:34 +0200 |
|---|---|---|
| committer | Joel Kronqvist <joel.kronqvist@iki.fi> | 2025-10-26 12:52:34 +0200 |
| commit | 57f20a5ef761985b34817846d471a064b180e089 (patch) | |
| tree | 9d0029868b9e170bf07ffab9e0386b06b4189837 /Game.py | |
| download | SnakePuzzle-57f20a5ef761985b34817846d471a064b180e089.tar.gz SnakePuzzle-57f20a5ef761985b34817846d471a064b180e089.zip | |
feat: implemented simple snake game
Diffstat (limited to 'Game.py')
| -rw-r--r-- | Game.py | 68 |
1 files changed, 68 insertions, 0 deletions
@@ -0,0 +1,68 @@ + +from Snake import Snake +from Vec import Vec2 + +class Walls: + """Contains the walls of a game. + Supports iterating over the walls and checking if there is a wall at a specific coordinate. + Useful as a wrapper to later increase performance of these operations.""" + + _walls = [] + + def __init__(self, walls): + self._walls = walls + + def fromString(wallString): + walls = [] + y = 0 + for line in wallString.split('\n'): + x = 0 + for char in line: + if char == "#": + walls.append(Vec2(x, y)) + x += 1 + y += 1 + return Walls(walls) + + def walls(self): + return self._walls + + def wallAt(self, pos): + return (pos in self._walls) + + def width(self): + return max(self._walls, key=lambda p: p.x).x + 1 + + def height(self): + return max(self._walls, key=lambda p: p.y).y + 1 + + +class Game: + """Class responsible for the main logic of a game. + For a game, this will probably be a singleton.""" + + snake = Snake([Vec2(6, 6), Vec2(6, 7), Vec2(6,8), Vec2(7,8)]) + walls = Walls.fromString("""############### +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# ### # +# # +###############""") + + def width(self): return self.walls.width() + def height(self): return self.walls.height() + + def tick(self): + self.snake.move() + + def isLost(self): + return self.snake.headInTail() or self.walls.wallAt(self.snake.head()) + |
