from OptionalUtils import get from typing import Optional from Vec import Vec2 from Game import Game from Box import Box from Door import Door from PressurePlate import PressurePlate from Trail import Trail from pygame import Surface import pygame class GameView: def __init__(self, timeBased: bool = False): self.timeBased = timeBased self.game = Game([ """#####O##### # # # # # # # # # # # # # # # # # # # # # # # # #####I#####""", """#####D##### # + # # _ # # # # # # # # # # # # # # # #####I#####""", """#####D##### # + # # + # # + # # + # # + # # b _ # # # # # # # #####I#####""", """#####D##### # #+# # # #+# # # #+# # # #+# # # b _ # # # # # # # # # #####I#####""", """#####D##### #+++++ # #+ # #+ # #_ # #####D##### # + # # b + # # + # # _ # #####I#####""", """########### # # # # # # # # # # # # # # # # # # #####I#####""", ]) self.cellWidth = 64 self._tickTime = 700 self._previousTick = -10*self._tickTime self.nextControlDirection: Optional[Vec2] = None def isRunning(self) -> bool: #return not self.game.isLost() return True def width(self) -> int: return self.game.level.width() * self.cellWidth def height(self) -> int: return self.game.level.height() * self.cellWidth def render(self, surface: Surface) -> None: surface.fill("black") for cell in self.game.level.walls.walls(): self._drawBoxOfColor(surface, "white", cell.x, cell.y) for static in self.game.level.statics: match static: case Door(): if static.isOpen(): self._drawBoxOfColor(surface, "lightgray", static.pos.x, static.pos.y) else: self._drawBoxOfColor(surface, "gray", static.pos.x, static.pos.y) case PressurePlate(): self._drawBoxOfColor(surface, "yellow", static.pos.x, static.pos.y) case Trail(): if static.isOn(): self._drawBoxOfColor(surface, "pink", static.pos.x, static.pos.y) else: self._drawBoxOfColor(surface, "purple", static.pos.x, static.pos.y) for box in self.game.level.boxes: self._drawBoxOfColor(surface, "brown", box.pos.x, box.pos.y) for cell in self.game.level.snake.cells: self._drawBoxOfColor(surface, "red", cell.x, cell.y) def _drawBoxOfColor(self, surface: Surface, color: str, x: int, y: int) -> None: pygame.draw.rect(surface, color, pygame.Rect( x*self.cellWidth, y*self.cellWidth, self.cellWidth, self.cellWidth )) def update(self, time: int) -> None: if self.timeBased and (self._previousTick + self._tickTime <= time): self._previousTick = time match self.nextControlDirection: case None: None case _: self.game.level.snake.heading = self.nextControlDirection self.nextControlDirection = None self.game.tick() elif not self.timeBased: match self.nextControlDirection: case None: None case _: self._previousTick = time self.game.level.snake.heading = self.nextControlDirection self.nextControlDirection = None self.game.tick() if self.game.level.isCompleted(): self.game.nextLevel() if self.game.isLost(): self.game.restartLevel()