labyrinth.py 2.11 KB
Newer Older
Constantin's avatar
Constantin committed
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
# class for the labyrinth

from enum import Enum

class Labyrinth:
	class GroundType(Enum):
		FLOOR = 1
		WALL  = 2
		
	class Field:
		def __init__(self,groundtype,column,row,labyrinth):
			# please only read from these members
			self.groundtype = groundtype
			self.column = column
			self.row = row
			self.labyrinth = labyrinth
			# the following usually change
			self.things = [] # list of things/players on this field
		def _removeThing(self,thing):
			self.things.remove(thing)
		def _addThing(self,thing):
			assert self.things.count(thing) == 0
			assert self.groundtype != Labyrinth.GroundType.WALL
			self.things.append(thing)
		def toString(self):
			# always starts with there is/there are
			if self.groundtype == Labyrinth.GroundType.WALL:
				return "there is a wall"
			else:
				if len(self.things) == 0:
					return "there is nothing"
				elif len(self.things) == 1:
					return "there is "+self.things[0].toString()
				else:
					return "there are "+(", ".join([x.toString() for x in self.things[:-1]]))+" and "+self.things[-1].toString()
	
	# constructor for a completely read labyrinth
	def __init__(self,width=None,height=None,stream=None):
		if width is not None: # empty labyrinth of given size
			assert height is not None
			assert stream is None
Constantin's avatar
Constantin committed
42
			self.tiles = [[Labyrinth.Field(Labyrinth.GroundType.FLOOR,col,row,self) for col in range(width)] for row in range(height)]
Constantin's avatar
Constantin committed
43
44
45
46
47
48
49
50
51
52
53
		elif height is not None:
			assert False # width None, height not
		elif stream is not None:
			self.tiles = self._readlab(stream)
	
	# function for reading a labyrinth from a file
	def _readlab (self,stream):
		tiles = []
		for rownum,line in enumerate(stream):
			row = []
			for colnum,char in enumerate(line):
Constantin's avatar
Constantin committed
54
55
				if char in [' ','0','_']:
					row.append(Labyrinth.Field(Labyrinth.GroundType.FLOOR,colnum,rownum,self))
Constantin's avatar
Constantin committed
56
				elif char in ['W','w','#','1']:
Constantin's avatar
Constantin committed
57
					row.append(Labyrinth.Field(Labyrinth.GroundType.WALL,colnum,rownum,self))
Constantin's avatar
Constantin committed
58
59
60
61
62
63
64
65
			tiles.append(row)
		return tiles
	
	def onThingMoved (self, thing, oldField, newField):
		assert oldField.labyrinth == self
		assert newField.labyrinth == self
		oldField._removeThing(thing)
		newField._addThing(thing)