Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Gambiarra/levels.py
blob: 9d16bd2066c5d29d72aa2371e6d46fc86ab64e97 (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# -*- coding: UTF-8 -*-
#
# Copyright (C) 2007 by ULPM: Alexandre Yukio Harano
#                             Fábio Cassarotti Parronchi Navarro
#                             Gabriel Geraldo França Marcondes
#                             Luiz Carlos Irber Júnior
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import pygame

import os

import simplejson as json

from Gambiarra.objects import *

from Gambiarra.command import Play, Help, Quit

class SimulationView(object):
    """ This widget holds the objects being simulated. """
    running = None
    background = None
    objects = None

    def __init__(self, objects):
        self.running = False
        self.background = pygame.Surface((1200, 770))
        self.background.fill([99, 157, 237])
        self.objects = pygame.sprite.RenderPlain()
        self.static_objs = []

        for obj in objects.values():
            if obj.mobility:
                obj.add(self.objects)
            else:
                self.static_objs.append(obj)

        self.static_objs.append(LeftWall())
        self.static_objs.append(RightWall())
        self.static_objs.append(UpWall())
        self.static_objs.append(DownWall())

    def draw(self, pos = None):
        screen = pygame.display.get_surface()
        if pos:
            screen.blit(self.background, (pos[0], pos[1]), pos)
        else:
            screen.blit(self.background, (0, 0))

        for obj in self.static_objs:
            obj.draw(screen, obj.rect)

        for item in self.objects:
            item.draw(screen, item.rect.topleft)

    def add(self, obj):
        if obj.mobility:
            obj.add(self.objects)
        else:
            self.static_objs.append(obj)

class ObjectBar(object):
    """ This widget contains the objects available for the problem. """

    def __init__(self, objects):
        self.background = pygame.Surface((1000, 130))
        self.background.fill([0, 255, 0])
        self.objects = pygame.sprite.RenderPlain(objects.values())

    def draw(self, pos = None):
        screen = pygame.display.get_surface()
        if pos:
            screen.blit(self.background, (pos[0], 770 + pos[1]), pos)
        else:
            screen.blit(self.background, (0, 770))

        objpos = [15, 785]
        for item in self.objects:
            item.rect.topleft = objpos
            item.draw(screen, item.rect.topleft )
            objpos[0] += item.image.get_width() + 15

    def update(self):
        pass

class CommandBar(object):
    """ This widget contains the commands: play, help, and quit. KISS! =D """

    def __init__(self):
        self.background = pygame.Surface((200, 130))
        self.width, self.height = self.background.get_size()
        self.background.fill([0, 0, 255])
        self.commands = [ Play(), Help(), Quit() ]

    def draw(self, pos=None):
        screen = pygame.display.get_surface()
        if pos:
            screen.blit(self.background, (1000 + pos[0], 770 + pos[1]), pos)
        else:
            screen.blit(self.background, (1000, 770))

        objpos = [1015, 810]
        for cmd in self.commands:
            cmd.rect.topleft = objpos
            cmd.draw(screen, cmd.rect.topleft )
            objpos[0] += cmd.image.get_width() + 15

    def update(self):
        pass

class Level(object):
    """This widget contains the objects in the scenario and their positions
    on the screen"""
    objects = None

    def __init__(self, obj_in_place, obj_to_add, goals, help_img):
        self.simulator = SimulationView(obj_in_place)
        self.objbar = ObjectBar(obj_to_add)
        self.cmdbar = CommandBar()
        self.goals = goals
        self.help_img = help_img

    def goal_reached(self):
        for obj, goal in self.goals:
            if not obj.rect.collidepoint(goal.rect.center):
                return False
        return True

    def draw(self):
        self.simulator.draw()
        self.objbar.draw()
        self.cmdbar.draw()

    def show_help(self, screen):
        screen.blit(self.help_img, (600 - self.help_img.get_width()/2,
                                    450 - self.help_img.get_height()/2) )
        pygame.display.flip()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    return

def init_levels():
    return load_levels()

def load_levels():
    level_dir = os.path.join('data', 'levels')
    files = os.listdir(level_dir)
    levels = []
    for level_file in sorted(f for f in files if f.split(".")[-1] == "level"):
        raw = open(os.path.join(level_dir, level_file))
        try:
            level = json.load(raw)
        except ValueError, error:
            print level_file, "-> invalid json file: ", error
            raw.close()
        else:
            lvl = load_level(level, level_dir, level_file)
            if lvl:
                levels.append(lvl)

    return levels

def load_level(level, level_dir, level_name):
    objs = {}
    for obj in level["placed"]:
        try:
            klass = globals()[obj["type"]]
        except KeyError, error:
            print level_name, "-> Invalid type for object:", error
            return None

        new = klass( ( int(obj["xpos"]), int(obj["ypos"]) ), editable=False)
        objs[obj["name"]] = new

    toadd = {}
    for obj in level["available"]:
        try:
            klass = globals()[obj["type"]]
        except KeyError, error:
            print level_name, "-> Invalid type for object:", error
            return None

        try:
            toadd[obj["name"]] = klass()
        except KeyError:
            print level_name, "-> Object name not available"
            return None

    goals = []
    for goal in level["goals"]:
        try:
            proj = objs[ goal[0] ]
            trg = objs[ goal[1] ]
        except KeyError, error:
            print level_name, "-> Object not available:", error
            return None
        goals.append( (proj, trg) )

    img_file = os.path.join(level_dir, level['help'])
    if os.path.isfile(img_file):
        help_image = pygame.image.load(img_file)
    else:
        print level_name, "-> Invalid help file:", level['help']
        return None

    return Level(objs, toadd, goals, help_image)