def tropo_remote_sms(recipient, msg):
    xprint("Sending SMS to Tropo...")
    recipient = clean_msg_for_url(recipient.lstrip('0'))
    msg = clean_msg_for_url(msg)
    tropo_request = d.tropo_request_polly_sante.replace(
        d.tropo_recipient, recipient).replace(d.tropo_message, msg)
    spin_register_process(str(tropo_request))
示例#2
0
 def __call__(self, msg):
     if self.target == LogTargets.SILENT:
         return
     elif self.target == LogTargets.PRINT:
         xprint(msg)
     elif self.target == LogTargets.FILE:
         raise NotImplemented
示例#3
0
    def loop(self, player_berserk=False):
        count_hero_turns = 0
        while True:
            active_unit = self.turns_manager.get_next()
            target_cell = None
            if self.fractions[active_unit] is Fractions.PLAYER:
                count_hero_turns += 1
                if player_berserk:
                    target_cell=self.brute_ai.decide_step(active_unit, target_fraction=Fractions.ENEMY)
                else:
                    orders = input("Tell me where to go!")
                    x, y = [int(coord) for coord in orders.split()]
                    xprint(x,y)
                    target_cell = Cell(x, y)

            elif self.fractions[active_unit] is Fractions.ENEMY:
                target_cell = self.brute_ai.decide_step(active_unit)
            elif self.fractions[active_unit] is Fractions.NEUTRALS:
                target_cell = self.random_ai.decide_step(active_unit)

            self.order_move(active_unit, target_cell)
            game_over = self.game_over()
            if game_over:
                xprint(game_over)
                return count_hero_turns
示例#4
0
    def post(self):
        expected = ['pb1', 'pb2', 'pb3', 'mg', 'he']
        data = {}
        del qlog.buf[:]
        locs = {}

        for item in expected:
            i = request.json.get(item)
            if i:
                x, y = i.split(',')
                locs[item] = Cell(int(x), int(y))

        if len(locs.keys()) != len(expected):
            error = {"code": "MISSING_SOMETHING"}
            return jsonify({'error': error}), 400

        pirate_band = [Unit(pirate_basetype) for _ in range(3)]
        locations = [locs[item] for item in ['pb1', 'pb2', 'pb3']]
        unit_locations = {pirate_band[i]: locations[i] for i in range(3)}
        unit_locations[Unit(mud_golem_basetype)] = locs['mg']
        dun = Dungeon(unit_locations, 8, 8, hero_entrance=locs['he'])
        test_game = DreamGame.start_dungeon(dun, Unit(demohero_basetype))
        all_units = test_game.print_all_units()
        xprint(all_units)
        hero_turns = test_game.loop(player_berserk=True)
        xprint("hero has made {} turns.".format(hero_turns))
        message = json.dumps({'log': qlog.buf})
        key = genkey(len(message))
        ciphertext = xor_strings(bytes(message, "ascii"), key)
        byt1 = base64.standard_b64encode(ciphertext)
        byt2 = base64.standard_b64encode(key)
        data['b1'] = byt1.decode('ascii')
        data['b2'] = byt2.decode('ascii')
        output = json.dumps(data)
        return output, 200
def retry_backup_logging_queue():
    if os.path.isfile(d.log_dir + d.remote_logging_backup_queue):
        failed_logs = [
            x.strip() for x in open(d.log_dir +
                                    d.remote_logging_backup_queue).readlines()
        ]
        if len(failed_logs) > d.backup_logging_requests_batch_retry_size:
            open(d.log_dir + d.remote_logging_backup_queue, 'w')
            while failed_logs:
                message = failed_logs.pop(0)
                xprint(">>>> Retrying request: " + message)
                send_request(message)
示例#6
0
def demo():
    data = {}
    del qlog.buf[:]
    test_game = demo_game()
    all_units = test_game.print_all_units()
    xprint(all_units)
    hero_turns = test_game.loop(player_berserk=True)
    xprint("hero has made {} turns.".format(hero_turns))
    message = json.dumps({'log': qlog.buf})
    key = genkey(len(message))
    byt1 = base64.standard_b64encode(xor_strings(bytes(message, "ascii"), key))
    byt2 = base64.standard_b64encode(key)
    data['b1'] = byt1.decode('ascii')
    data['b2'] = byt2.decode('ascii')
    output = json.dumps(data)
    return output, 200
示例#7
0
 def decorated_function(*args, **kwargs):
     if len(args) == 4:
         e, s, t, w = args
     elif len(args) == 3:
         s, t, w = args
     elif len(args) == 2:
         s, t = args
         w = 'none'
     else:
         return
     source = {'name': s.type_name, 'location': get_location(s)}
     weapon = w.name
     target = {'name': t.type_name, 'location': get_location(t)}
     battle = json.dumps({'a': source, 'd': target, 'w': weapon})
     output = "[WAR_GPS] {} [/WAR_GPS]".format(battle)
     xprint(output)
     return f(*args, **kwargs)
示例#8
0
    @classmethod
    @lru_cache()
    def total_occurances(cls):
        result = 0
        for m in MasteriesEnum:
            result += cls.occurances(m)

        return result

    @classmethod
    @lru_cache(maxsize=2048)
    def coupling(cls, m1, m2):
        coupling = 0
        for group in cls.all:
            if m1 in group and m2 in group:
                coupling += 1

        return coupling * cls.coupling_coef / (1 + cls.occurances(m1) +
                                               cls.occurances(m2))


if __name__ == "__main__":
    for m in MasteriesEnum:
        xprint(m, MasteriesGroups.occurances(m))
    xprint(MasteriesGroups.total_occurances())

    for m1 in MasteriesEnum:
        for m2 in MasteriesEnum:
            xprint(m1, m2, MasteriesGroups.coupling(m1, m2))
示例#9
0
def demo_dream():
    game = demo_game()
    xprint(game)
    game.print_all_units()
    hero_turns = game.loop(player_berserk=True)
    xprint("hero has made {} turns.".format(hero_turns))
def send_request(http_request):
    #xprint("HTTP Request Generated: " + http_request)
    try:
        wp = urllib2.urlopen(str(http_request), timeout=d.web_request_timeout)
        wp = wp.read().decode('utf-8').lower()
        #xprint("HTTP Response:\n\n"+wp+"\n")
        return d.REQUEST_SUCCESS.lower() in wp

    except http.client.BadStatusLine as e:
        xprint("An Exception occurred!\n" + str(e))
        xprint(traceback.format_exc())
        xprint("Moving on... Tired of getting SMSs about this... ")
        backup_failed_logging_request(http_request)
        return False

    except socket.timeout:
        xprint("Socket timeout! Current timeout: " +
               str(socket.getdefaulttimeout()))
        backup_failed_logging_request(http_request)
        return False

    except urllib2.URLError as e:
        xprint("URL Error... Timeout?\n" + str(e))
        xprint(traceback.format_exc())
        backup_failed_logging_request(http_request)
        return False

    except urllib2.UnknownHandler as e:
        xprint("Unknown URL type!\n" + str(e))
        xprint(traceback.format_exc())
        xprint("Here it is: " + http_request)
        backup_failed_logging_request(http_request)
        return False

    except ValueError as e:
        xprint("Unknown URL type!\n" + str(e))
        xprint(traceback.format_exc())
        xprint("Here it is: " + http_request)
        backup_failed_logging_request(http_request)
        return False

    except Exception as e:
        xprint("An Exception occurred!\n" + str(e))
        xprint(traceback.format_exc())
        if str(e) != '' and http_request.startswith("http://"):  # hack!!
            tropo_remote_sms(d.sms_alert_number, d.sms_alert_message + str(e))
        xprint("Moving on...")
        backup_failed_logging_request(http_request)
        return False
示例#11
0
from utils.named_enums import NameEnum, auto
from common import xprint


class DamageTypes(NameEnum):
    SLASH = auto()
    CRUSH = auto()
    PIERCE = auto()

    FIRE = auto()
    FROST = auto()
    LIGHTNING = auto()
    ACID = auto()

    # design: succeptable entities have strong vulnerability. damage of below types comes in small amounts.
    SONIC = auto()


class DamageTypeGroups:
    physical = {DamageTypes.SLASH, DamageTypes.CRUSH, DamageTypes.PIERCE}
    elemental = {
        DamageTypes.FIRE, DamageTypes.FROST, DamageTypes.LIGHTNING,
        DamageTypes.ACID
    }
    exotic = {DamageTypes.SONIC}


if __name__ == "__main__":
    xprint(list(DamageTypes))
示例#12
0
            self.exp_spent[m] += indirect_costs[m]


if __name__ == "__main__":
    # for i in range(512):
    #     print(i, Masteries.increment_cost(i))
    #
    # for m in MasteriesEnum:
    #     print(m, Masteries.requirements(m,100))

    masteries = Masteries()
    # masteries.exp_spent[MasteriesEnum.AXE] = 5000
    # masteries.exp_spent[MasteriesEnum.SWORD] = 15000
    # masteries.exp_spent[MasteriesEnum.CLUB] = 70

    xprint(masteries.exp_spent)
    xprint(masteries.values)

    while masteries.values[MasteriesEnum.CLUB] < 10:
        masteries.level_up(MasteriesEnum.CLUB)
    xprint(masteries.level_up(MasteriesEnum.CLUB))
    xprint(masteries.exp_spent)
    xprint(masteries.values)
    while masteries.values[MasteriesEnum.AXE] < 30:
        masteries.level_up(MasteriesEnum.AXE)
    xprint(masteries.level_up(MasteriesEnum.AXE))
    xprint(masteries.exp_spent)
    xprint(masteries.values)
    while masteries.values[MasteriesEnum.SWORD] < 50:
        masteries.level_up(MasteriesEnum.SWORD)
    xprint(masteries.level_up(MasteriesEnum.SWORD))
            adv = 1 / (
                1 +
                (precision - evasion) / ChanceCalculator.advantage_to_double)

        if base_prob >= 0.5:
            new_chance = base_prob**adv  # Note: as base_prob is below one, powers below one increase the

        else:
            chance_to_avoid = 1 - base_prob
            adv = 1 / adv
            new_chance_to_avoid = chance_to_avoid**adv
            new_chance = 1 - new_chance_to_avoid

        assert 0 <= new_chance <= 1
        return new_chance


if __name__ == "__main__":

    for base_chance in [0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99]:
        for attack, defense in [(0, 25), (25, 0), (75, 0), (0, 75), (225, 0),
                                (0, 225)]:
            if defense > attack:
                adv = 1 + (defense -
                           attack) / ChanceCalculator.advantage_to_double
            else:
                adv = 1 / (
                    1 +
                    (attack - defense) / ChanceCalculator.advantage_to_double)
            xprint(base_chance, attack, defense, adv,
                   ChanceCalculator.chance(base_chance, attack, defense))
示例#14
0
 def print_all_units(self):
     for unit, xy in self.battlefield.unit_locations.items():
         x, y = xy
         xprint("There is a {} at ({},{})".format(unit, x, y))