Strip newlines off map when loading
[erdslangetjie.git] / erdslangetjie / __main__.py
1 import sys
2 import os
3 import kivy
4
5 kivy.require('1.6.0')
6
7 from kivy.app import App
8 from kivy.uix.widget import Widget
9 from kivy.uix.floatlayout import FloatLayout
10 from kivy.graphics import Color, Rectangle
11
12 from erdslangetjie.data import filepath, load
13 from erdslangetjie.level import Level
14 from erdslangetjie.player import ThePlayer, Nemesis
15
16
17 class GameWindow(FloatLayout):
18
19     def __init__(self, level):
20         super(GameWindow, self).__init__(size=(960, 960))
21         if os.path.exists(filepath(level)):
22             level_data = load(level)
23             self.level = level
24         elif os.path.exists(filepath('levels/' + level)):
25             level_data = load('levels/' + level)
26             self.level = 'levels/' + level
27         else:
28             print 'Unable to find %s - treating this as a new level' % level
29             sys.exit(1)
30         self.level_obj = Level()
31         self.level_obj.load(level_data)
32         level_data.close()
33
34         self.player = ThePlayer()
35         self.level_obj.load_tiles()
36         if not self.level_obj.enter_pos:
37             raise RuntimeError('No entry point')
38
39         self.player.pos = self.level_obj.enter_pos
40
41     def build(self):
42         self.clear_widgets()
43         tiles = self.level_obj.get_tiles()
44         tile_size = 24
45         bx, by = 0, 0
46         for tile_line in tiles:
47             bx = 0
48             for tile in tile_line:
49                 node = Widget(size=(tile_size, tile_size), pos=(bx, by))
50                 with node.canvas:
51                     Color(1, 1, 1)
52                     Rectangle(pos=node.pos, size=node.size,
53                             texture=tile.texture)
54                 self.add_widget(node)
55                 bx += tile_size
56             by += tile_size
57
58         player_pos = (self.player.pos[0] * tile_size,
59                 self.player.pos[1] * tile_size)
60         player_tile = Widget(size=(tile_size, tile_size),
61                 pos=player_pos)
62         with player_tile.canvas:
63             Color(1, 1, 1)
64             Rectangle(pos=player_pos, size=player_tile.size,
65                     texture=self.player.sprite.texture)
66         self.add_widget(player_tile)
67
68
69 class GameApp(App):
70
71     def __init__(self):
72         self.level = 'level1.txt'
73         super(GameApp, self).__init__()
74
75     def build(self):
76         game = GameWindow(self.level)
77         game.build()
78         return game
79
80
81 def main():
82     """ Erdslangetjie, a maze game of eluding nemesis
83     """
84     GameApp().run()