Exemple #1
0
    def __init__(self, nest=None, gpio=None, ifttt=None):
        Zone.__init__(self, nest=nest, gpio=gpio, ifttt=ifttt)

        self.logger = logging.getLogger('HVAC.Zone.LivingRoom')

        self.display_name = "Living Room"

        # ifff action and response retry value (0 = no wait for an activation, assume it worked)
        self.ifttt_cool_on = ("livingroom_ac_on", 0)
        self.ifttt_cool_off = ("livingroom_ac_off", 0)
        self.ifttt_cooling_on = ("livingroom_ac_cool", 30)
        self.ifttt_cooling_off = ("livingroom_ac_eco", 30)
        self.ifttt_cooling_temp = ("livingroom_ac_set_%s", 0)

        self.ifttt_heating_on = ("livingroom_heat_on", 0)
        self.ifttt_heating_off = ("livingroom_heat_off", 0)

        # Current Living Room settings
        # GE (Haier) AEC10AX 10,000BTU 120V
        self.ac_min = 64
        self.ac_max = 86
        self.ac_temp_default = 70  # Default temp if no info from the thermostat
        self.ac_cooling_on_offset = -10  # When cooling drop temp by N degrees
        self.ac_cooling_off_offset = 2  # When NOT cooling raise temp by N degrees

        # Nest specific settings
        self.therm_name = "Living Room Thermostat"  # Nest name_long

        # GPIO specific settings
        self.gpio_cool = 1 << 2  # Living room cool stage 1
        self.gpio_heat = 1 << 6  # Living room heat stage 2
Exemple #2
0
 def getZone(self, zoneType, game, event=None, player=None):
     """ Return the zone for the given zone type and game """
     if zoneType == zone_types.CHARACTER:
         return CharacterZone(game.currentTurn.player.character)
     elif zoneType == zone_types.DECK:
         return DeckWithDiscardPileZone(player.deck, zoneType=zone_types.DECK)
     if zoneType == zone_types.DESTROYED:
         return DeckZone(game.destroyedDeck, zoneType=zone_types.DESTROYED)
     elif zoneType == zone_types.DISCARD_PILE:
         return DeckZone(player.discardPile, zoneType=zone_types.DISCARD_PILE)
     elif zoneType == zone_types.EVENT:
         return EventZone(event)
     elif zoneType == zone_types.GAINED:
         return GainedZone(game.currentTurn.gainedCards, self.getZone(zone_types.DISCARD_PILE, game, event=event, player=player))
     elif zoneType == zone_types.HAND:
         return ListZone(player.hand, zoneType=zone_types.HAND)
     elif zoneType == zone_types.KICK:
         return DeckZone(game.kickDeck, zoneType=zone_types.KICK)
     elif zoneType == zone_types.LINE_UP:
         return Zone(game.lineUp)
     elif zoneType == zone_types.MAIN_DECK:
         return DeckZone(game.mainDeck, zoneType=zone_types.MAIN_DECK)
     elif zoneType == zone_types.ONGOING:
         return ListZone(player.ongoing, zoneType=zone_types.ONGOING)
     elif zoneType == zone_types.PLAYED:
         return ListZone(game.currentTurn.playedCards, zoneType=zone_types.PLAYED)
     elif zoneType == zone_types.SUPERVILLAIN:
         return Zone(game.superVillainStack, zoneType=zone_types.SUPERVILLAIN)
     elif zoneType == zone_types.UNDER_CHARACTER:
         return ListZone(player.underCharacter, zoneType=zone_types.UNDER_CHARACTER)
     elif zoneType == zone_types.WEAKNESS:
         return DeckZone(game.weaknessDeck, zoneType=zone_types.WEAKNESS)
     return None
Exemple #3
0
    def __init__(self, eng):
        self.eng = eng  # get the engine

        # Set up all sprite groups
        self.all_sprites = pg.sprite.Group()  # everything
        self.background = pg.sprite.Group()  # background tiles
        self.foreground = pg.sprite.Group()  # non-interacting blocks
        self.blocks = pg.sprite.Group()  # non-moving sprites that interact
        self.players = pg.sprite.Group()  # sprites you can control
        self.friends = pg.sprite.Group()  # moving friendly sprites
        self.foes = pg.sprite.Group()  # enemies
        self.hud = pg.sprite.Group()  # HUD (health, money etc.)
        self.misc = pg.sprite.Group()  # other (dialog boxes etc.)

        # set up the groups list (this is the order in which you want them to
        #   be drawn)
        self.groups_list = [
            self.background, self.foreground, self.blocks, self.players,
            self.friends, self.foes, self.hud, self.misc
        ]
        # define groups that are diegetic (i.e. groups that exist in the game
        # world and will be affected by camera movement) EXCLUDES players
        self.diegetic_groups = [
            self.background, self.foreground, self.blocks, self.friends,
            self.foes
        ]
        # set up player
        self.player = Player(self)

        # Zone class will set up the blocks and background
        self.current_zone = Zone(self, "zone1")
Exemple #4
0
def get_test_zone2():
    '''(NoneType) -> Zone'''
    test_zone = Zone()

    test_zone.load("test.txt")

    return test_zone
Exemple #5
0
    def __init__(self, nest=None, gpio=None, ifttt=None):
        Zone.__init__(self, nest=nest, gpio=gpio, ifttt=ifttt)

        self.logger = logging.getLogger('HVAC.Zone.CatRoom')

        self.display_name = "Cat Room"

        # ifff action and response retry value (0 = no wait for an activation, assume it worked)
        self.ifttt_cool_on = ("catroom_ac_on", 0)
        self.ifttt_cool_off = ("catroom_ac_off", 0)
        self.ifttt_cooling_on = ("catroom_ac_cool", 30)
        self.ifttt_cooling_off = ("catroom_ac_eco", 30)
        self.ifttt_cooling_temp = ("catroom_ac_set_%s", 0)

        self.ifttt_heating_on = ("catroom_heat_on", 0)
        self.ifttt_heating_off = ("catroom_heat_off", 0)

        # Current Living Room settings
        # GE (Haier) AEC10AX 10,000BTU 120V
        self.ac_min = 64
        self.ac_max = 86
        self.ac_temp_default = 70  # Default temp if no info from the thermostat
        self.ac_cooling_on_offset = -4  # When cooling drop temp by N degrees
        self.ac_cooling_off_offset = 4  # When NOT cooling raise temp by N degrees

        # Nest specific settings
        # Since the room is shared with the living room, we use this
        # as the basis of which mode we're in.  Note, Amy's room controls
        # the radiator heat for this room, but living room controls plugin heater.
        self.therm_name = "Living Room Thermostat"  # Nest name_long

        # GPIO specific settings
        self.gpio_cool = 1 << 3  # Living room cool stage 2
        self.gpio_heat = 1 << 1  # Living room heat stage 3
Exemple #6
0
 def turn_off_cooling(self):
     Zone.turn_off_cooling(self)
     if self.ac_cooling == False:
         hour = datetime.datetime.now()
         # If it's between 10pm and 8am, set the fan to -low-
         if hour.hour >= 22 or hour.hour < 8:  # 10pm to 8am
             self.cooling_fan_speed('low')
         else:
             self.cooling_fan_speed('auto')
Exemple #7
0
 def __init__(self, event):
     """ Initialize the zone """
     zoneType = None
     self.event = event
     if hasattr(event, "fromZone") and event.fromZone is not None:
         zoneType = event.fromZone.zoneType
     elif hasattr(event, "zones") and event.zones is not None and len(event.zones) > 0:
         zoneType = event.zones[0].zoneType
     Zone.__init__(self, event, zoneType=zoneType)
Exemple #8
0
def test_exceptions():
    with pytest.raises(ValueError):
        z1 = Zone(0)

    with pytest.raises(ValueError):
        z2 = Zone([1, 2, 3])

    with pytest.raises(ValueError):
        z3 = Zone([1, 2])
Exemple #9
0
 def turn_on_cooling(self):
     Zone.turn_on_cooling(self)
     if self.ac_cooling == True:
         hour = datetime.datetime.now()
         if hour.hour >= 22 or hour.hour < 8:  # 10pm to 8am
             self.cooling_fan_speed('low')
         elif hour.hour >= 10 and hour.hour < 18:  # 10am to 6pm
             self.cooling_fan_speed('high')
         else:  # 8am to 10am and 6pm to 10pm
             self.cooling_fan_speed('auto')
Exemple #10
0
 def __init__(self, event):
     """ Initialize the zone """
     zoneType = None
     self.event = event
     if hasattr(event, "fromZone") and event.fromZone is not None:
         zoneType = event.fromZone.zoneType
     elif hasattr(
             event,
             "zones") and event.zones is not None and len(event.zones) > 0:
         zoneType = event.zones[0].zoneType
     Zone.__init__(self, event, zoneType=zoneType)
Exemple #11
0
    def loadZone(self, name, path):
        if path[len(path)-1] != '/':
            path += '/'

        if self.zone:
            self.zone.rootNode.removeNode()
            
        self.zone = Zone(self, name, path)
        error = self.zone.load()
        if error == 0:
            self.consoleOff()
            self.setFlymodeText()
            base.setBackgroundColor(self.fog_colour)
Exemple #12
0
def main(opt):
    configureLogger(opt.verbose)
    if opt.clean:
        log.warning("cleaning the build directory")
        shutil.rmtree('build')
    zone = Zone('Library')
    zone.build(pcs() + npcs() + morphs() + libTokens())
    ecp = Campaign('eclipse')
    dmScreen = Zone('DM Screen')
    ecp.build([zone, dmScreen], propertySets(),
              [eclipseTable(), nameTable(),
               morphTable()])
    log.warning('Done building %s with a total of %s macros, %s assets' %
                (ecp, len(list(ecp.macros)), len(list(ecp.assets))))
    return ecp
Exemple #13
0
    def perspective_onZoneTrigger(self,simObject,zoneLink):#,zoneIn):
        if simObject not in self.simObjects:
            traceback.print_stack()
            print "AssertionError: simObject is not in SimAvatars simObject list!"
            return
        if not self.playerLookup.has_key(simObject):
            traceback.print_stack()
            print "AssertionError: simObject is not in SimAvatars playerLookup list!"
            return


        from zone import Zone,ZoneLink

        zlink = ZoneLink.byName(zoneLink)
        
        player = self.playerLookup[simObject]
        if player.zone:
            z = Zone.byName(zlink.dstZoneName)
            czone = player.zone.zone
            
            if czone == z:
                #good
                #we just need to respawn player, whew
                player.zone.respawnPlayer(player,zlink.dstZoneTransform)
                return


        #we want to present the player with a choice of active zones 
        #and/or to launch their own zone instance (if they are allowed to)
        self.world.onZoneTrigger(self.playerLookup[simObject],zlink)
Exemple #14
0
def setup():
    global zones
    GPIO.setmode(GPIO.BCM)
    data = []
    try:
        with open(STATE_FILE) as json_file:
            data = json.load(json_file)
    except:
        logging.debug("State file not available - ignoring")
    print(data)
    if str(1) in data:
        logging.info("State file found for zone %d - Value %f" %
                     (1, data[str(1)]))
        zones.append(Zone(1, 14, 17, data[str(1)]))
    else:
        zones.append(Zone(1, 14, 17))
Exemple #15
0
    def __init__(self, bot, leader: discord.Member, players: [discord.Member],
                 zone: Zone, channel: discord.TextChannel, restart: bool):
        self.bot = bot
        self.leader = leader
        self.players = players
        self.players.append(leader)
        self.characters = []
        cc = bot.get_cog('CharacterController')

        for player in players:
            char = cc.get(player)
            char.reset_stats()
            self.characters.append(char)

        self.zone = zone

        if restart:
            leader_char = cc.get(leader)

            if zone.name in leader_char.depths.keys():
                self.depth = zone.get_restart_level(
                    leader_char.get_depth_progress(zone.name))
        else:
            self.depth = 1

        self.solo = True if len(players) == 1 else False
        self.channel = channel
        self.current_room = self.zone.get_next_room(self.characters,
                                                    self.depth)
        self.status = 'idle'  # idle, fighting
def CmdTP(mob,args):
    player = mob.player
    zname = args[0]
    
    if zname.lower() == 'bindstone':
        if player.darkness:
            z = player.darknessBindZone
            trans = player.darknessBindTransform
        elif player.monster:
            z = player.monsterBindZone
            trans = player.monsterBindTransform
        else:
            z = player.bindZone
            trans = player.bindTransform
        dst = ' '.join(str(i) for i in trans)
    else:
        try:
            z = Zone.byName(zname)
            dst = z.immTransform
        except:
            mob.player.sendGameText(RPG_MSG_GAME_DENIED,"Unknown zone or zone not setup for immortal command %s.\\n"%zname)
            return
    
    #are we in the same zone?
    if player.zone.zone == z:
        #good
        #we just need to respawn player, whew
        player.zone.respawnPlayer(player,dst)
    else:
        from zone import TempZoneLink
        zlink = TempZoneLink(zname,dst)
        player.world.onZoneTrigger(player,zlink)
def CmdTP(mob, args):
    player = mob.player
    zname = args[0]

    if zname.lower() == 'bindstone':
        if player.darkness:
            z = player.darknessBindZone
            trans = player.darknessBindTransform
        elif player.monster:
            z = player.monsterBindZone
            trans = player.monsterBindTransform
        else:
            z = player.bindZone
            trans = player.bindTransform
        dst = ' '.join(str(i) for i in trans)
    else:
        try:
            z = Zone.byName(zname)
            dst = z.immTransform
        except:
            mob.player.sendGameText(
                RPG_MSG_GAME_DENIED,
                "Unknown zone or zone not setup for immortal command %s.\\n" %
                zname)
            return

    #are we in the same zone?
    if player.zone.zone == z:
        #good
        #we just need to respawn player, whew
        player.zone.respawnPlayer(player, dst)
    else:
        from zone import TempZoneLink
        zlink = TempZoneLink(zname, dst)
        player.world.onZoneTrigger(player, zlink)
Exemple #18
0
 def setZones(self, zones):
     try:
         if type(zones[0]) <> type(Zone()):
             print 'The argument must be a Zone list'
     except:
         print 'The argument must be a Zone list'
         pass
    def __init__(self):
        self.zone = Zone(100, 100)

        self.merchants = {}
        self.init_merchants(20)

        self.order = {}
Exemple #20
0
    def __init__(self, nest=None, gpio=None, ifttt=None):
        Zone.__init__(self, nest=nest, gpio=gpio, ifttt=ifttt)

        self.logger = logging.getLogger('HVAC.Zone.AmysRoom')

        self.display_name = "Amy's Bedroom"

        # ifttt action and response retry value (0 = no wait for an activation, assume it worked)
        self.ifttt_heating_on = ("amysroom_heat_on", 0)
        self.ifttt_heating_off = ("amysroom_heat_off", 0)

        # Nest specific settings
        self.therm_name = "Amy's Bedroom Thermostat"  # Long Name

        # GPIO specific settings
        self.gpio_heat = 1 << 0  # Amy's room stage 2 heat
Exemple #21
0
 def __iter__(s):
     center(s.__class__.__name__)
     s.__fetch_if_needed()
     for item in s.__zones:
         n = Zone(s.__maas, item)
         yield n
     cleave(s.__class__.__name__)
Exemple #22
0
def build_zone_list(term="\n"):
    debug = 1
    if (debug == 1):
        print("in build_zone_list()")

    startZ = 1
    csvindex = 0
    list_of_zones = list()

    #build list of zones from file
    with open('zonedata.csv') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in reader:
            data = row[0]

            if (startZ == 1):
                #zone title
                ztemp = Zone(data)
                list_of_zones.append(ztemp)
                startZ = 0
            elif ("Meta" in data):
                list_of_zones[csvindex].set_meta(data)
            elif ("Policy" in data):
                list_of_zones[csvindex].set_policy(data)
            elif (data == "****"):
                #end of zone section
                startZ = 1
                csvindex = csvindex + 1
            else:
                tmp_net = Network(data)
                list_of_zones[csvindex].add_network(tmp_net)
        #end of for row
    #end of csv

    return (list_of_zones)
Exemple #23
0
    def __init__(self, nest=None, gpio=None, ifttt=None):
        Zone.__init__(self, nest=nest, gpio=gpio, ifttt=ifttt)

        self.logger = logging.getLogger('HVAC.Zone.DiningRoom')

        self.display_name = "Dining Room"

        # ifff action and response retry value (0 = no wait for an activation, assume it worked)
        self.ifttt_heating_on   = ( "dining_room_heat_on", 0 )
        self.ifttt_heating_off   = ( "dining_room_heat_off", 0 )

        # Nest specific settings
        # Since the room is shared with the living room, we use this
        # as the basis of which mode we're in.
        self.therm_name  = "Living Room Thermostat" # Nest name_long

        # GPIO specific settings
        self.gpio_heat    = 1 << 1  # Living room heat stage 3
Exemple #24
0
 def __init__(self):
     self.zones = []
     self.no_mines_left = 0
     for x in range(10):
         self.zones.append([])
         for y in range(10):
             mine = bool(randint(0,9) < 1)
             if mine: self.no_mines_left += 1
             self.zones[x].append(Zone(x, y, mine))
Exemple #25
0
    def loadZone(self, name, path):
        if path[len(path) - 1] != "/":
            path += "/"

        if self.zone:
            self.zone.rootNode.removeNode()

        self.zone = Zone(self, name, path)
        error = self.zone.load()
        if error == 0:
            self.consoleOff()
            self.setFlymodeText()
            base.setBackgroundColor(self.fog_colour)
Exemple #26
0
def main():
    Zone.status += status_callback
    Zone.success += success_callback
    Zone.download_progress += save_callback

    global term_width
    term_width = get_terminal_size()[0]

    global args
    args = parse_args()

    username = args.username
    if not username:
        if 'APPD_SSO_USERNAME' in os.environ:
            username = os.environ['APPD_SSO_USERNAME']
        else:
            print 'Username: '******'APPD_SSO_PASSWORD' in os.environ:
            password = os.environ['APPD_SSO_PASSWORD']
        else:
            password = getpass.getpass()

    z = Zone(args.zone, args.version,
             username=username, password=password, debug=args.debug)

    if args.no_download:
        print z.get_url(args.product, platform=args.os, bits=args.bits, package=args.format)
    else:
        z.download_product(args.product, platform=args.os, bits=args.bits, package=args.format, output=args.output)

    if not args.quiet:
        print 'Done!'

    sys.exit(0)
Exemple #27
0
    def __prepareZones(self):
        last = -1
        while 1:
            # getting where is 'include' directive
            pos = self.contents.find('zone ', last + 1)
            if pos == -1: return None
            # fix
            if pos > 1:
                char = self.contents[pos - 1]
                if char <> '\n' and char <> '\r' and \
                   char <> ' '  and char <> '\t' and \
                   char <> ';':
                    return None
            # marking 'include' position
            last = pos

            # creating a Zone instance
            thisZone = Zone()
            try:
                OneZonePart = self.contents[pos:].split('}')[0]
                # Getting Name
                thisZone.setName(self.__getStr(OneZonePart.split('{')[0]))
                # Getting Filename
                thisZone.setFile(
                    self.__getStr(OneZonePart.split('file')[1].split(';')[0]))
                #Getting type
                if OneZonePart.split('type')[1].split(';')[0].upper().find(
                        'SLAVE') <> -1:
                    thisZone.setType('slave')
                else:
                    thisZone.setType('master')

                self.zones.append(thisZone)
            except:
                pass

            # destroying thisZone instance
            thisZone = None
Exemple #28
0
def test_fields():

    # sample areas
    a1 = Area(name="area1",
              desc="area desc",
              domain=[8],
              action=lambda: 1,
              resource_id="r_id")
    a2 = Area(name="area2",
              desc="area desc",
              domain=[9],
              action=lambda: 0,
              resource_id="r_id")

    # test initialization
    areas = [a1, a2]
    z = Zone(areas)

    # test fields
    assert z.areas == areas

    # test dump
    assert z.dump() == [a1.dump(), a2.dump()]
Exemple #29
0
    def __init__(self, mac_data, timestep):
        #print "Wifimodel constructor %s" % self
        self.essid = ""
        self.macaddress = mac_data

        self.zone_raw = Zone()
        self.zone_predicted = Zone()

        self.rssi_raw = 0
        self.rssi_predicted = 0
        self.rssi_delta = 0
        self.rssi_step_delta = 0
        self.rssi_step_predicted = 0

        self.timestamp = 0
        self.timestamp_step_delta = 0

        self.quality_raw = 0
        self.quality_max = 0
        self.aged = 0
        self.history = list() 

        self.cla_model = Predictor(timestep)
Exemple #30
0
	def __init__(self, authtoken):
		self.server = 'https://api.rach.io/1/public/'
		self.headers = {
			'Content-Type': 'application/json',
			'Authorization': 'Bearer %s' % authtoken
			}
		self.h = httplib2.Http('.cache')

		self.person = Person(self)
		self.device = Device(self)
		self.zone = Zone(self)
		self.schedulerule = Schedulerule(self)
		self.flexschedulerule = FlexSchedulerule(self)
		self.notification = Notification(self)
Exemple #31
0
def qca_sim(fn, **kwargs):
    '''Simulate all possible outcomes for each zone of a given qca circuit'''

    # parse QCADesigner file
    cells, spacing, zones, J, feedback = parse_qca_file(fn, show=False)

    # check for specification of adjacency type
    if 'adj' in kwargs:
        if kwargs['adj'].lower() == 'full':
            J = convert_to_full_adjacency(cells, spacing, J)
        elif kwargs['adj'].lower() == 'lim':
            J = convert_to_lim_adjacency(cells, spacing, J)

    # set the solver type
    if 'solver' in kwargs:
        try:
            solver = SOLVERS[kwargs['solver'].lower()]
        except:
            print('No solver specified. Using default...')
            solver = SOLVERS['default']
    else:
        solver = SOLVERS['default']

    # set up zone formulation
    Gz = construct_zone_graph(cells, zones, J, feedback, show=False)
    Zones = {key: Zone(key, Gz, J, cells, feedback) for key in Gz.nodes()}
    # solve every zone for every possible set of inputs
    solution = Solution(Gz)
    for i in xrange(len(zones)):
        for j in xrange(len(zones[i])):
            key = (i, j)
            cases, outs, z_order = Zones[key].solve_all(solver)
            solution.add_zone(Zones[key], outs, z_order)

    # write solution to file
    solution.write_to_file('./qca_sim_test')

    # run solution inputs (single sets)
    input_inds = solution.get_inputs()

    input_pols = gen_pols(len(input_inds))  # set of all possible input pols

    print 'start'
    out = {}  # dict of outputs lists for each input polarization list
    for pols in input_pols:
        input_pol = {(0, 0): [(pols, )]}
        out[pols] = solution.run_input_sequence(input_pol)

    pprint(out)
Exemple #32
0
def main():

    for agents_attributes in json.load(
            open("agents-100k.json")):  #read from json file
        longitude = agents_attributes.pop('longitude')
        latitude = agents_attributes.pop('latitude')
        pos = Position(longitude,
                       latitude)  # create a new position for every agent
        agent = Agent(pos, **agents_attributes)  # create the agent
        zone = Zone.find_zone_that_contains(
            pos)  # find the zone in which the agent exist
        zone.add_inhabitant(agent)  # add the agent in this zone

    agreeableness_graph = AgreeablenessGraph()  # initialise the graph
    agreeableness_graph.show(Zone.ZONES)
Exemple #33
0
    def __init__(self, nest=None, gpio=None, ifttt=None):
        Zone.__init__(self, nest=nest, gpio=gpio, ifttt=ifttt)

        self.logger = logging.getLogger('HVAC.Zone.MarksRoom')

        self.display_name = "Mark's Room"

        # ifff action and response retry value (0 = no wait for an activation, assume it worked)
        self.ifttt_cool_on = ("marksroom_ac_on", 0)
        self.ifttt_cool_off = ("marksroom_ac_off", 0)
        self.ifttt_cooling_on = ("marksroom_ac_cool", 30)
        self.ifttt_cooling_off = ("marksroom_ac_eco", 30)
        self.ifttt_cooling_temp = ("marksroom_ac_set_%s", 0)

        self.ifttt_cooling_fan_auto = ("marksroom_ac_fan_auto", 0)
        self.ifttt_cooling_fan_high = ("marksroom_ac_fan_high", 0)
        self.ifttt_cooling_fan_med = ("marksroom_ac_fan_med", 0)
        self.ifttt_cooling_fan_low = ("marksroom_ac_fan_low", 0)

        #self.ifttt_fan_on       = ( "marksroom_fan_on", 0)
        #self.ifttt_fan_off      = ( "marksroom_fan_off", 0)

        # Current Bedroom Room settings
        # GE (Haier) AEC08LX 8,000BTU 120V
        self.ac_min = 64
        self.ac_max = 86
        self.ac_temp_default = 70  # Default temp if no info from the thermostat
        self.ac_cooling_on_offset = -10  # When cooling drop temp by N degrees
        self.ac_cooling_off_offset = 2  # When NOT cooling raise temp by N degrees
        self.ac_cooling_fan = None

        # Nest specific settings
        self.therm_name = "Master Bedroom Thermostat (Mark's Bedroom)"  # Long Name

        # GPIO specific settings
        self.gpio_cool = 1 << 4  # Cooling stage 1
Exemple #34
0
 def createZones(self):
     """
     100mm are equal to 378 px.
     'Real' width is 680 px
     """
     with open('assets/mapCoords.csv', 'r') as f:
         f.readline()
         for line in f:
             (name, x, y, w, h) = line.split(",")
             x = int(x)
             y = int(y)
             w = int(w)
             h = int(h)
             zone = Zone(self, name, (x, y), (w, h), self.scale)
             zone.zoneActivated.connect(self.parent.log.addEntry)
             self.zones[name] = zone
Exemple #35
0
def main():
    # Load agents
    for agent_properties in json.load(open("agents-100k.json")):
        longitude = agent_properties.pop('longitude')
        latitude = agent_properties.pop('latitude')
        # store agent position in radians
        position = Position(longitude, latitude)

        zone = Zone.find_zone_that_contains(position)
        agent = Agent(position, **agent_properties)
        zone.add_inhabitant(agent)

    agreeableness_graph = AgreeablenessGraph()
    agreeableness_graph.show(Zone.ZONES)

    income_graph = IncomeGraph()
    income_graph.show(Zone.ZONES)
    def __prepareZones(self):
        last = -1
        while 1:
            # getting where is 'include' directive
            pos = self.contents.find('zone ', last+1)
            if pos == -1: return None
            # fix
            if pos > 1:
                char = self.contents[pos-1]
                if char <> '\n' and char <> '\r' and \
                   char <> ' '  and char <> '\t' and \
                   char <> ';':
                       return None
            # marking 'include' position
            last = pos
            
            # creating a Zone instance
            thisZone = Zone()
            try:
                OneZonePart = self.contents[pos:].split('}')[0]
                # Getting Name
                thisZone.setName( self.__getStr( OneZonePart.split('{')[0] ) )
                # Getting Filename
                thisZone.setFile( self.__getStr( OneZonePart.split('file')[1].split(';')[0] ) )
                #Getting type
                if OneZonePart.split('type')[1].split(';')[0].upper().find('SLAVE') <> -1:
                    thisZone.setType('slave')
                else:
                    thisZone.setType('master')
                    
                self.zones.append(thisZone)
            except:
                pass

            # destroying thisZone instance
            thisZone = None
Exemple #37
0
    def to_JSON(self, event_list: list, zone: Zone, comma: bool):
        temp = str(zone.to_JSON()) + ""
        i = 0
        for event in event_list:
            if i == 0:
                temp += '\n\t{"event' + str(i) + '":'
            else:
                temp += '\n\t"event' + str(i) + '":'
            temp += "\n\t\t" + event.to_JSON()
            if i == (len(event_list) - 1):
                temp += "\n\t}"
                if comma:
                    temp += ","
            else:
                temp += ","
            i += 1
        temp += "\n"

        return temp
Exemple #38
0
    def link_zone(self, zone):
        from zone import Zone

        if not isinstance(zone, Zone):
            zone = Zone.get(zone)
        return zone.link_banner(self)
Exemple #39
0
 def __init__(self, cards, zoneType=None):
     """ Initialize the Deck Zone """
     self.cards = cards
     Zone.__init__(self, cards, zoneType=zoneType)
Exemple #40
0
 def __init__(self, character):
     """ Initialize the zone """
     self.character = character
     Zone.__init__(self, character, zoneType=CHARACTER)
Exemple #41
0
 def __init__(self, deck, zoneType=None):
     """ Initialize the Deck Zone """
     self.deck = deck
     Zone.__init__(self, deck, zoneType=zoneType)
Exemple #42
0
class World(DirectObject):
    def __init__(self):
        self.last_mousex = 0
        self.last_mousey = 0

        self.zone = None
        self.zone_reload_name = None

        self.winprops = WindowProperties()

        # simple console output
        self.consoleNode = NodePath(PandaNode("console_root"))
        self.consoleNode.reparentTo(aspect2d)

        self.console_num_lines = 24
        self.console_cur_line = -1
        self.console_lines = []
        for i in range(0, self.console_num_lines):
            self.console_lines.append(
                OnscreenText(
                    text="",
                    style=1,
                    fg=(1, 1, 1, 1),
                    pos=(-1.3, 0.4 - i * 0.05),
                    align=TextNode.ALeft,
                    scale=0.035,
                    parent=self.consoleNode,
                )
            )

        # Configuration
        self.consoleOut("zonewalk v.%s loading configuration" % VERSION)
        self.configurator = Configurator(self)
        cfg = self.configurator.config
        resaveRes = False
        if "xres" in cfg:
            self.xres = int(cfg["xres"])
        else:
            self.xres = 1024
            resaveRes = True

        if "yres" in cfg:
            self.yres = int(cfg["yres"])
        else:
            self.yres = 768
            resaveRes = True

        if resaveRes:
            self.saveDefaultRes()

        self.xres_half = self.xres / 2
        self.yres_half = self.yres / 2
        self.mouse_accum = MouseAccume(lambda: (self.xres_half, self.yres_half))

        self.eyeHeight = 7.0
        self.rSpeed = 80
        self.flyMode = 1

        # application window setup
        base.win.setClearColor(Vec4(0, 0, 0, 1))
        self.winprops.setTitle("zonewalk")
        self.winprops.setSize(self.xres, self.yres)

        base.win.requestProperties(self.winprops)
        base.disableMouse()

        # network test stuff
        self.login_client = None
        if "testnet" in cfg:
            if cfg["testnet"] == "1":
                self.doLogin()

        # Post the instructions
        self.title = addTitle("zonewalk v." + VERSION)
        self.inst0 = addInstructions(0.95, "[FLYMODE][1]")
        self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.")
        self.inst2 = addInstructions(0.9, "Loc:")
        self.inst3 = addInstructions(0.85, "Hdg:")
        self.error_inst = addInstructions(0, "")
        self.kh = []

        self.campos = Point3(155.6, 41.2, 4.93)
        base.camera.setPos(self.campos)

        # Accept the application control keys: currently just esc to exit navgen
        self.accept("escape", self.exitGame)
        self.accept("window-event", self.resizeGame)

        # Create some lighting
        ambient_level = 0.6
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0))
        render.setLight(render.attachNewNode(ambientLight))

        direct_level = 0.8
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0.0, 0.0, -1.0))
        directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1))
        directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1))
        render.setLight(render.attachNewNode(directionalLight))

        # create a point light that will follow our view point (the camera for now)
        # attenuation is set so that this point light has a torch like effect
        self.plight = PointLight("plight")
        self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0))
        self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002))

        self.plnp = base.camera.attachNewNode(self.plight)
        self.plnp.setPos(0, 0, 0)
        render.setLight(self.plnp)
        self.cam_light = 1

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "mouse3": 0,
            "flymode": 1,
        }

        # setup FOG
        self.fog_colour = (0.8, 0.8, 0.8, 1.0)
        self.linfog = Fog("A linear-mode Fog node")
        self.linfog.setColor(self.fog_colour)
        self.linfog.setLinearRange(700, 980)  # onset, opaque distances as params
        # linfog.setLinearFallback(45,160,320)
        base.camera.attachNewNode(self.linfog)
        render.setFog(self.linfog)
        self.fog = 1

        # camera control
        self.campos = Point3(0, 0, 0)
        self.camHeading = 0.0
        self.camPitch = 0.0
        base.camLens.setFov(65.0)
        base.camLens.setFar(1200)

        self.cam_speed = 0  # index into self.camp_speeds
        self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0]

        # Collision Detection for "WALKMODE"
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  The ray will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0.0, 0.0, 0.0)
        self.camGroundRay.setDirection(0, 0, -1)  # straight down
        self.camGroundCol = CollisionNode("camRay")
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())

        # attach the col node to the camCollider dummy node
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        # self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        # self.cTrav.showCollisions(render)

        # Add the spinCameraTask procedure to the task manager.
        # taskMgr.add(self.spinCameraTask, "SpinCameraTask")
        taskMgr.add(self.camTask, "camTask")

        self.toggleControls(1)

        # need to step the task manager once to make our fake console work
        taskMgr.step()

    # CONSOLE ---------------------------------------------------------------------
    def consoleScroll(self):
        for i in range(0, self.console_num_lines - 1):
            self.console_lines[i].setText(self.console_lines[i + 1].getText())

    def consoleOut(self, text):
        print text  # output to stdout/log too

        if self.console_cur_line == self.console_num_lines - 1:
            self.consoleScroll()
        elif self.console_cur_line < self.console_num_lines - 1:
            self.console_cur_line += 1

        self.console_lines[self.console_cur_line].setText(text)

        taskMgr.step()

    def consoleOn(self):
        self.consoleNode.show()

    def consoleOff(self):
        self.consoleNode.hide()

    # User controls -----------------------------------------------------------
    def toggleControls(self, on):
        if on == 1:
            self.accept("escape", self.exitGame)

            self.accept("1", self.setSpeed, ["speed", 0])
            self.accept("2", self.setSpeed, ["speed", 1])
            self.accept("3", self.setSpeed, ["speed", 2])
            self.accept("4", self.setSpeed, ["speed", 3])
            self.accept("5", self.setSpeed, ["speed", 4])

            self.accept("alt-f", self.fogToggle)
            self.accept("t", self.camLightToggle)
            self.accept("k", self.displayKeyHelp)
            self.accept("f", self.toggleFlymode)
            self.accept("l", self.reloadZone)
            self.accept("z", self.saveDefaultZone)
            self.accept("a", self.setKey, ["cam-left", 1])
            self.accept("d", self.setKey, ["cam-right", 1])
            self.accept("w", self.setKey, ["forward", 1])
            self.accept("mouse1", self.setKey, ["forward", 1])
            self.accept("mouse3", self.setKey, ["mouse3", 1])
            self.accept("s", self.setKey, ["backward", 1])

            self.accept("k-up", self.hideKeyHelp)
            self.accept("a-up", self.setKey, ["cam-left", 0])
            self.accept("d-up", self.setKey, ["cam-right", 0])
            self.accept("w-up", self.setKey, ["forward", 0])
            self.accept("mouse1-up", self.setKey, ["forward", 0])
            self.accept("mouse3-up", self.setKey, ["mouse3", 0])
            self.accept("s-up", self.setKey, ["backward", 0])
        else:
            messenger.clear()

    def setSpeed(self, key, value):
        self.cam_speed = value
        self.setFlymodeText()

    def fogToggle(self):
        if self.fog == 1:
            render.clearFog()
            base.camLens.setFar(100000)
            self.fog = 0
        else:
            render.setFog(self.linfog)
            base.camLens.setFar(1200)
            self.fog = 1

    def camLightToggle(self):
        if self.cam_light == 0:
            render.setLight(self.plnp)
            self.cam_light = 1
        else:
            render.clearLight(self.plnp)
            self.cam_light = 0

    def displayKeyHelp(self):
        self.kh = []
        msg = "HOTKEYS:"
        pos = 0.75
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "------------------"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "W: camera fwd, S: camera bck, A: rotate view left, D: rotate view right"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "1-5: set camera movement speed"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "F: toggle Flymode/Walkmode"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "L: load a zone"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "ALT-F: toggle FOG and FAR plane on/off"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = 'T: toggle additional camera "torch" light on/off'
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "Z: set currently loaded zone as new startup default"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )
        msg = "ESC: exit zonewalk"
        pos -= 0.05
        self.kh.append(
            OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04)
        )

    def hideKeyHelp(self):
        for n in self.kh:
            n.removeNode()

    def setFlymodeText(self):
        zname = ""
        if self.zone:
            zname = self.zone.name

        if self.flyMode == 0:
            self.inst0.setText("[WALKMODE][%i] %s" % (self.cam_speed + 1, zname))
        else:
            self.inst0.setText("[FLYMODE][%i] %s " % (self.cam_speed + 1, zname))

    def toggleFlymode(self):
        zname = ""
        if self.zone:
            zname = self.zone.name

        if self.flyMode == 0:
            self.flyMode = 1
        else:
            self.flyMode = 0

        self.setFlymodeText()

    # Define a procedure to move the camera.
    def spinCameraTask(self, task):
        angleDegrees = task.time * 6.0
        angleRadians = angleDegrees * (pi / 180.0)
        base.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3)
        base.camera.setHpr(angleDegrees, 0, 0)
        return task.cont

    def camTask(self, task):
        # query the mouse
        mouse_dx = 0
        mouse_dy = 0

        # if we have a mouse and the right button is depressed
        if base.mouseWatcherNode.hasMouse():
            if self.keyMap["mouse3"] != 0:
                self.mouse_accum.update()
            else:
                self.mouse_accum.reset()

        mouse_dx = self.mouse_accum.dx
        mouse_dy = self.mouse_accum.dy

        self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed + 1) * max(5 * 1000 / self.xres, 3)
        self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed + 1) * max(3 * 1000 / self.yres, 1)

        if self.keyMap["cam-left"] != 0 or mouse_dx < 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading += self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading += self.rSpeed * globalClock.getDt()

            if self.camHeading > 360.0:
                self.camHeading = self.camHeading - 360.0
        elif self.keyMap["cam-right"] != 0 or mouse_dx > 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading -= self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading -= self.rSpeed * globalClock.getDt()

            if self.camHeading < 0.0:
                self.camHeading = self.camHeading + 360.0
        else:
            self.rSpeed = 80

        if mouse_dy > 0:
            self.camPitch += self.rYSpeed * globalClock.getDt()
        elif mouse_dy < 0:
            self.camPitch -= self.rYSpeed * globalClock.getDt()

        # set camera heading and pitch
        base.camera.setHpr(self.camHeading, self.camPitch, 0)

        # viewer position (camera) movement control
        v = render.getRelativeVector(base.camera, Vec3.forward())
        if not self.flyMode:
            v.setZ(0.0)

        move_speed = self.cam_speeds[self.cam_speed]
        if self.keyMap["forward"] == 1:
            self.campos += v * move_speed * globalClock.getDt()
        if self.keyMap["backward"] == 1:
            self.campos -= v * move_speed * globalClock.getDt()

        # actually move the camera
        lastPos = base.camera.getPos()
        base.camera.setPos(self.campos)
        # self.plnp.setPos(self.campos)      # move the point light with the viewer position

        # WALKMODE: simple collision detection
        # we simply check a ray from slightly below the "eye point" straight down
        # for geometry collisions and if there are any we detect the point of collision
        # and adjust the camera's Z accordingly
        if self.flyMode == 0:
            # move the camera to where it would be if it made the move
            # the colliderNode moves with it
            # base.camera.setPos(self.campos)
            # check for collissons
            self.cTrav.traverse(render)
            entries = []
            for i in range(self.camGroundHandler.getNumEntries()):
                entry = self.camGroundHandler.getEntry(i)
                entries.append(entry)
                # print 'collision'
            entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ()))

            if len(entries) > 0:  # and (entries[0].getIntoNode().getName() == "terrain"):
                # print len(entries)
                self.campos.setZ(entries[0].getSurfacePoint(render).getZ() + self.eyeHeight)
            else:
                self.campos = lastPos
                base.camera.setPos(self.campos)

            # if (base.camera.getZ() < self.player.getZ() + 2.0):
            #    base.camera.setZ(self.player.getZ() + 2.0)

        # update loc and hpr display
        pos = base.camera.getPos()
        hpr = base.camera.getHpr()
        self.inst2.setText("Loc: %.2f, %.2f, %.2f" % (pos.getX(), pos.getY(), pos.getZ()))
        self.inst3.setText("Hdg: %.2f, %.2f, %.2f" % (hpr.getX(), hpr.getY(), hpr.getZ()))
        return task.cont

    def exitGame(self):
        sys.exit(0)

    def resizeGame(self, win):
        props = base.win.getProperties()
        self.xres = props.getXSize()
        self.yres = props.getYSize()
        self.xres_half = self.xres / 2
        self.yres_half = self.yres / 2
        self.saveDefaultRes()

    # Records the state of the arrow keys
    # this is used for camera control
    def setKey(self, key, value):
        self.keyMap[key] = value

    # -------------------------------------------------------------------------
    # this is the mythical MAIN LOOP :)
    def update(self):

        if self.zone_reload_name != None:
            self.doReload(self.zone_reload_name)
            self.zone_reload_name = None

        if self.zone != None:
            self.zone.update()

        taskMgr.step()

        if self.login_client != None:
            self.login_client.update()

    # ZONE loading ------------------------------------------------------------

    # general zone loader driver
    # removes existing zone (if any) and load the new one
    def loadZone(self, name, path):
        if path[len(path) - 1] != "/":
            path += "/"

        if self.zone:
            self.zone.rootNode.removeNode()

        self.zone = Zone(self, name, path)
        error = self.zone.load()
        if error == 0:
            self.consoleOff()
            self.setFlymodeText()
            base.setBackgroundColor(self.fog_colour)

    def saveDefaultRes(self):
        cfg = self.configurator.config
        cfg["xres"] = str(self.xres)
        cfg["yres"] = str(self.yres)
        self.configurator.saveConfig()

    # initial world load after bootup
    def load(self):
        cfg = self.configurator.config

        if self.login_client != None:
            return

        zone_name = cfg["default_zone"]
        basepath = cfg["basepath"]
        self.loadZone(zone_name, basepath)

    # config save user interfacce
    def saveDefaultZone(self):
        if self.zone:
            cfg = self.configurator.config
            cfg["default_zone"] = self.zone.name
            self.configurator.saveConfig()

    # zone reload user interface

    # this gets called from our update loop when it detects that zone_reload_name has been set
    # we do this in this convoluted fashion in order to keep the main loop taskMgr updates ticking
    # because otherwise our status console output at various stages during the zone load would not
    # be displayed. Yes, this is hacky.
    def doReload(self, name):
        cfg = self.configurator.config
        basepath = cfg["basepath"]
        self.loadZone(name, basepath)

    # form dialog callback
    # this gets called from the form when the user has entered a something
    # (hopefully a correct zone short name)
    def reloadZoneDialogCB(self, name):
        self.frmDialog.end()
        self.zone_reload_name = name
        self.toggleControls(1)

    # this is called when the user presses "l"
    # it disables normal controls and fires up our query form dialog
    def reloadZone(self):
        base.setBackgroundColor((0, 0, 0))
        self.toggleControls(0)
        self.consoleOn()
        self.frmDialog = FileDialog(
            "Please enter the shortname of the zone you wish to load:",
            "Examples: qrg, blackburrow, freportn, crushbone etc.",
            self.reloadZoneDialogCB,
        )

        self.frmDialog.activate()  # relies on the main update loop to run

    ###############################
    # EXPERIMENTAL
    def doLogin(self):

        self.login_client = UDPClientStream("127.0.0.1", 5998)
Exemple #43
0
 def zones_build( self, build_dir ):
     # Regular zones
     Zone.BUILD_DIR = build_dir
     reg_zone = Zone( self.cur, self.fd, 0, "." )
     reg_zone.walk_domain( 0, "." )
Exemple #44
0
def main():
    '''(NoneType) -> NoneType'''
    WINDOW_W, WINDOW_H = get_window_dim()

    pygame.init()

    fps_clock = time.Clock()
    FPS = get_fps()

    window = display.set_mode((WINDOW_W, WINDOW_H))

    # Set up arg parser to get the zone
    arg_parser = ArgumentParser()
    # Add the zone argument
    arg_parser.add_argument("zone", help="the zone to play, relative to data/zone")
    # Get the arg
    args = arg_parser.parse_args()

    ZONE = args.zone

    zone = Zone()
    zone.load(ZONE) # This loads the player

    sum_tracker = SumTracker(zone.player)
    keys_tracker = KeysTracker(zone.player, sum_tracker) # Put it below sum_tracker

    zone.render(window)
    sum_tracker.render(window)
    keys_tracker.render(window)

    display.flip()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            # Check if player won
            elif zone.player.win:
                # Render text to screen saying player won
                FONT_SIZE = 50
                WHITE = (255, 255, 255)
                BLACK = (0, 0, 0)
                FONT = Font(None, FONT_SIZE)
                X1, Y1 = 40, 100
                X2, Y2 = 40, 150
                FONT_S1 = FONT.render("YOU WIN!", False, WHITE)
                FONT_S2 = FONT.render("Click to exit...", False, WHITE)
                # Black out window
                window.fill(BLACK)
                # Render text
                window.blit(FONT_S1, (X1, Y1))
                window.blit(FONT_S2, (X2, Y2))
                
                display.flip()

                # Wait for a click
                new_event = pygame.event.wait() # Some issue with other events getting in
                                                # way, but it seems to work well enough
                while new_event.type != MOUSEBUTTONDOWN:
                    new_event = pygame.event.wait()

                running = False
            # Check for game over
            elif (zone.player.sum < -128) or (zone.player.sum > 127):
                # Game over
                # Render text to screen saying game is over
                FONT_SIZE = 50
                WHITE = (255, 255, 255)
                BLACK = (0, 0, 0)
                FONT = Font(None, FONT_SIZE)
                X1, Y1 = 40, 100
                X2, Y2 = 40, 150
                X3, Y3 = 40, 250
                # Check for underflow or overflow
                if zone.player.sum < -128:
                    status = "UNDERFLOW"
                else:
                    status = "OVERFLOW"
                FONT_S1 = FONT.render("GAMEOVER!", False, WHITE)
                FONT_S2 = FONT.render("YOU CREATED AN {}!".format(status), False, WHITE)
                FONT_S3 = FONT.render("Click to exit...", False, WHITE)
                # Black out window
                window.fill(BLACK)
                # Render text
                window.blit(FONT_S1, (X1, Y1))
                window.blit(FONT_S2, (X2, Y2))
                window.blit(FONT_S3, (X3, Y3))

                display.flip()

                # Wait for a click
                new_event = pygame.event.wait() # Some issue with other events getting in
                                                # way, but it seems to work well enough
                while new_event.type != MOUSEBUTTONDOWN:
                    new_event = pygame.event.wait()

                running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    zone.move_player("LEFT", window)
                elif event.key == pygame.K_RIGHT:
                    zone.move_player("RIGHT", window)
                elif event.key == pygame.K_UP:
                    zone.move_player("UP", window)
                elif event.key == pygame.K_DOWN:
                    zone.move_player("DOWN", window)
                # Update trackers
                sum_tracker.render(window)
                keys_tracker.render(window)

                display.flip()

        fps_clock.tick(FPS)
    pygame.quit()
Exemple #45
0
    def unlink_zone(self, zone):
        from zone import Zone

        if not isinstance(zone, Zone):
            zone = Zone.get(zone)
        return zone.unlink_campaign(self)
Exemple #46
0
	def zones(self):
		from zone import Zone
		return Zone.get_for_publisher(self)
Exemple #47
0
 def convert_to_JSON(self, event: Event, zone: Zone):
     return "{" + str(zone.to_JSON()) + "[\n\t" + event.to_JSON() + "\n]}"