summaryrefslogtreecommitdiff
path: root/Game.py
blob: 7e5cb1d9ff33e171ff8fddd590a960e28d382ab9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

from typing import Optional, Union

import Vec

from OptionalUtils import exists
from Snake import Snake
from Vec import Vec2 
import Vec
from Box import Box
from Door import Door
from PressurePlate import PressurePlate
from Trail import Trail
from Walls import Walls
Static = Union[PressurePlate, Trail, Door]


class Game:
    """Class responsible for the main logic of a game.
       For a game, this will probably be a singleton."""
    

    def __init__(self, levels: list[str]):
        self.snake: Optional[Snake] = None
        self.boxes: list[Box] = []
        self.statics: list[Static] = []
        self.walls: Walls = Walls.empty()
        self.levelIn: Optional['Vec2'] = None
        self.level = -1
        self.levels = []
        self.levels = levels
        self.nextLevel()


    def nextLevel(self) -> None:
        self.level += 1
        self.walls = Walls.fromString(self.levels[self.level])
        self.snake = None
        self.statics = []
        self.boxes = []

        y = 0
        for line in self.levels[self.level].split('\n'):
            x = 0
            for char in line:
                if char == "b":
                    self.boxes.append(Box(Vec.Vec2(x, y)))
                elif char == "D":
                    if self.doorAt(Vec.Vec2(x, y)) == None:
                        self.statics.append(Door(Vec.Vec2(x, y)))
                elif char == "_":
                    self.parseSwitchTrail(self.levels[self.level], Vec.Vec2(x, y))
                elif char == "I":
                    self.levelIn = Vec.Vec2(x, y)
                x += 1
            y += 1

        match self.levelIn:
            case None: raise ValueError("level must have entrance")
            case Vec2: self.snake = Snake([self.levelIn, self.levelIn, self.levelIn, self.levelIn], self)

        self.statics.append(Door(self.levelIn))
        self.snake.heading = Vec.up


    def parseSwitchTrail(self, levelStr: str, platePos: Vec2) -> None:
        level = levelStr.split('\n')
        startSwitch = None
        if level[platePos.y][platePos.x] == "_":
            startSwitch = PressurePlate(platePos)
            self.statics.append(startSwitch)
        else:
            raise ValueError

        visited = []
        def inner(pos: Vec2) -> Optional[Static]:
            visited.append(pos)
            if level[pos.y][pos.x] == "+":
                directions = filter(lambda p: not p in visited,
                                 map(lambda p: pos + p,
                                     [Vec.up, Vec.down, Vec.left, Vec.right]
                                 )
                             )
                nextIter = filter(lambda x: x != None, map(lambda x: inner(x), directions))
                nextPart = next(nextIter)
                #assert len(nextPart) == 1
                match nextPart:
                    case Trail() | Door():
                        trail = Trail(pos, nextPart)
                        self.statics.append(trail)
                        return trail
                    case _: raise ValueError(f"trails must be followed by doors or trails, not {nextPart}")
            elif level[pos.y][pos.x] == "_" and pos == platePos:
                directions = filter(lambda p: not p in visited,
                                 map(lambda p: pos + p,
                                     [Vec.up, Vec.down, Vec.left, Vec.right]
                                 )
                             )
                nextIter = filter(lambda x: x != None, map(lambda x: inner(x), directions))
                for tr in nextIter:
                    match tr:
                        case Door() | Trail(): startSwitch.addTrail(tr)
                        case _: raise ValueError(f"plates must be followed by doors or trails, not {tr}")

            elif level[pos.y][pos.x] == "D":
                door = self.doorAt(pos)
                if door != None:
                    return door

                door = Door(pos)
                self.statics.append(door)
                return door
            return None

        inner(platePos)
        for static in self.statics:
            match static:
                case PressurePlate():
                    trailString = map( lambda x: x.pos.toString(), static._trails)


    def width(self) -> int:
        return self.walls.width()
    def height(self) -> int:
        return self.walls.height()


    def _movableSolidAt(self, pos: Vec2) -> bool:
        match self.snake:
            case Snake():
                if pos in self.snake.cells:
                    return True
        return pos in map(lambda box: box.pos, self.boxes)

    def tick(self) -> None:
        match self.snake:
            case Snake():
                self.snake.move()

                lastSnakeCell = self.snake.cells[0]#[len(self.snake.cells) - 1]
                if (lastSnakeCell.x < 0 or lastSnakeCell.x >= self.width()) or (lastSnakeCell.y < 0 or lastSnakeCell.y >= self.height()):
                    self.nextLevel()
                    return 

        for static in self.statics:
            match static:
                case PressurePlate():
                    if static.isActive() and not self._movableSolidAt(static.pos):
                        static.deactivate()
                    elif (not static.isActive()) and self._movableSolidAt(static.pos):
                        static.activate()
        for static in self.statics:
            match static:
                case Door():
                    if static.isOpen() and not static.isActive():
                        if not self._movableSolidAt(static.pos):
                            static.close()


    def isLost(self) -> bool:
        match self.snake:
            case Snake(): return self.snake.hasCollided
            case _: return False


    def doorAt(self, pos: Vec2) -> Optional[Door]:
        for static in self.statics:
            match static:
                case Door():
                    if static.pos == pos:
                        return static
        return None


    def closedDoorAt(self, pos: Vec2) -> bool:
        res = False
        for static in self.statics:
            match static:
                case Door():
                    res = res or (static.pos == pos and not static.isOpen())
        return res

    def switchAt(self, pos: Vec2) -> Optional[PressurePlate]:
        for static in self.statics:
            match static:
                case PressurePlate():
                    if static.pos == pos:
                        return static
        return None


    def enter(self, pos: Vec2, inDir: Vec2) -> bool:
        boxAt = next(filter(lambda box: box.pos == pos, self.boxes), None)
        if self.walls.wallAt(pos) or self.closedDoorAt(pos):
            return False
        elif exists(self.snake, lambda s: pos in s.cells):
            return False
        else:
            match boxAt:
                case None: return True
                case _:
                    if self.enter(pos + inDir, inDir):
                        boxAt.pos = pos + inDir
                        return True
                    else:
                        return False