home · contact · privacy
Register game commands and tasks outside of game module.
[plomrogue2-experiments] / game_common.py
1 from parser import ArgError
2
3
4 class MapManager:
5
6     def __init__(self, map_classes):
7         """Collects tuple of basic Map[Geometry] classes."""
8         self.map_classes = map_classes
9
10     def get_map_geometries(self):
11         geometries = []
12         for map_class in self.map_classes:
13             geometries += [map_class.__name__[3:]]
14         return geometries
15
16     def get_map_class(self, geometry):
17         for map_class in self.map_classes:
18             if map_class.__name__[3:] == geometry:
19                 return map_class
20
21
22 class Map:
23
24     def __init__(self, size=(0, 0)):
25         self.size = size
26         self.terrain = '?'*self.size_i
27
28     @property
29     def size_i(self):
30         return self.size[0] * self.size[1]
31
32     def set_line(self, y, line):
33         height_map = self.size[0]
34         width_map = self.size[1]
35         if y >= height_map:
36             raise ArgError('too large row number %s' % y)
37         width_line = len(line)
38         if width_line > width_map:
39             raise ArgError('too large map line width %s' % width_line)
40         self.terrain = self.terrain[:y * width_map] + line +\
41                        self.terrain[(y + 1) * width_map:]
42
43     def get_position_index(self, yx):
44         return yx[0] * self.size[1] + yx[1]
45
46
47 class World:
48
49     def __init__(self):
50         self.Thing = Thing  # child classes may use an extended Thing class here
51         self.turn = 0
52         self.things = []
53
54     def get_thing(self, id_, create_unfound=True):
55         for thing in self.things:
56             if id_ == thing.id_:
57                 return thing
58         if create_unfound:
59             t = self.Thing(self, id_)
60             self.things += [t]
61             return t
62         return None
63
64     def new_map(self, geometry, yx):
65         map_type = self.game.map_manager.get_map_class(geometry)
66         self.map_ = map_type(yx)
67
68
69 class Thing:
70
71     def __init__(self, world, id_):
72         self.world = world
73         self.id_ = id_
74         self.type_ = '?'
75         self.position = [0,0]
76
77
78 class CommonCommandsMixin:
79
80     def cmd_MAP(self, geometry, yx):
81         """Create new map of grid geometry, size yx and only '?' cells."""
82         self.world.new_map(geometry, yx)
83     cmd_MAP.argtypes = 'string:geometry yx_tuple:pos'
84
85     def cmd_THING_TYPE(self, i, type_):
86         t = self.world.get_thing(i)
87         t.type_ = type_
88     cmd_THING_TYPE.argtypes = 'int:nonneg string'
89
90     def cmd_THING_POS(self, i, yx):
91         t = self.world.get_thing(i)
92         t.position = list(yx)
93     cmd_THING_POS.argtypes = 'int:nonneg yx_tuple:nonneg'