Ejemplo n.º 1
0
    def room2(self):
        m = MapRenderer("second room", self.engine)
        m.renderBackground()
        self.current_room = 2
        self.player.resetx = 300
        self.player.resety = 416

        # set up doors
        d = Door(2, 300, 432, 300, 16, "third room", self.engine)
        self.engine.objects.append(d)
        self.player.interactables.add(d)
        self.engine.drawables.add(d)

        # set up container and enemy
        self.crate.createLanternContainer(2, 387, 328)
        self.crate.createBeartrapContainer(2, 330, 332)
        self.spawner.createEnemy(2, 386, 183)
        self.spawner.createEnemy(2, 60, 71)

        # door to next room
        d2 = Door(2, 61, 189, 413, 65, "third room", self.engine)
        print("changing room")
        self.engine.drawables.add(d2)
        self.engine.objects.append(d2)
        self.player.interactables.add(d2)
        m.renderForeGround()

        # add all impassable sprites to classes which need them
        for impassable in m.getAllImpassables():
            self.player.blocks.add(impassable)
Ejemplo n.º 2
0
def main():
    pi = pigpio.pi()
    srv = Servo(pi)
    swi = Switch(pi, srv)
    door = Door(pi)

    try:
        while True:
            logger.debug("waiting id card")
            # ここでカード読み込み
            if database.confirm("ここに番号"), "ここにIDm"):
                srv.open_lock()
                slack.send_slack("ここになまえ")
                time.sleep(10)
                while door.door_status() == door.OPEN:
                    time.sleep(0.5)
                srv.close_lock()
            else:
                led.red_led_on()
                print("Can't confirm.")
                time.sleep(3)
                led.red_led_off()
    except:
        pi.stop()
        r.close()
        main()
Ejemplo n.º 3
0
    def __init__(self,
                 door_config: DoorConfig,
                 room_type: RoomType = RoomType.STANDARD):
        self.north_door: Optional[Door] = Door(
            Direction.NORTH) if door_config.north else None
        self.south_door: Optional[Door] = Door(
            Direction.SOUTH) if door_config.south else None
        self.east_door: Optional[Door] = Door(
            Direction.EAST) if door_config.east else None
        self.west_door: Optional[Door] = Door(
            Direction.WEST) if door_config.west else None

        self.door_map = {
            Direction.NORTH: self.north_door,
            Direction.SOUTH: self.south_door,
            Direction.EAST: self.east_door,
            Direction.WEST: self.west_door
        }

        self.number_of_connections = sum(door_config.raw)

        self.treasure: Optional[Treasure] = None

        self.enemies: List[Enemy] = []

        self.type = room_type
        self.entity_type = EntityType.ROOM
        self.id = generate_random_id(self.entity_type)

        self.visited = False
Ejemplo n.º 4
0
 def add_connection(self, room: 'Room', direction: Direction):
     door = Door(
         direction, DoorType.BARRICADE
     ) if self.door_map[direction] is None else self.door_map[direction]
     door.connection = room
     if room.door_map[direction.opposite()] is None:
         door.type = DoorType.BARRICADE
Ejemplo n.º 5
0
    def room3(self):
        m = MapRenderer("third room", self.engine)
        m.renderBackground()
        self.current_room = 3

        # set up doors
        d = Door(2, 413, 65, 300, 16, "second room", self.engine)
        self.engine.objects.append(d)
        self.player.interactables.add(d)
        self.engine.drawables.add(d)

        # set up container and enemy
        self.spawner.createAbbot(2, 82, 399)
        self.crate.createBeartrapContainer(2, 200, 70)

        d2 = Door(2, 300, 300, 52, 56, "fourth room", self.engine)
        self.engine.drawables.add(d2)
        self.engine.objects.append(d2)
        self.player.interactables.add(d2)

        m.renderForeGround()

        # add all impassable sprites to classes which need them
        for impassable in m.getAllImpassables():
            self.player.blocks.add(impassable)
Ejemplo n.º 6
0
    def room4(self):
        m = MapRenderer("fourth room", self.engine)
        m.renderBackground()
        self.current_room = 4

        # set up doors
        d = Door(2, 52, 56, 300, 16, "third", self.engine)
        self.engine.objects.append(d)
        self.player.interactables.add(d)
        self.engine.drawables.add(d)

        # set up container and enemy
        self.crate.createRancidMeatContainer(2, 234, 66)
        self.spawner.createAbbot(2, 352, 376)

        d2 = Door(2, 17, 195, 50, 416, "fifth room", self.engine)
        self.engine.drawables.add(d2)
        self.engine.objects.append(d2)
        self.player.interactables.add(d2)

        m.renderForeGround()

        # add all impassable sprites to classes which need them
        for impassable in m.getAllImpassables():
            self.player.blocks.add(impassable)
Ejemplo n.º 7
0
def _create_door (game, data) :
	door = Door (
		default = 'images/door_closed.png',
		closed='images/door_closed.png',
		open='images/door_open.png')
	door.set_pos (_get_coords (data))
	return door
Ejemplo n.º 8
0
 def __init__(self):
     #
     # instantiate all our classes
     self.comms = Comms(config.ORIGIN_NUM, config.TARGET_NUMS)
     self.light = Light(config.CITY_NAME, config.LATITUDE, config.LONGITUDE,
                        config.SUNRISE_DELAY, config.SUNSET_DELAY)
     self.door = Door(config.REVS)
     self.camera = Camera(config.MAX_HORZ, config.MAX_VERT)
Ejemplo n.º 9
0
class World:
    def __init__(self, app):
        self.app = app
        self.enemy_list = []
        self.width = 640
        self.height = 480
        self.player = Player(self, 225, 85, 15, 15)
        self.background = Background(self, pygame.image.load('assets/background_image.png'))
        self.door = Door(self,self.background, 0, 150)
        self.door_2 = Door(self,self.background,0,50)
        self.npc = None
        self.protectable_item = ProtectableItem(self,app,150,150, 'assets/cake.png')
        self.score_display = ScoreDisplay(self)
        window_size = SCREEN_WIDTH, SCREEN_HEIGHT = 320,240
        self.screen = pygame.display.set_mode(window_size,RESIZABLE)
        self.surface = pygame.Surface(self.screen.get_size())
        self.surface = self.surface.convert()
        self.fpsClock=pygame.time.Clock()


    def update(self):
        self.player.update()
        self.player.Interacting(self.npc)
        if self.door.check_door_touching(self.player):
            for enemy_number in range(0,1):
                PlayerAttacker(self, 50, 50,  pygame.image.load('assets/demon1.png'))
                itemAttacker(self, 10, 10,  pygame.image.load('assets/demon1.png'))



        #self.door.check_door_touching(self.player)
        self.player.Interacting(self.npc)
        for this_enemy in self.enemy_list:
            this_enemy.update()
        if self.npc != None:
            self.npc.update()

    def draw(self):
        self.surface.fill((0, 0, 0)) # clear screen (Paint it all white)
        self.background.draw(self.surface)
        self.player.draw(self.surface)
        self.protectable_item.draw(self.surface)
        self.score_display.draw()
        if self.npc != None:
            self.npc.draw(self.surface)
        for this_enemy in self.enemy_list:
            this_enemy.draw(self.surface)
            this_enemy.draw(self.surface)
        self.door.draw(self.surface)

        self.screen.blit(self.surface, (0,0)) # this might be what was missing
        pygame.display.update() #  Actually do all the stuff? (Not actually sure what this does... but I think it should be called at the end of the drawing step)
        FPS = 30
        self.fpsClock.tick(FPS)

    def change_location(self, background_image):
        self.background.change_image(background_image)
        self.npc = NonPlayer(self, pygame.image.load('assets/npc_32x32.png'))
Ejemplo n.º 10
0
    def __init__(self, pi, servo):
        self.pi = pi
        self.door = Door(pi)
        self.time_old = time.time()
        self.servo = servo
        pi.set_mode(Switch.switch_pin, pigpio.INPUT)
        pi.set_pull_up_down(Switch.switch_pin, pigpio.PUD_DOWN)

        self._cb = pi.callback(Switch.switch_pin, pigpio.RISING_EDGE, self._cbf1)
Ejemplo n.º 11
0
class Switch:
    switch_pin = 22

    def __init__(self, pi, servo):
        self.pi = pi
        self.door = Door(pi)
        self.time_old = time.time()
        self.servo = servo
        pi.set_mode(Switch.switch_pin, pigpio.INPUT)
        pi.set_pull_up_down(Switch.switch_pin, pigpio.PUD_DOWN)

        self._cb = pi.callback(Switch.switch_pin, pigpio.RISING_EDGE, self._cbf1)

    def _cbf(self, gpio, level, tick):
        if time.time() - self.time_old < 1:
            return
        else:
            self.servo.open_lock()
            database.button_info_insert()
            slack.button()
            time.sleep(5)
            while self.door.door_status() == self.door.OPEN:
                time.sleep(0.5)
            self.servo.close_lock()
        self.time_old = time.time()

    def _cbf1(self, gpio, level, tick):
        # 長押しでリスタートの機能追加版
        if time.time() - self.time_old < 1:
            return
        else:
            counter = 0
            while True:
                status = self.pi.read(Switch.switch_pin)
                if status == 1:
                    counter += 1
                    if counter >= 60:
                        led.red_led_on()
                        led.green_led_on()
                        time.sleep(2)
                        led.green_led_off()
                        led.red_led_off()
                        self.time_old = time.time()
                        subprocess.Popen("sudo systemctl restart badegg.service", shell=True)
                        break
                else:
                    self.servo.open_lock()
                    database.button_info_insert()
                    slack.button()
                    time.sleep(5)
                    while self.door.door_status() == self.door.OPEN:
                        time.sleep(0.5)
                    self.servo.close_lock()
                    self.time_old = time.time()
                    break
                time.sleep(0.05)
Ejemplo n.º 12
0
def get_doors_for_world(world_type):
    if (world_type == "japaneseVillage"):
        door = Door(1, 1000, 1000, "door1")
        return [door]
    elif (world_type == "beach"):
        door = Door(1, 10000, 10000, "door1")
        return [door] 
    elif (world_type == "insideHouse"):
        door = Door(1, 5000, 500, "door1")
        return [door] 
Ejemplo n.º 13
0
def play_game(contestant_switches):
    doors = [Door(False), Door(False), Door(True)]
    random.shuffle(doors)

    game = Game(*doors)
    game.contestant_guess = doors[0]
    game.host_open_door()

    if contestant_switches:
        game.contestant_switch()
    return game.contestant_has_won()
class DoorTests(unittest.TestCase):
    def setUp(self):
        self.func = Door("green", 5)

    def test_color_is_evaluated_as_getter(self):
        with self.assertRaises(AttributeError):
            self.func.color

    def test_color_is_evaluated_as_setter(self):
        raised = False
        try:
            self.func.color = "red"
        except:
            raised = True
        self.assertFalse(raised, 'Exception raised')

    def test_size_is_evaluated_as_getter(self):
        self.assertEqual(self.func.size, 5)

    def test_size_is_evaluated_as_setter(self):
        with self.assertRaises(AttributeError):
            self.func.size = 10

    def test_status_as_getter_with_default_parameter(self):
        self.assertEqual(self.func.status, "Cerrado")

    def test_status_is_evaluated_as_setter(self):
        raised = False
        try:
            self.func.status = "Abierto"
        except:
            raised = True
        self.assertFalse(raised, 'Exception raised')

    def test_status_if_status_is_cerrado_then_open_returns_business_is_closed(
            self):
        self.func.status = "Cerrado"
        self.assertEqual(self.func.open(), "Business is closed")

    def test_status_if_status_is_abierto_then_open_returns_open_red_door(self):
        self.func.color = "red"
        self.func.status = "Abierto"
        self.assertEqual(self.func.open(), "open red door")

    def test_close_if_status_is_cerrado_then_close_returns_door_is_closed(
            self):
        self.func.status = "Cerrado"
        self.assertEqual(self.func.close(), "Door is closed")

    def test_close_if_status_is_abierto_then_close_returns_close_door_of_5_meters(
            self):
        self.func.status = "Abierto"
        self.assertEqual(self.func.close(), "close door of 5 meters")
Ejemplo n.º 15
0
def main():
    lst = [
        Door("opened"),
        Door(),
        Door(),
        Window("opened"),
        Window(),
        Door(),
        Window("opened"),
        Window("opened")
    ]

    openclosefuncs.closeAll(lst)
    openclosefuncs.openAll(lst)
Ejemplo n.º 16
0
def generate_doors(count=100):
    door_list = []

    for i in range(1, count + 1):
        door_list.append(Door(i))

    return door_list
Ejemplo n.º 17
0
    def __reset(self):
        self.alphabet = [False] * 26
        Framework.__init__(self)
        Framework.setZoom(self, 115)
        Framework.setCenter(self, [0, 1.74])
        self.wristAngle = math.pi / 2
        self.doorOpened = False
        self.recording = False
        self.reset = False
        self.arm_angles = [
            math.pi / 2, math.pi / 2, math.pi / 2, math.pi / 2, math.pi / 2
        ]
        lengths = [1, 1, .4, .27]
        self.arm = Arm(self.world,
                       self.arm_angles,
                       lengths,
                       basePos=(-.1, 0.08),
                       motorRange=2 * math.pi)
        self.arm.target_pose[0] = random.uniform(-1, 1)
        self.arm.target_pose[1] = random.uniform(1.5, 2.3)

        ground = self.world.CreateBody(position=(0, 0))
        ground.CreateEdgeChain([(-4, -2), (-4, .6), (-2, .6), (-2, 0), (2, 0),
                                (2, 6), (4, 6), (4, -2), (-2, -2)])

        self.door = Door(self.world, (-2, .62), 1.2)
Ejemplo n.º 18
0
 def addInternalDoor(self, r1, r2, s):
     x, y = [0], [0]
     r = 0
     dp = [0, 0]
     if self.rooms[r1].status == '0':
         r = r1
         x = [
             self.rooms[r2].origin[0],
             min(self.rooms[r1].anti_origin[0],
                 self.rooms[r2].anti_origin[0])
         ]
         y = [
             self.rooms[r2].origin[1],
             min(self.rooms[r1].anti_origin[1],
                 self.rooms[r2].anti_origin[1])
         ]
     elif self.rooms[r2].status == '0':
         r = r2
         x = [
             self.rooms[r1].origin[0],
             min(self.rooms[r1].anti_origin[0],
                 self.rooms[r2].anti_origin[0])
         ]
         y = [
             self.rooms[r1].origin[1],
             min(self.rooms[r1].anti_origin[1],
                 self.rooms[r2].anti_origin[1])
         ]
     if s == 'v':  # wertykalny
         dp = [choice(x), randint(y[0], y[-1] - 1)]
     elif s == 'h':  # horyzontalny
         dp = [randint(x[0], x[-1] - 1), choice(y)]
     self.doors.append(Door(*dp, *self.rooms[r].anti_origin, s))
Ejemplo n.º 19
0
    def create_dict_map(self,
                        width=TESTLEVEL_WIDTH,
                        height=TESTLEVEL_HEIGHT,
                        level_array=TESTLEVEL):
        dict_map = {(x, y): Tile((x, y))
                    for x in range(width) for y in range(height)}

        for l_x in range(width):
            for l_y in range(height):
                if level_array[l_x][l_y] == '.':
                    dict_map[(l_x, l_y)].blocked = False
                elif level_array[l_x][l_y] == '#':
                    dict_map[(l_x, l_y)].skin = 0
                elif level_array[l_x][l_y] == '$':
                    dict_map[(l_x, l_y)].skin = 1
                elif level_array[l_x][l_y] == '%':
                    dict_map[(l_x, l_y)].skin = 2
                    door_component = Door(player=self.player,
                                          entities=self.entities)
                    dict_map[(l_x, l_y)].door = door_component
                    dict_map[(l_x, l_y)].add_door_component()
                elif level_array[l_x][l_y] == '[':
                    dict_map[(l_x, l_y)].skin = 3
                elif level_array[l_x][l_y] == '=':
                    dict_map[(l_x, l_y)].skin = 4
                elif level_array[l_x][l_y] == ']':
                    dict_map[(l_x, l_y)].skin = 5

        self.current_level = dict_map
Ejemplo n.º 20
0
    def __init__(self):
        self.rooms = []
        self.currentRoom = 0
        self.inventory = []

        firstRoom = Room(
            1,
            "Je staat in de keuken. Er staan een aanrecht en een koelkast, en er is 1 deur.",
            [Door(123, 1)],
            [Key(123, "woonkamersleutel"),
             Key(321, "schatkistsleutel")])
        secondRoom = Room(2, "Je staat in de woonkamer, er is een deur",
                          [Door(123, 0)], [])
        self.rooms.append(firstRoom)
        self.rooms.append(secondRoom)
        print(self.rooms[self.currentRoom].description)
Ejemplo n.º 21
0
    def populate_map(self, map):
        # define rooms and items
        # furniture
        couch = Furniture("couch")
        piano = Furniture("piano")
        double_bed = Furniture("double bed")
        queen_bed = Furniture("queen bed")
        dresser = Furniture("dresser")
        dining_table = Furniture("dining table")

        # doors
        door_a = Door("door a")
        door_b = Door("door b")
        door_c = Door("door c")
        door_d = Door("door d")

        # keys
        key_a = Key("key for door a", door_a)
        key_b = Key("key for door b", door_b)
        key_c = Key("key for door c", door_c)
        key_d = Key("key for door d", door_d)

        # rooms
        game_room = Room("game room")
        bedroom_1 = Room("bedroom 1")
        bedroom_2 = Room("bedroom 2")
        living_room = Room("living room")
        outside = Room("outside")

        # setting start and end rooms
        map.set_start_room(game_room)
        map.set_end_room(outside)

        # object relations
        map.add_relation("game room", [couch, piano, door_a])
        map.add_relation("bedroom 1", [queen_bed, door_a, door_b, door_c])
        map.add_relation("bedroom 2", [double_bed, dresser, door_b])
        map.add_relation("living room", [dining_table, door_c, door_d])
        map.add_relation("outside", [door_d])
        map.add_relation("piano", [key_a])
        map.add_relation("double bed", [key_c])
        map.add_relation("dresser", [key_d])
        map.add_relation("queen bed", [key_b])
        map.add_relation("door a", [game_room, bedroom_1])
        map.add_relation("door b", [bedroom_1, bedroom_2])
        map.add_relation("door c", [bedroom_1, living_room])
        map.add_relation("door d", [living_room, outside])
Ejemplo n.º 22
0
def main() :
    e = league.Engine("Spook City")
    e.init_pygame()
    timer = pygame.time.set_timer(pygame.USEREVENT + 1, 1000 // league.Settings.gameTimeFactor)
    count = 0

    p = Player(1, 400, 300)
    spawner = EnemySpawner(e,p)
    crate = createInteract(e,p)

    spawner.createEnemy(2,128,128)
    crate.createLanternContainer(2,128,300)
    crate.createBeartrapContainer(2,256,300)

    mapRenderer = MapRenderer("first room", e)
    world_size = mapRenderer.renderBackground()
    p.world_size = world_size
    mapRenderer.renderForeGround()
    d = Door(2, 300, 4, 300, 416, "second room", e)
    e.light_points = p.raycast_points
    e.player = p
    overlay = Overlay(p)
    e.overlay = overlay
    e.objects.append(p)
    e.objects.append(overlay)
    e.objects.append(d)

    # any objects to be created on the fly
    p.items = e.dynamic_instances
    p.interactables.add(d)

    # add all drawables
    e.drawables.add(p)
    e.drawables.add(d)
    mapRenderer.renderForeGround()

    p.resetx = 300
    p.resety = 416

    bgm = BackgroundMusic("lavender town")
    bgm.start_music()
  
    # add all impassable sprites to classes which need them
    for impassable in mapRenderer.getAllImpassables():
        p.blocks.add(impassable)

    # create room object in engine
    e.room = Room(p, e, overlay)
    p.room = e.room

    e.key_events[pygame.K_a] = p.move_left
    e.key_events[pygame.K_d] = p.move_right
    e.key_events[pygame.K_w] = p.move_up
    e.key_events[pygame.K_s] = p.move_down
    e.key_events[pygame.K_e] = p.interact
    e.key_events[pygame.K_SPACE] = p.use_active_item
    e.key_events[pygame.K_ESCAPE] = e.stop
    e.events[pygame.QUIT] = e.stop
    e.run()
Ejemplo n.º 23
0
    def _build_door(self):
        """Position and build the level door"""
        self.door = Door(self)
        self.door.rect.y = 196
        self.door.rect.x = -100

        self.doors = pygame.sprite.Group()
        self.doors.add(self.door)
Ejemplo n.º 24
0
 def __init__(self, app):
     self.app = app
     self.enemy_list = []
     self.width = 640
     self.height = 480
     self.player = Player(self, 225, 85, 15, 15)
     self.background = Background(self, pygame.image.load('assets/background_image.png'))
     self.door = Door(self,self.background, 0, 150)
     self.door_2 = Door(self,self.background,0,50)
     self.npc = None
     self.protectable_item = ProtectableItem(self,app,150,150, 'assets/cake.png')
     self.score_display = ScoreDisplay(self)
     window_size = SCREEN_WIDTH, SCREEN_HEIGHT = 320,240
     self.screen = pygame.display.set_mode(window_size,RESIZABLE)
     self.surface = pygame.Surface(self.screen.get_size())
     self.surface = self.surface.convert()
     self.fpsClock=pygame.time.Clock()
Ejemplo n.º 25
0
 def __init__(self, doors: int):
     self.doors = {
         possible_doors[i]: Door(possible_doors[i])
         for i in range(
             doors
         )  #dict comprehension, podobnie do list comprehension tylko musi być klucz i wrtość
     }
     self.close_doors()
Ejemplo n.º 26
0
 def testSpecific(self):
     testHeight: float = 85.8
     testWidth: float = 40
     testWood: str = 'Cedar'
     door1 = Door(woodType=testWood, width=testWidth, height=testHeight)
     self.assertEqual(door1.woodType, testWood)
     self.assertEqual(door1.height, testHeight)
     self.assertEqual(door1.width, testWidth)
Ejemplo n.º 27
0
def load_modules():
    modules = {}
    # load detectors from database
    from detector import Detector
    Detector.load_to_dict(modules)

    # load alarm from database
    from alarm import Alarm
    Alarm.load_to_dict(modules)

    # load rfid
    from rfid import Rfid
    Rfid.load_to_dict(modules)

    from door import Door
    Door.load_to_dict(modules)

    return modules
Ejemplo n.º 28
0
def set_tcp_info():
    door = Door()
    ip_info = {
        'ip': '192.168.3.35',
        'mask': '255.255.255.0',
        'gateway': '192.168.3.1',
        'dns1': '225.5.5.5',
        'dns2': '225.6.6.6',
        'work_type': '01',
        'tcp_listen': 8000,
        'udp_listen': 8101,
        'remote_port': 9000,
        'remote_ip': '192.168.3.155',
        'dhcp': '00',
        'remote_domain': ''
    }
    res = door.set_tcp_info(ip_info)
    print(res)
Ejemplo n.º 29
0
    def init_objects(self):
        #  create player object
        player_pos = self.current_level.get_character_pos()
        player_current_row = player_pos[0]
        player_current_col = player_pos[1]
        self.player = Player(player_current_row, player_current_col)

        #  create robots
        self.robots = []
        robot_positions = self.current_level.get_robot_positions()
        for pos in robot_positions:
            r = pos[0]
            c = pos[1]
            self.robots.append(Robot(r, c, self.current_level.get_matrix()))

        #  create apples
        self.apples = []
        apple_positions = self.current_level.get_apple_positions()
        for pos in apple_positions:
            r = pos[0]
            c = pos[1]
            self.apples.append(Apple(r, c))

        #  create doors
        self.doors = []
        door_positions = self.current_level.get_door_positions()
        for pos in door_positions:
            r = pos[0]
            c = pos[1]
            self.doors.append(Door(r, c))

        #  create keys
        self.keys = []
        key_positions = self.current_level.get_key_positions()
        for pos in key_positions:
            r = pos[0]
            c = pos[1]
            self.keys.append(Key(r, c))

        #  create lights
        self.lights = []
        light_positions = self.current_level.get_light_positions()
        for pos in light_positions:
            r = pos[0]
            c = pos[1]
            self.lights.append(Light(r, c))

        #  count number of apples
        self.total_apple_count = len(self.apples)
        #print("Number of apples in the level ", self.total_apple_count)

        #  count keys and doors
        self.total_key_count = len(self.keys)
Ejemplo n.º 30
0
 def build():
     prizes = [0, 0, 1]
     
     doors = []
     
     for i in range(0, 3):
         prize = prizes[randrange(len(prizes))]
         
         doors.append(Door(f"Door{i + 1}", prize, 0, 0))
         
         prizes.remove(prize)
         
     return doors
Ejemplo n.º 31
0
 def __init__(self, rows):
     super(Map, self).__init__()
     self.height = len(rows)
     self.width = len(rows[0])
     for y, row in enumerate(rows):
         self._map[y] = {}
         for x, item in enumerate(row):
             if item == '#':
                 self._map[y][x] = Floor()
             elif item == '|':
                 self._map[y][x] = Door()
             elif item == '@':
                 self._map[y][x] = Player()
             else:
                 self._map[y][x] = None  
Ejemplo n.º 32
0
	def makeDoor(self, door):
		try:
			d = Door("model/" + door["model"] + ".json", door["openWith"], door["permanent"])
			d.setPos(self.gridToPos(door["pos"]))
			d.type = "door"
			d.symbol = 'd'

			if door["openWith"] == "switches":
				d.switches = door["switches"]

			return d
		except KeyError as e:
			print "Error in map doors..."
			exit()
Ejemplo n.º 33
0
        if config.has_option(section, 'type'):
            t = config.get(section, 'type')
            if t == 'door':
                name = section
                txseq = int(config.get(section, 'txsequence'))
                rxseq = int(config.get(section, 'rxsequence'))
                address = config.get(section, 'address')
                initial_unlock = config.get(section, 'inital_unlock')
                if initial_unlock == 'True':
                    initial_unlock = True
                else:
                    initial_unlock = False

                key = config.get(section, 'key')
                logger.debug('Adding door "%s"'%section)
                door = Door(name, address, txseq, rxseq, key, ser, initial_unlock)
                doors[address] = door
            else:
                logger.warning('Unknown entry type "%s"', t)
        elif section == 'Master Controller':
            txseq = int(config.get(section, 'txsequence'))
            rxseq = int(config.get(section, 'rxsequence'))
            key = config.get(section, 'key')
            master = MasterController('0', txseq, rxseq, key, ser, command_queue) 
    
    if master == None:
        logger.error('Please specify a master controller')
        sys.exit(1)

    command_queue.put('announce_closed')
    
Ejemplo n.º 34
0
from door import Door

d = Door('smart-door') # replace with your one
d.checkAvailable()
Ejemplo n.º 35
0
def main():
    """The main loop of the game.  It handles loading the levels, key strokes, playing music and sounds; relies heavily on multiple other classes to function correctly.
        These include the camera, coins, door, entities, platform, player, sounds, spike, themes, and trophies classes."""
    gc.enable() # Garbage collector
    global cameraX, cameraY, key_count, delete_door, current_level, deaths, deaths_total, volume # Load in the global variables
    pygame.mixer.pre_init(44100, -16, 2, 2048) # Initilize the music
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH) # Set the screen information
    screen_rect = screen.get_rect()
    timer = pygame.time.Clock()

    # We don't want to see the normal mouse cursor while playing.
    pygame.mouse.set_visible(False)

    sounds = Sounds() # Allows us to call sounds by doing sounds.name

    font = pygame.font.SysFont("arial", 25) # Font for the game

    loading_bar = pygame.transform.scale(pygame.image.load("images/button.png"), (WIN_WIDTH, 35)) # Loading bar image (so that the "Loading Level (level)..." text is visible)

    up = down = left = right = running = False # Set all key strokes (directions) to False


    # Load in the first level by assigning sprites into groups and into the platforms and coin_list lists
    # Read about what each thing does in the respective class
    # !!! WARNING !!! The game will break if the level does not contain the player ("C") within; the game may break if the door Top and Bottom is not found as well.
    """KEY FOR LEVELS
        P = Platform
        C = player starting position
        A = Spike (Up)
        V = Spike (Down)
        > = Spike (Right)
        < = Spike (Left)
        K = Key
        X = Trophy
        T = Door Top
        B = Door Bottom"""

    platforms = []
    coin_list = []

    entities = pygame.sprite.Group()
    coinA = pygame.sprite.Group()
    spikes = pygame.sprite.Group()
    trophies = pygame.sprite.Group()
    monsters = pygame.sprite.Group()
    x = 0
    y = 0
    level = open('levels/level' + str(current_level) + '.txt', 'r')
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y) # Place a platform at the given x,y
                platforms.insert(0, p) # Insert it into the platforms list
                entities.add(p) # Add to entities so it appears on screen
            if col == "C":
                charX = x # The character x found from file loading
                charY = y # The character y found from file loading
                player = Player(charX, charY) # Set the player along with the x,y of the starting position
            if col == "A":
                spike = Spike(x, y, 1) # Load a spike at the x,y found 
                entities.add(spike) # Add the spike to the entities
                spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
            if col == "V":
                spike = Spike(x, y, 2) # Load a spike at the x,y found 
                entities.add(spike) # Add the spike to the entities
                spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
            if col == ">":
                spike = Spike(x, y, 3) # Load a spike at the x,y found 
                entities.add(spike) # Add the spike to the entities
                spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
            if col == "<":
                spike = Spike(x, y, 4) # Load a spike at the x,y found 
                entities.add(spike) # Add the spike to the entities
                spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
            
            if col == "M":
                monster = Monster(x, y) # Load a spike at the x,y found 
                entities.add(monster) # Add the spike to the entities
                monsters.add(monster) # Add the spike to the spike sprite group for collison purposes
            
            if col == "K":
                c1 = Coins(x, y) # Load a coin image at the given x,y
                entities.add(c1) # Coin 1 to the entities
                coinA.add(c1) # add coin 1 to the coinA sprite group
            if col == "X":
                win_object = Trophy(x, y) # Load the proper trophy by passing the current_level to the trophy class and load at the given x,y from file loading
                entities.add(win_object) # Add the trophy to the entities so it appears
                trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
            if col == "T":
                doorA = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked1.png"), (60,100)))
                platforms.append(doorA) # Make the door top a platform so the player cannot walk through it
                entities.add(doorA) # Add the door bottom to the entities
            if col == "B":
                doorB = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked2.png"), (60,32)))
                platforms.append(doorB) # Make the door bottom a platform so the player cannot walk through it
                entities.add(doorB) # Add the door bottom to entities
            x += 32
        y += 32
        x = 0

    # Try loading in the level image and theme; if it fails, use level 0 theme and background
    background = pygame.image.load('images/backgrounds/background.png').convert_alpha()
    background_rect = background.get_rect()

    total_level_width  = len('level'[0])*32
    total_level_height = len('level')*32
    camera = Camera(complex_camera, total_level_width, total_level_height)
    entities.add(player) # Finally, add player to entities so it appears
    missiles = pygame.sprite.RenderUpdates()

        
    # The main loop of the game which runs it until we're done.    
    while 1:
        pygame.display.set_caption("Asylum | Deaths (level): " + str(deaths) + " | Deaths (Total): " + str(deaths_total) + " | FPS: " + str(int(timer.get_fps())))
        asize = ((screen_rect.w // background_rect.w + 1) * background_rect.w, (screen_rect.h // background_rect.h + 1) * background_rect.h)
        bg = pygame.Surface(asize)

        # Create the background
        for x in range(0, asize[0], background_rect.w):
            for y in range(0, asize[1], background_rect.h):
                screen.blit(background, (x, y))

        timer.tick(38) # The maximum framerate; the game is designed to run at an FPS of 30-40 (38 being best)

        # All the keystroke events; the game can run using the UP-RIGHT-LEFT arrow keys, Space Bar, and the AWD keys (down is never needed)
        #   ENTER will kill the player (used if the player glitch spawns outside the level or glitch out (reloads the level as if they died))
        for e in pygame.event.get():
            if e.type == QUIT: 
                exit()
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                exit()
            if e.type == KEYDOWN and e.key == K_UP:
                player.direction = 'up'
                up = True
                down = left = right = False
            if e.type == KEYDOWN and e.key == K_DOWN:
                player.direction = 'down'
                down = True
                up = left = right = False
            if e.type == KEYDOWN and e.key == K_LEFT:
                player.direction = 'left'
                left = True
                right = up = down = False
            if e.type == KEYDOWN and e.key == K_RIGHT:
                player.direction = 'right'
                right = True
                left = up = down = False
            if e.type == KEYDOWN and e.key == K_w:
                player.direction = 'up'
                up = True
                down = left = right = False
            if e.type == KEYDOWN and e.key == K_s:
                player.direction = 'down'
                down = True
                up = left = right = False
            if e.type == KEYDOWN and e.key == K_a:
                player.direction = 'left'
                left = True
                right = up = down = False
            if e.type == KEYDOWN and e.key == K_d:
                player.direction = 'right'
                right = True
                left = up = down = False
            """
            if e.type == KEYDOWN and e.key == K_RSHIFT and player.attacking == False and pygame.sprite.spritecollide(player, monster, True):
                print "Space bar clicked, attacking!"
                player.attacking = True
                sounds.shot.play()
                sounds.shot.set_volume(volume)
                if player.direction == 'down':
                    player.image = pygame.transform.scale(player.attackList[0], (50, 50))
                if player.direction == 'left':
                    player.image = pygame.transform.scale(player.attackList[1], (50, 50))
                if player.direction == 'up':
                    player.image = pygame.transform.scale(player.attackList[2], (50, 50))
                if player.direction == 'right':
                    player.image = pygame.transform.scale(player.attackList[3], (50, 50))
            """

            if e.type == KEYUP and e.key == K_UP:
                player.direction = 'up'
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                player.direction = 'down'
                down = False
            if e.type == KEYUP and e.key == K_RIGHT:
                player.direction = 'right'
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                player.direction = 'left'
                left = False
            if e.type == KEYUP and e.key == K_w:
                player.direction = 'up'
                up = False
            if e.type == KEYUP and e.key == K_s:
                player.direction = 'down'
                down = False
            if e.type == KEYUP and e.key == K_d:
                player.direction = 'right'
                right = False
            if e.type == KEYUP and e.key == K_a:
                player.direction = 'left'
                left = False
            """
            if e.type == KEYUP and e.key == K_RSHIFT:
                player.attacking = False
                print "reset attack"
            """

        # All of the coin collision detection; when it occurs, the coin is removed and a sound plays while adding one to the coin_count (4 opens the door)
        # the True in each IF statement means that when the collision occurs the coin is removed from it's group, thus removing it from appearing on screen
        if pygame.sprite.spritecollide(player, coinA, True, pygame.sprite.collide_mask):
            sounds.coin_sound.play()
            sounds.coin_sound.set_volume(volume)
            key_count += 1

        # If the player manages to reach the trophy, reset the level deaths, add one to the current_level, kill the theme (music), add the loading bar, print out loading level
        #       kill all key-presses (directions) empty all sprites and lists and load in the next level
        if pygame.sprite.spritecollide(player, trophies, True, pygame.sprite.collide_mask):
            sounds.footsteps.play()
            deaths = 0
            current_level += 1
            platforms = None
            level = None
            up = False
            right = False
            left = False
            key_count = 0
            doorA.kill()
            doorB.kill()
            entities.empty()
            trophies.empty()
            spikes.empty()
            coinA.empty()
            monsters.empty()
            screen.blit(loading_bar, (0,0)) # Blit the loading bar image to the screen (so text shows up on all background colors)
            load_text = font.render("Loading Level " + str(current_level) + "...", True, (255, 255, 255)) # Blit loading text to the loading_bar
            screen.blit(load_text, (1,0))
            pygame.display.update()
            gc.collect()
            x = 0
            y = 0
            platforms = []
            pause.sleep(3) # Sleep for 5 seconds ('loading'...might have an effect on lag by allowing it to pause for a few seconds)
            try:
                level = open('levels/level' + str(current_level) + '.txt', 'r') # Try loading the next level; if it fails, we assume they finished the game and reload the title screen
            except:
                screen.blit(loading_bar, (0,0))
                congrats = font.render("Congratulations! You've conquered your fears and escaped Asylum!", True, (255, 255, 255))
                screen.blit(congrats, (0,0))
                print "blitted congrats"
                pygame.display.update()
                pause.sleep(5)
                False
                current_level = 0 # Reset the level counter so clicking play again doesn't crash the game
                coin_count = 0 # Reset coin count
                delete_door = True # Reset the door deletion status (True means the door can be removed)
                # Since we're heading back to the title menu, let's bring back the title screen music.
                pygame.mixer.pre_init(44100, -16, 2, 2048)
                sounds = Sounds()
                titleScreen()
            for row in level:
                for col in row:
                    if col == "P":
                        p = Platform(x, y)
                        platforms.insert(0, p)
                        entities.add(p)
                    if col == "C":
                        charX = x
                        charY = y
                        player = Player(charX, charY)
                    if col == "A":
                        spike = Spike(x, y, 1)
                        entities.add(spike)
                        spikes.add(spike)
                    if col == "V":
                        spike = Spike(x, y, 2) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == ">":
                        spike = Spike(x, y, 3) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == "<":
                        spike = Spike(x, y, 4) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == "M":
                        monster = Monster(x, y) # Load a spike at the x,y found 
                        entities.add(monster) # Add the spike to the entities
                        monsters.add(monster) # Add the spike to the spike sprite group for collison purposes
                    if col == "K":
                        c1 = Coins(x, y)
                        entities.add(c1)
                        coin_list.append(c1)
                        coinA.add(c1)
                    if col == "X":
                        win_object = Trophy(x, y)
                        entities.add(win_object)
                        trophies.add(win_object)
                    if col == "T":
                        doorA = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked1.png"), (60,100)))
                        platforms.append(doorA) # Make the door top a platform so the player cannot walk through it
                        entities.add(doorA) # Add the door bottom to the entities
                    if col == "B":
                        doorB = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked2.png"), (60,32)))
                        platforms.append(doorB) # Make the door bottom a platform so the player cannot walk through it
                        entities.add(doorB) # Add the door bottom to entities
                    x += 32
                y += 32
                x = 0
            """
            player.update(up, down, left, right, running, platforms)
            for e in entities:
                screen.blit(e.image, camera.apply(e))
            """
            pygame.display.update()
            delete_door = True # reset door status
            player.dead = False # ensure the player isn't dead
            entities.add(player)

        # Player collision with spike; if true, kill the player
        if pygame.sprite.spritecollide(player, spikes, False, pygame.sprite.collide_mask):
            player.dead = True
        if pygame.sprite.spritecollide(player, monsters, False, pygame.sprite.collide_mask):
            player.dead = True

        for m in monsters:
            m.sensePlayers(player, platforms)

        # If the player is dead, reset all key strokes to False, play the death sound, empty all groups and lists and reload the level, add one to both total and level deaths
        if player.dead == True:
            up = False
            right = False
            left = False
            sounds.death_sound.play()
            sounds.death_sound.set_volume(volume)
            player = Player(charX, charY)
            platforms = None
            level = None
            x = 0
            y = 0
            doorA.kill()
            doorB.kill()
            entities.empty()
            trophies.empty()
            spikes.empty()
            coinA.empty()
            monsters.empty()
            gc.collect()
            pause.sleep(1)
            key_count = 0
            platforms = []
            level = open('levels/level' + str(current_level) + '.txt', 'r')
            deaths += 1
            deaths_total += 1
            for row in level:
                for col in row:
                    if col == "P":
                        p = Platform(x, y)
                        platforms.insert(0, p)
                        entities.add(p)
                    if col == "C":
                        charX = x
                        charY = y
                        player = Player(charX, charY)
                    if col == "A":
                        spike = Spike(x, y, 1)
                        entities.add(spike)
                        spikes.add(spike)
                    if col == "V":
                        spike = Spike(x, y, 2) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == ">":
                        spike = Spike(x, y, 3) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == "<":
                        spike = Spike(x, y, 4) # Load a spike at the x,y found 
                        entities.add(spike) # Add the spike to the entities
                        spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
                    if col == "M":
                        monster = Monster(x, y) # Load a spike at the x,y found 
                        entities.add(monster) # Add the spike to the entities
                        monsters.add(monster) # Add the spike to the spike sprite group for collison purposes
                    if col == "K":
                        c1 = Coins(x, y)
                        entities.add(c1)
                        coin_list.append(c1)
                        coinA.add(c1)
                    if col == "X":
                        win_object = Trophy(x, y)
                        entities.add(win_object)
                        trophies.add(win_object)
                    if col == "T":
                        doorA = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked1.png"), (60,100)))
                        platforms.append(doorA) # Make the door top a platform so the player cannot walk through it
                        entities.add(doorA) # Add the door bottom to the entities
                    if col == "B":
                        doorB = Door(x, y, pygame.transform.scale(pygame.image.load("images/door_locked2.png"), (60,32)))
                        platforms.append(doorB) # Make the door bottom a platform so the player cannot walk through it
                        entities.add(doorB) # Add the door bottom to entities
                    x += 32
                y += 32
                x = 0
                delete_door = True
                player.dead = False
            entities.add(player) # Readd the player to the entities

        # If the coin count is four, then set the door status to False, kill the door sprites and remove from the platforms list
        # When delete_door is True it means the door can be removed when the coins are all collected; False means it's been opened. This check was added to prevent it from continually playing the sounds.
        if key_count >= 1 and delete_door == True:
            sounds.door.play()
            sounds.door.set_volume(volume)
            for x in xrange(2): # Since we ensure doors are added to the end of the list, we can just remove the last two items in the platforms list safely
                del platforms[-1]
            delete_door = False # now the door status is False
            doorA.kill() # Kill doorA and doorB (makes it disappear (the door has "opened"))
            doorB.kill()

        camera.update(player)

        # Update the player and everything else
        missiles.update()
        pygame.sprite.groupcollide(missiles, platforms, True, False)
        missiles.draw(screen)
        player.update(up, down, left, right, running, platforms)
        for e in entities:
            screen.blit(e.image, camera.apply(e))

        pygame.display.update() # Update the display
Ejemplo n.º 36
0
class levelLoader(object):
	""" 
	This class actually handles a lot of things; while also handling the level loading, it also must be used to call from another class in the game
	class itself.  For example, to use anything from the Player class, the user must have levelLoader.getPlayer().functionHere.
	In all honesty, this class handles pretty much everything that has anything to do with levels.
	"""
	def __init__(self):
		self.level = 0
		self.platforms = []

		self.doorsClosed = True

		self.entities = pygame.sprite.Group()
		self.coin = pygame.sprite.Group()
		self.spikes = pygame.sprite.Group()
		self.trophies = pygame.sprite.Group()
		self.x = 0
		self.y = 0

		self.levelCoins = 0
		self.loadedCoins = False

		self.showDebug = False

	def buildLevel(self):
		"""
		KEY FOR LEVELS
        P = Platform
        C = player starting position
        A = Spike (Up)    - 1
        V = Spike (Down)  - 2
        > = Spike (Right) - 3
        < = Spike (Left)  - 4
        K = Key
        X = Trophy
        T = Door Top
        B = Door Bottom
        O = Coin
        """
		level = open(Directory.getDirectory() + '/levels/level' + str(self.level) + '.txt', 'r')
		for row in level:
		    for col in row:
		    	if col.isdigit() and self.loadedCoins == False:
		    		if int(col) > 0:
		    			self.loadedCoins = True
		    			self.levelCoins = int(col)
		    		else:
		    			self.loadedCoins = True
		    			self.levelCoins = 1
		        if col == "P":
		            p = Platform(self.x, self.y) # Place a platform at the given x,y
		            self.platforms.insert(0, p) # Insert it into the platforms list
		            self.entities.add(p) # Add to entities so it appears on screen
		        if col == "C":
					self.charX = self.x # The character x found from file loading
					self.charY = self.y # The character y found from file loading
					self.player = Player(self.charX, self.charY) # Set the player along with the x,y of the starting position
		        if col == "A":
		            spike = Spike(self.x, self.y, 1) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "V":
		            spike = Spike(self.x, self.y, 2) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == ">":
		            spike = Spike(self.x, self.y, 3) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "<":
		            spike = Spike(self.x, self.y, 4) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "O":
					coin = Coins(self.x, self.y) # Load a coin image at the given x,y
					self.entities.add(coin) # Coin 1 to the entities
					self.coin.add(coin) # add coin 1 to the coinA sprite group
		        if col == "X":
					try:
						win_object = Trophy(self.x, self.y, self.level) # Load the proper trophy by passing the level to the trophy class and load at the given x,y from file loading
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
					except:
						win_object = Trophy(self.x, self.y, 0)
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
		        if col == "T":
		            self.doorA = Door(self.x, self.y)
		            self.platforms.append(self.doorA) # Make the door top a platform so the player cannot walk through it
		            self.entities.add(self.doorA) # Add the door bottom to the entities
		        if col == "B":
		            self.doorB = Door(self.x, self.y)
		            self.platforms.append(self.doorB) # Make the door bottom a platform so the player cannot walk through it
		            self.entities.add(self.doorB) # Add the door bottom to entities
		        self.x += 32
		    self.y += 32
		    self.x = 0

		# Try loading in the level image and theme; if it fails, use level 0 theme and background
		try:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background' + str(self.level) + '.png').convert_alpha()
		    self.background_rect = self.background.get_rect()
		except:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background0.png').convert_alpha()
		    self.background_rect = self.background.get_rect()

	def getPlayer(self):
		return self.player

	def getPlatforms(self):
		return self.platforms

	def getEntities(self):
		return self.entities

	def getCoins(self):
		return self.coin

	def getTrophy(self):
		return self.trophies

	def getSpikes(self):
		return self.spikes

	def getBGWidth(self):
		return self.background_rect.w

	def getBGHeight(self):
		return self.background_rect.h

	def getBackground(self):
		return self.background

	def delPlatforms(self):
		del self.platforms[-1]

	def delDoors(self):
		self.doorsClosed = False
		self.doorA.kill()
		self.doorB.kill()

	def rebuildDoors(self):
		self.doorsClosed = True

	def doorStatus(self):
		return self.doorsClosed

	def clearScreen(self):
		self.player.onGround = True
		self.x = 0
		self.y = 0
		self.loadedCoins = False
		level = self.level
		self.platforms = None
		self.doorA.kill()
		self.doorB.kill()
		self.entities.empty()
		self.trophies.empty()
		self.spikes.empty()
		self.coin.empty()

	def rebuildObjects(self):
		self.level = self.level
		self.platforms = []
		self.doorsClosed = True
		self.player = Player(self.charX, self.charY)
		self.entities = pygame.sprite.Group()
		self.coin = pygame.sprite.Group()
		self.spikes = pygame.sprite.Group()
		self.trophies = pygame.sprite.Group()
		self.x = 0
		self.y = 0
		self.player.dead = False
		self.player.up = False
		self.player.right = False
		self.player.left = False
		self.player.running = False

	def addLevel(self):
		self.level += 1

	def resetLevel(self):
		self.level = 0

	def getLevel(self):
		return self.level

	def loadingBar(self):
		return self.loadingBar

	def getLevelCoins(self):
		return self.levelCoins

	def infoScreen(self):
		self.debug = Display.font.render("Information Window", True, (255,255,255))
		self.death_status = Display.font.render("player.canDie: " + str(self.getPlayer().canDie), True, (255,255,255))
		self.door_status = Display.font.render("door_closed: " + str(self.doorsClosed), True, (255,255,255))
		self.coin_debug = Display.font.render("coin_count: " + str(self.getPlayer().getCoins()), True, (255,255,255))
		Display.screen.blit(self.debug, (0,0))
		Display.screen.blit(self.death_status, (0,25))
		Display.screen.blit(self.door_status, (0,50))
		Display.screen.blit(self.coin_debug, (0,75))
 def test_door_toggle_from_True_to_False(self):
     result = Door(0)
     result.toggle()
     result.toggle()
     self.assertEqual(result.is_open, False)
Ejemplo n.º 38
0
	def buildLevel(self):
		"""
		KEY FOR LEVELS
        P = Platform
        C = player starting position
        A = Spike (Up)    - 1
        V = Spike (Down)  - 2
        > = Spike (Right) - 3
        < = Spike (Left)  - 4
        K = Key
        X = Trophy
        T = Door Top
        B = Door Bottom
        O = Coin
        """
		level = open(Directory.getDirectory() + '/levels/level' + str(self.level) + '.txt', 'r')
		for row in level:
		    for col in row:
		    	if col.isdigit() and self.loadedCoins == False:
		    		if int(col) > 0:
		    			self.loadedCoins = True
		    			self.levelCoins = int(col)
		    		else:
		    			self.loadedCoins = True
		    			self.levelCoins = 1
		        if col == "P":
		            p = Platform(self.x, self.y) # Place a platform at the given x,y
		            self.platforms.insert(0, p) # Insert it into the platforms list
		            self.entities.add(p) # Add to entities so it appears on screen
		        if col == "C":
					self.charX = self.x # The character x found from file loading
					self.charY = self.y # The character y found from file loading
					self.player = Player(self.charX, self.charY) # Set the player along with the x,y of the starting position
		        if col == "A":
		            spike = Spike(self.x, self.y, 1) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "V":
		            spike = Spike(self.x, self.y, 2) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == ">":
		            spike = Spike(self.x, self.y, 3) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "<":
		            spike = Spike(self.x, self.y, 4) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "O":
					coin = Coins(self.x, self.y) # Load a coin image at the given x,y
					self.entities.add(coin) # Coin 1 to the entities
					self.coin.add(coin) # add coin 1 to the coinA sprite group
		        if col == "X":
					try:
						win_object = Trophy(self.x, self.y, self.level) # Load the proper trophy by passing the level to the trophy class and load at the given x,y from file loading
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
					except:
						win_object = Trophy(self.x, self.y, 0)
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
		        if col == "T":
		            self.doorA = Door(self.x, self.y)
		            self.platforms.append(self.doorA) # Make the door top a platform so the player cannot walk through it
		            self.entities.add(self.doorA) # Add the door bottom to the entities
		        if col == "B":
		            self.doorB = Door(self.x, self.y)
		            self.platforms.append(self.doorB) # Make the door bottom a platform so the player cannot walk through it
		            self.entities.add(self.doorB) # Add the door bottom to entities
		        self.x += 32
		    self.y += 32
		    self.x = 0

		# Try loading in the level image and theme; if it fails, use level 0 theme and background
		try:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background' + str(self.level) + '.png').convert_alpha()
		    self.background_rect = self.background.get_rect()
		except:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background0.png').convert_alpha()
		    self.background_rect = self.background.get_rect()
Ejemplo n.º 39
0
        doneplaying.wait()


        doneplaying.clear()

        openevent.wait(10)
        if openevent.is_set():
            closedevent.wait()
            # let em clear out

        light.turnon()
        eyes.turnoff()

        threading.Timer(5, lambda: scaring.clear()).start()

door = Door(args=(open_callback, close_callback, closedevent), kwargs={'gpio_door': 11})

        
dist = Distance(args=(distance_callback, 190),
               kwargs={'gpio_trigger': 16,
                      'gpio_echo': 18})

def stopthreads():
    light.fullon()
    spk.stop()
    dist.stop()
    light.stop()
    eyes.stop()
    door.stop()

    eyes.join(1)