Пример #1
0
 def test_error_attacker_bomb_time_invalid(self):
     """ Attacker wants to set a bomb but his bomb quota for today is expired"""
     attacker = self.p1a
     attacker.can_set_after = Util.next_day()
     params = self.default_params
     with self.assertRaises(TimeError) as e:
         Bomb.handler(attacker, params)
     self.assertEqual(e.exception.message, "You cannot set bomb before time {}.".\
             format(Util.utc_to_chi(attacker.can_set_after).strftime(\
             "%m-%d %I:%M%p")))
     self.assertEqual(len(self.bomb_queue), 0)
Пример #2
0
 def test_invul_error_time_before_valid_time(self):
     """ MEDIC can only INVUL one person per 24 hour period """
     medic = self.p1c
     medic.can_set_after = Util.next_day()
     medic.put()
     params = self.default_params
     with self.assertRaises(TimeError) as e:
         Invul.handler(medic, params)
     self.assertEqual(e.exception.message, "You cannot set invul before time {}."\
             .format(Util.utc_to_chi(medic.can_set_after).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.invul_queue), 0)
Пример #3
0
 def test_invul_error_time_before_now(self):
     """ MEDIC can only INVUL a time in the future """
     medic = self.p1c
     now = Util.utc_to_chi(datetime.now()) - timedelta(hours=1)
     params = ["p1a", str(now.month), str(now.day),\
             str(now.hour), str(now.minute)]
     with self.assertRaises(TimeError) as e:
         Invul.handler(medic, params)
     self.assertEqual(e.exception.message, "You cannot set {} before time {}."\
             .format(now.strftime("%m-%d %I:%M%p"),\
             Util.utc_to_chi(datetime.now()).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.invul_queue), 0)
Пример #4
0
 def test_error_time_is_before_now(self):
     """ Attacker wants to set a bomb back in time """
     attacker = self.p1a
     now = Util.utc_to_chi(datetime.now()) - timedelta(hours=1)
     params = ["Here", str(now.month), str(now.day),\
             str(now.hour), str(now.minute)]
     with self.assertRaises(TimeError) as e:
         Bomb.handler(attacker, params)
     self.assertEqual(e.exception.message, "You cannot set {} before time {}."\
             .format(now.strftime("%m-%d %I:%M%p"),\
             Util.utc_to_chi(datetime.now()).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.bomb_queue), 0)
Пример #5
0
    def saveExport(self, _outFile):
        writer = PyArchive.FileWriter()
        writer.Open(_outFile, True)

        # 写入所有文件
        writer.Write("audio#1.ogg", self.status.music)
        writer.Write("audio#2.ogg", self.status.accompaniment)
        writer.Write("app.asset",
                     Util.fileToBytes('./template/Karaoke/app.asset'))
        writer.Write("app.lua", Util.fileToBytes('./template/Karaoke/app.lua'))
        writer.Write("config.lua", self.renderConfig())
        writer.Write("preloads.json",
                     Util.stringToBytes(json.dumps(self.status.preloads)))
        writer.Close()
Пример #6
0
    def inner_handler(cls, message):
        """ Return [(number, msg),...]"""
        action, params = CommandHandler.get_command(message.Body)
        attacker = Util.get_attacker(message.From)

        if action == "KILL":
            return Kill.handler(attacker, params)
        elif action[1:] == "REPLY":
            ref = params.pop(0)[:-1]
            return Reply.handler(ref, params, attacker)
        elif action == "BOMB":
            return Bomb.handler(attacker, params)
        elif action == "INVUL":
            return Invul.handler(attacker, params)
        elif action == "DISARM":
            return Disarm.handler(attacker, params)
        elif action == "SNIPE":
            if message.From != WEI_HAN:
                raise CommandError(action)
            sniper = Player.query(Player.codename == params[0]).get()
            if sniper == None:
                raise DbError(params[0])
            return Snipe.handler(sniper, params[1])
        elif action == "?":
            msg = "Guide for SAMSU Assassins:\n"
            msg += "KILL <target codename>\n"
            msg += "BOMB <mm> <dd> <hour> <min> <place>\n"
            msg += "INVUL <target codename> <mm> <dd> <hour> <min>\n"
            msg += "DISARM <target codename>\n"
            msg += "SNIPE - send message and picture to {}\n".format(WEI_HAN)
            msg += "REPLY - [REPLY <number>] Y or [REPLY <number>] N\n"
            msg += "If you receive an UNKNOWN ERROR or don't get a message that you expect, contact Wei Han at 312-731-0539."
            return [(attacker.key.id(), msg)]
        else:
            raise CommandError(action)
Пример #7
0
 def test_good_invul(self):
     """ GOOD test """
     medic = self.p1c
     now = Util.utc_to_chi(datetime.now())
     params = self.default_params
     Invul.handler(medic, params)
     self.assertEqual(len(self.invul_queue),1)
Пример #8
0
    def reply_handler(cls, action, response):
        if response == "Y" or response == "y":
            action.need_validation = False
            action.incorrect_kill = False
            action_key = action.put()

            victim = Player.get_by_id(action.victim)
            victim.disarm = True
            victim.put()

            disarm = Disarm()
            disarm.attacker = action.attacker
            disarm.victim = action.victim
            disarm.starttime = datetime.now()
            disarm.endtime = datetime.now() + timedelta(hours = 1)
            disarm_key = disarm.put()

            task = taskqueue.Task(url="/disarm", params={"id": disarm_key.id()},
                    eta=disarm.endtime)
            task.add(queue_name="disarm")
            q = taskqueue.Queue('disarm').fetch_statistics()
            logging.critical(q)

            return [(action.victim, "You have been DISARM until {}".format(\
                    Util.utc_to_chi(disarm.endtime).strftime("%m-%d %I:%M%p")))]
        else:
            action.need_validation = False
            action.incorrect_kill = False
            action.put()
            return [(action.attacker, "Your DISARM target claims he was not "
                "disarmed by you.")]
Пример #9
0
 def test_good_bomb(self):
     """ Good attacker set good bomb. """
     attacker = self.p1a
     later = Util.utc_to_chi(datetime.now())
     params = self.default_params
     Bomb.handler(attacker, params)
     self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
             queue_names='bomb')), 1)
Пример #10
0
 def renderConfig(self):
     f = open('./template/Karaoke/config.lua', 'r')
     scripts = f.read()
     f.close()
     # 替换变量
     scripts = scripts.replace("{{__lrc__}}", self.status.lyrics)
     # 转换成python bytes
     return Util.stringToBytes(scripts)
Пример #11
0
 def saveExport(self, _outFile):
     self.status.preloads[0]['count'] = len(self.status.photos)
     writer = PyArchive.FileWriter()
     writer.Open(_outFile, True)
     # 写入文件
     idx = 0
     for filename in self.status.binary.keys():
         idx += 1
         writer.Write('img#{0}.jpg'.format(idx),
                      self.status.binary[filename])
     writer.Write("app.asset",
                  Util.fileToBytes('./template/PhotoAlbum/app.asset'))
     writer.Write("app.lua",
                  Util.fileToBytes('./template/PhotoAlbum/app.lua'))
     writer.Write("config.lua", self.renderConfig())
     writer.Write("preloads.json",
                  Util.stringToBytes(json.dumps(self.status.preloads)))
     writer.Close()
Пример #12
0
 def renderConfig(self):
     f = open('./template/Reciting/config.lua', 'r')
     scripts = f.read()
     f.close()
     # 替换变量
     scripts = scripts.replace("{{__title__}}", self.status.title)
     scripts = scripts.replace("{{__author__}}", self.status.author)
     scripts = scripts.replace("{{__reciter__}}", self.status.reciter)
     scripts = scripts.replace("{{__content__}}", self.status.content)
     # 转换成python bytes
     return Util.stringToBytes(scripts)
Пример #13
0
    def saveExport(self, _outFile):
        writer = PyArchive.FileWriter()
        writer.Open(_outFile, True)

        # 判断是否有朗诵音频
        if 0 != len(self.status.audio):
            writer.Write("audio#1.ogg", self.status.audio)
            writer.Write("preloads.json",
                         Util.stringToBytes(json.dumps(self.status.preloads)))
        else:
            writer.Write("preloads.json", Util.stringToBytes(json.dumps([])))

        # 写入所有文件
        writer.Write("app.asset",
                     Util.fileToBytes('./template/Reciting/app.asset'))
        writer.Write("app.lua",
                     Util.fileToBytes('./template/Reciting/app.lua'))
        writer.Write("config.lua", self.renderConfig())

        writer.Close()
Пример #14
0
    def test_reply_disarm_y(self):
        """ Test disarm reply y """
        later = Util.utc_to_chi(self.action.datetime + timedelta(hours=1))

        ret = Disarm.reply_handler(self.action, "y")
        self.assertEqual(1, len(ret))
        self.assertEqual(ret[0][0], "+1")
        self.assertEqual(ret[0][1], "You have been DISARM until {}".format(\
                later.strftime("%m-%d %I:%M%p")))
        self.assertEqual(self.p1a.disarm, True)
        self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
                queue_names='disarm')), 1)
Пример #15
0
 def renderConfig(self):
     lines = ''
     f = open('./template/RingPhotography360/config.lua', 'r')
     scripts = f.read()
     f.close()
     # 替换变量
     scripts = scripts.replace("{{__count__}}",
                               "{0}".format(len(self.status.binary)))
     scripts = scripts.replace("{{__description__}}", self.description)
     scripts = scripts.replace("{{__title__}}", self.title)
     # 转换成python bytes
     return Util.stringToBytes(scripts)
Пример #16
0
    def test_reply_disarm_y(self):
        """ Test disarm reply y """
        later = Util.utc_to_chi(self.action.datetime + timedelta(hours=1))

        ret = Disarm.reply_handler(self.action, "y")
        self.assertEqual(1, len(ret))
        self.assertEqual(ret[0][0], "+1")
        self.assertEqual(ret[0][1], "You have been DISARM until {}".format(\
                later.strftime("%m-%d %I:%M%p")))
        self.assertEqual(self.p1a.disarm, True)
        self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
                queue_names='disarm')), 1)
Пример #17
0
 def setUp(self):
     super(TestBomb, self).setUp()
     test_dt = Util.utc_to_chi(datetime.now()) + timedelta(minutes=1)
     self.default_params = ["Here", str(test_dt.month), str(test_dt.day),\
             str(test_dt.hour), str(test_dt.minute)]
     
     action = Action()
     action.attacker = "+1"
     action.action = "BOMB"
     action.victim = "*"
     action.datetime = datetime.now()
     action.place = "Place"
     action.put()
     self.action = action
Пример #18
0
 def renderConfig(self):
     lines = ''
     idx = 0
     for desc in self.status.photos.values():
         idx += 1
         line = 'description["img#{0}.jpg"]["en_US"] = "{1}"\n'.format(
             idx, desc)
         lines += line
     f = open('./template/PhotoAlbum/config.lua', 'r')
     scripts = f.read()
     f.close()
     # 替换变量
     scripts = scripts.replace("{{__count__}}",
                               "{0}".format(len(self.status.photos)))
     scripts = scripts.replace("{{__description__}}", lines)
     # 转换成python bytes
     return Util.stringToBytes(scripts)
Пример #19
0
    def handler(cls, attacker, victim_codename):
        logging.info("SNIPE start.")

        victim = Util.get_victim(victim_codename)

        logging.info("Attacker {}".format(attacker))
        logging.info("Victim {}".format(victim))

        """ validation """
        outgoing = []
        try:
            Kill.validate_kill(attacker, victim)
            if attacker.role != "SNIPER":
                raise MeError("not SNIPER")
        except (TeamError, MeError, TargetError) as message:
            outgoing.append((WEI_HAN, message.message))
            outgoing.append((attacker.key.id(), message.message))
            return outgoing
        except:
            message = "[ERR] Unknown Error in SNIPE"
            outgoing.append((WEI_HAN, message))
            outgoing.append((attacker.key.id(), message))
            return outgoing

        action = Action()
        action.attacker = attacker.key.id()
        action.action = "SNIPE"
        action.victim = victim.key.id()
        action.datetime = datetime.now()
        action_key = action.put()

        attacker = Player.get_by_id(action.attacker)
        attacker.killed.append(str(action_key.id()))
        attacker.put()

        victim.state = "DEAD"
        victim.killed_by = str(action_key.id())
        victim.put()

        message = "{} has been SNIPED.".format(victim_codename)
        outgoing.append((victim.key.id(), "You have been SNIPED. (Ref {}).".\
                format(action_key.id())))
        outgoing.append(("*", message))
        outgoing += Team.push(Team.get_by_id(victim.team))
        return outgoing
Пример #20
0
    def handler(cls, attacker, params):

        if len(params) == 0:
            raise CommandError("Parameter {}".format(params))

        victim = Util.get_victim(params[0])
        Disarm.validate_disarm(attacker, victim)

        action = Action()
        action.attacker = attacker.key.id()
        action.action = "DISARM"
        action.victim = victim.key.id()
        action.datetime = datetime.now()
        action.need_validation = True
        action_key = action.put()

        return [(action.victim, "{} claimed to have disarm you. "
            "[REPLY {}] Y/N.".format(attacker.realname, action_key.id()))]
Пример #21
0
    def handler(cls, attacker, victim_codename):
        logging.info("SNIPE start.")

        victim = Util.get_victim(victim_codename)

        logging.info("Attacker {}".format(attacker))
        logging.info("Victim {}".format(victim))
        """ validation """
        outgoing = []
        try:
            Kill.validate_kill(attacker, victim)
            if attacker.role != "SNIPER":
                raise MeError("not SNIPER")
        except (TeamError, MeError, TargetError) as message:
            outgoing.append((WEI_HAN, message.message))
            outgoing.append((attacker.key.id(), message.message))
            return outgoing
        except:
            message = "[ERR] Unknown Error in SNIPE"
            outgoing.append((WEI_HAN, message))
            outgoing.append((attacker.key.id(), message))
            return outgoing

        action = Action()
        action.attacker = attacker.key.id()
        action.action = "SNIPE"
        action.victim = victim.key.id()
        action.datetime = datetime.now()
        action_key = action.put()

        attacker = Player.get_by_id(action.attacker)
        attacker.killed.append(str(action_key.id()))
        attacker.put()

        victim.state = "DEAD"
        victim.killed_by = str(action_key.id())
        victim.put()

        message = "{} has been SNIPED.".format(victim_codename)
        outgoing.append((victim.key.id(), "You have been SNIPED. (Ref {}).".\
                format(action_key.id())))
        outgoing.append(("*", message))
        outgoing += Team.push(Team.get_by_id(victim.team))
        return outgoing
Пример #22
0
    def handler(cls, attacker, params):
        logging.info("KILL start")

        victim = Util.get_victim(params[0])

        Kill.validate_kill(attacker, victim)

        action = Action()
        action.attacker = attacker.key.id()
        action.action = "KILL"
        action.victim = victim.key.id()
        action.datetime = datetime.now()
        action.need_validation = True
        action_key = action.put()

        logging.info("KILL finish")

        return [(action.victim, "{} claimed to have killed you. "
            "[REPLY {}] Y/N.".format(attacker.realname, action_key.id()))]
Пример #23
0
    def handler(cls, attacker, params):
        logging.info("KILL start")

        victim = Util.get_victim(params[0])

        Kill.validate_kill(attacker, victim)

        action = Action()
        action.attacker = attacker.key.id()
        action.action = "KILL"
        action.victim = victim.key.id()
        action.datetime = datetime.now()
        action.need_validation = True
        action_key = action.put()

        logging.info("KILL finish")

        return [
            (
                action.victim,
                "{} claimed to have killed you. " "[REPLY {}] Y/N.".format(attacker.realname, action_key.id()),
            )
        ]
Пример #24
0
    def train(self):
        per_batch = 32
        epochs = 100
        eval_per_n_batches = int(self.data.num_train_data_entries() /
                                 per_batch)

        avg_cost, avg_accu = 0, 0
        lowest_val_avg_cost, non_improving_count = 10000.0, 0

        for i in range(epochs * eval_per_n_batches):
            lr = Util.decaying_learning_rate(
                self.min_learning_rate, self.max_learning_rate,
                (self.decay_speed * eval_per_n_batches), i)
            xfeed, yfeed = self.data.next_batch_train(per_batch)
            xfeed = np.reshape(
                xfeed, (xfeed.shape[0], self.n_input_steps, self.n_embedding))
            _, train_cost, train_accuracy = self.sess.run(
                [self.optimizer, self.cross_entropy, self.test_accuracy],
                feed_dict={
                    self.x: xfeed,
                    self.y: yfeed,
                    self.prob_keep_fc1: 0.5,
                    self.learning_rate: lr
                })
            avg_cost += train_cost
            avg_accu += train_accuracy

            if i % eval_per_n_batches == eval_per_n_batches - 1:
                xfeed, yfeed = self.data.validate_data_all()
                xfeed = np.reshape(
                    xfeed,
                    (xfeed.shape[0], self.n_input_steps, self.n_embedding))
                va, val_avg_cost = self.sess.run(
                    [self.test_accuracy, self.cross_entropy],
                    feed_dict={
                        self.x: xfeed,
                        self.y: yfeed,
                        self.prob_keep_fc1: 1.0
                    })
                self.__write_summary(
                    {
                        'train_accuracy': avg_accu / eval_per_n_batches,
                        'validate_accuracy': va,
                        'train_cost': avg_cost / eval_per_n_batches,
                        'validate_cost': val_avg_cost,
                        'learning_rate': lr
                    }, int(i / float(eval_per_n_batches)))
                if val_avg_cost < lowest_val_avg_cost:
                    lowest_val_avg_cost = val_avg_cost
                    non_improving_count = 0
                    self.saver.save(
                        self.sess,
                        os.path.join(
                            dir_path,
                            '../model_checkpoint/lstm_early_stopping_without_conc'
                        ))
                else:
                    non_improving_count += 1
                    print('No improvement for past %d epochs' %
                          non_improving_count)
                    if non_improving_count == 5:
                        break
                avg_cost = 0
                avg_accu = 0
Пример #25
0
 def setUp(self):
     super(TestInvul, self).setUp()
     test_dt = Util.utc_to_chi(datetime.now()) + timedelta(minutes=1)
     self.default_params = ["p1a", str(test_dt.month), str(test_dt.day),\
             str(test_dt.hour), str(test_dt.minute)]
Пример #26
0
def bomb_worker():
    ''' Get bomb id '''
    req_key = request.form.get('id', "")
    bomb = Bomb.get_by_id(int(req_key))

    ''' ERROR: no bomb found by id '''
    if not bomb:
        logging.error("BOMB Worker: No bomb found by key {}".format(req_key))
        raise Exception()

    ''' Bomb deprecated no action '''
    if bomb.deprecated:
        logging.info("BOMB Worker: Bomb with key {} deprecated. No explosion".format(req_key))
        return "BOMB Worker: Deprecated Bomb"

    ''' Trigger bomb '''
    logging.info("BOMB: triggered at {} UTC {} Chicago".format(
        datetime.now(),
        Util.utc_to_chi(datetime.now().replace(tzinfo=pytz.utc))))
    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    attacker = Player.get_by_id(bomb.attacker)
    attacker.can_set_after = Util.next_day()
    attacker.put()

    bomb.trigger = True
    bomb_key = bomb.put()

    action = Action()
    action.attacker = bomb.attacker
    action.action = "BOMB"
    action.victim = "*"
    action.datetime = datetime.now()
    action.place = bomb.place
    action_key = action.put()


    response_num_list = [key.id() for key in Player.query(ndb.AND(Player.state=="ALIVE",\
            Player.invul==False) ).fetch(keys_only=True)]
    response = "{} has been bombed at {}. If you were there, [REPLY {}] Y.".format(
        action.place,
        Util.utc_to_chi(action.datetime).strftime("%m-%d %I:%M%p"),
        action_key.id())

    for response_number in response_num_list:
        logging.info("Making message {} for {} with num_list {}".format(
            response, response_number, response_num_list))

        '''Make message'''
        outgoing_message = Message(From=SERVER_NUMBER,
                                   To=response_number,
                                   Body=response)
        outgoing_message.put()

        '''Send message'''
        client.messages.create(
            to=response_number,
            from_=SERVER_NUMBER,
            body=response)

    return "Bomb triggered at {}".format(bomb.place)
Пример #27
0
    def handler(cls, attacker, params):
        '''Validation'''
        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "DEMO":
            raise MeError("not DEMO")

        if datetime.now() < attacker.can_set_after:
            raise TimeError("bomb", Util.utc_to_chi(attacker.can_set_after))

        if attacker.disarm:
            raise MeError("DISARM")

        ''' Parse place and time '''
        if len(params) < 5:
            raise CommandError("BOMB - {}".format(" ".join(params)))
        month = params.pop(0)
        day = params.pop(0)
        minute = params.pop(0)
        second = params.pop(0)
        place = " ".join(params)

        central = pytz.timezone("US/Central")
        chi_dt = datetime(2016,
                        int(month),
                        int(day),
                        int(minute),
                        int(second),
                        tzinfo=central)
        utc_dt = Util.chi_to_utc(chi_dt)
        logging.debug("CHI time: {}".format(chi_dt))
        logging.debug("UTC time: {}".format(utc_dt))

        if utc_dt < datetime.now():
            cur_time = Util.utc_to_chi(datetime.now())
            logging.error("BOMB: trying to set time {} before now {} (UTC)".format(utc_dt.isoformat(' '), datetime.now().isoformat(' ')))
            raise TimeError(chi_dt, cur_time)

        '''Make new bomb'''
        bomb = Bomb()
        bomb.attacker = attacker.key.id()
        bomb.place = place
        bomb.time = utc_dt
        bomb.trigger = False
        bomb_key = bomb.put()

        ''' Invalidate old bomb '''
        try:
            old_bomb = Bomb.get_by_id(attacker.item)
            logging.info("BOMB: invalidating old bomb with id {}".format(attacker.item))
            old_bomb.deprecated = True
            old_bomb.put()
        except:
            logging.info("BOMB: unable to invalidate old bomb")

        ''' Setting new bomb '''
        attacker.item = bomb_key.id()
        attacker.put()

        task = taskqueue.Task(url="/bomb", params={"id": bomb_key.id()}, eta=utc_dt)
        task.add(queue_name="bomb")

        logging.info("BOMB: set for {} at {}".format(utc_dt, place))

        return [(bomb.attacker, "Your bomb in {} will explode at {}".format(
            bomb.place, chi_dt.strftime("%m-%d %I:%M%p")))]
Пример #28
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()
        self.testbed.init_taskqueue_stub(root_path=".")
        self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
        # Setup fixture
        today = Util.next_day() - timedelta(days=1)

        # Make Team 1 and populate with player 1a, 1b, 1c. 
        # p1a is ALIVE and DEMO
        # p1b is ALIVE, DISARM, and SNIPER
        # p1c is ALIVE, MEDIC
        self.team1 = Team(id = "Team1", to_kill="Team2", target_of="Team3")
        self.p1a = Player(id="+1", realname="player1a", codename="p1a",\
                team="Team1", state="ALIVE", role="DEMO", can_set_after=today)
        self.team1.demo = "+1"
        self.p1a.put()
        self.p1b = Player(id="+2", realname="player1b", codename="p1b",\
                team="Team1", state="ALIVE", disarm=True, role="SNIPER",\
                can_set_after=today)
        self.team1.sniper="+2"
        self.p1b.put()
        self.p1c = Player(id="+3", realname="player1c", codename="p1c",\
                team="Team1", state="ALIVE", role="MEDIC", can_set_after=today)
        self.team1.medic="+3"
        self.p1c.put()
        self.team1.put()

        # Make Team 2 and populate with player 2a, 2b, 2c.
        # p2a is ALIVE
        # p2b is DEAD
        # p2c is INVUL
        self.team2 = Team(id="Team2", to_kill="Team3", target_of="Team1")
        self.p2a = Player(id="+4", realname="player2a", codename="p2a",\
                team="Team2", state="ALIVE", role="DEMO", can_set_after=today)
        self.team2.demo = "+4"
        self.p2a.put()
        self.p2b = Player(id="+5", realname="player2b", codename="p2b",\
                team="Team2", state="DEAD", role="SNIPER", can_set_after=today)
        self.team2.sniper="+5"
        self.p2b.put()
        self.p2c = Player(id="+6", realname="player2c", codename="p2c",\
                team="Team2", state="ALIVE", invul=True, role="MEDIC",\
                can_set_after=today)
        self.team2.medic="+6"
        self.p2c.put()
        self.team2.put()
        
        # Make Team 3 and populate with player 3a, 3b, 3c.
        self.team3 = Team(id="Team3", to_kill="Team1", target_of="Team2")
        self.p3a = Player(id="+7", realname="player3a", codename="p3a",\
                team="Team3", state="ALIVE", role="DEMO", can_set_after=today)
        self.team3.demo = "+7"
        self.p3a.put()
        self.p3b = Player(id="+8", realname="player3b", codename="p3b",\
                team="Team3", state="ALIVE", role="SPY", can_set_after=today)
        self.team3.sniper="+8"
        self.p3b.put()
        self.p3c = Player(id="+9", realname="player3c", codename="p3c",\
                team="Team3", state="ALIVE", role="MEDIC", can_set_after=today)
        self.team3.medic="+9"
        self.p3c.put()
        self.team3.put()
Пример #29
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()
        self.testbed.init_taskqueue_stub(root_path=".")
        self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
        # Setup fixture
        today = Util.next_day() - timedelta(days=1)

        # Make Team 1 and populate with player 1a, 1b, 1c.
        # p1a is ALIVE and DEMO
        # p1b is ALIVE, DISARM, and SNIPER
        # p1c is ALIVE, MEDIC
        self.team1 = Team(id="Team1", to_kill="Team2", target_of="Team3")
        self.p1a = Player(
            id="+1", realname="player1a", codename="p1a", team="Team1", state="ALIVE", role="DEMO", can_set_after=today
        )
        self.team1.demo = "+1"
        self.p1a.put()
        self.p1b = Player(
            id="+2",
            realname="player1b",
            codename="p1b",
            team="Team1",
            state="ALIVE",
            disarm=True,
            role="SNIPER",
            can_set_after=today,
        )
        self.team1.sniper = "+2"
        self.p1b.put()
        self.p1c = Player(
            id="+3", realname="player1c", codename="p1c", team="Team1", state="ALIVE", role="MEDIC", can_set_after=today
        )
        self.team1.medic = "+3"
        self.p1c.put()
        self.team1.put()

        # Make Team 2 and populate with player 2a, 2b, 2c.
        # p2a is ALIVE
        # p2b is DEAD
        # p2c is INVUL
        self.team2 = Team(id="Team2", to_kill="Team3", target_of="Team1")
        self.p2a = Player(
            id="+4", realname="player2a", codename="p2a", team="Team2", state="ALIVE", role="DEMO", can_set_after=today
        )
        self.team2.demo = "+4"
        self.p2a.put()
        self.p2b = Player(
            id="+5", realname="player2b", codename="p2b", team="Team2", state="DEAD", role="SNIPER", can_set_after=today
        )
        self.team2.sniper = "+5"
        self.p2b.put()
        self.p2c = Player(
            id="+6",
            realname="player2c",
            codename="p2c",
            team="Team2",
            state="ALIVE",
            invul=True,
            role="MEDIC",
            can_set_after=today,
        )
        self.team2.medic = "+6"
        self.p2c.put()
        self.team2.put()

        # Make Team 3 and populate with player 3a, 3b, 3c.
        self.team3 = Team(id="Team3", to_kill="Team1", target_of="Team2")
        self.p3a = Player(
            id="+7", realname="player3a", codename="p3a", team="Team3", state="ALIVE", role="DEMO", can_set_after=today
        )
        self.team3.demo = "+7"
        self.p3a.put()
        self.p3b = Player(
            id="+8", realname="player3b", codename="p3b", team="Team3", state="ALIVE", role="SPY", can_set_after=today
        )
        self.team3.sniper = "+8"
        self.p3b.put()
        self.p3c = Player(
            id="+9", realname="player3c", codename="p3c", team="Team3", state="ALIVE", role="MEDIC", can_set_after=today
        )
        self.team3.medic = "+9"
        self.p3c.put()
        self.team3.put()
Пример #30
0
    def handler(cls, attacker, params):
        """ Validation """
        if len(params) != 5:
            raise CommandError("INVUL - {}".format(params))

        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "MEDIC":
            raise MeError("not MEDIC")

        target_codename = params.pop(0)
        target = Util.get_victim(target_codename)

        if target.team != attacker.team:
            raise TeamError

        if target.state == "DEAD":
            raise TargetError("DEAD")

        chi_start_time = datetime(year=2016, month=int(params[0]),\
                day=int(params[1]), hour=int(params[2]),\
                minute=int(params[3]))
        utc_start_time = Util.chi_to_utc(chi_start_time)
        utc_end_time = utc_start_time + timedelta(hours=8)

        if utc_start_time < datetime.now():
            raise TimeError(chi_start_time, Util.utc_to_chi(datetime.now()))

        if datetime.now() < attacker.can_set_after:
            raise TimeError("invul", Util.utc_to_chi(attacker.can_set_after))

        """ Make new Invul """
        invul = Invul()
        invul.medic = attacker.key.id()
        invul.target = target.key.id()
        invul.start_time = utc_start_time
        invul.end_time = utc_end_time

        """ Invalidate old invul """
        try:
            old_invul = Invul.get_by_id(attacker.item)
            logging.info("INVUL: invalidating old invul with id {}".\
                    format(attacker.item))
            if old_invul.in_effect or old_invul.deprecated:
                raise TimeError("invul" "midnight")
            old_invul.deprecated = True
            old_invul.put()
        except:
            logging.info("INVUL: unable to invalidate old invul")

        invul_key = invul.put()
        attacker.item = invul_key.id()
        attacker.put()

        task = taskqueue.Task(url="/invul", params={"id": invul_key.id()},\
                eta = utc_start_time)
        task.add(queue_name="invul")

        return [(invul.medic, "Invul will been set for {} from {} to {}.".\
                format(target_codename,\
                chi_start_time.strftime("%m-%d %I:%M%p"),
                Util.utc_to_chi(utc_end_time).strftime("%m-%d %I:%M%p")))]
Пример #31
0
def invul_worker():
    ''' Get invul id'''
    req_key = request.form.get("id", "")
    inv = Invul.get_by_id(int(req_key))

    ''' No Inv found '''
    if not inv:
        logging.error("INV worker: no INV found")
        raise Exception()

    '''Inv deprecated'''
    if inv.deprecated:
        logging.info("INV Worker: Inv deprecated. No action.")
        return "INVUL Worker: Deprecated"

    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    '''Target dead. Report back to medic'''
    logging.info(inv)
    target_num = inv.target
    logging.info(target_num)
    target = Player.get_by_id(target_num)
    medic = Player.get_by_id(inv.medic)
    logging.info(medic)
    if not target:
        logging.error("INV worker: cannot find target {}".format(target_num))
        return
    if target.state == "DEAD":
        logging.error("INV worker: Target {} has died. Cannot grant INVUL".format(target.codename))
        response = "Your INVUL target has died. Cannot grant dead people INVUL."
        msg = Message(From=SERVER_NUMBER,
                      To=inv.medic,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.medic,
            from_=SERVER_NUMBER,
            body=response)
        return "INVUL Worker"

    '''Target alive. If INVUL not yet in effect, trigger'''
    if not inv.in_effect:
        logging.info("INVUL worker: Triggering 8 hour INVUL for target {} at {}".format(target.codename, datetime.now()))
        inv.in_effect = True
        inv_key = inv.put()
        task = taskqueue.Task(url="/invul", params={"id": inv_key.id()}, eta=inv.end_time)
        task.add(queue_name="invul")

        logging.info("Task queue okay")
        logging.info(target)
        target.invul = True
        target.put()

        logging.info("target set okay")
        logging.info(medic)
        medic.can_set_after = Util.next_day()
        medic.put()

        logging.info("medic set okay")
        response  = "You have been granted INVUL for 8 hour from {} to {}".\
                format(Util.utc_to_chi(inv.start_time).strftime("%m-%d %I:%M%p"),\
                Util.utc_to_chi(inv.end_time).strftime("%m-%d %I:%M%p"))
        msg = Message(From=SERVER_NUMBER,
                      To=inv.target,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.target,
            from_=SERVER_NUMBER,
            body=response)
        logging.info("message set okay")
        return "INVUL Worker"
    else:
        logging.info("INVUL worker: END 8 hour INVUL for target {} at {}".format(target.codename, datetime.now()))
        inv.deprecated = True
        inv.put()
        target.invul = False
        target.put()

        response = "Your INVUL period has ended. You are no longer INVUL."
        msg = Message(From=SERVER_NUMBER,
                      To=inv.target,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.target,
            from_=SERVER_NUMBER,
            body=response)
        return "INVUL Worker"
Пример #32
0
    def handler(cls, attacker, params):
        '''Validation'''
        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "DEMO":
            raise MeError("not DEMO")

        if datetime.now() < attacker.can_set_after:
            raise TimeError("bomb", Util.utc_to_chi(attacker.can_set_after))

        if attacker.disarm:
            raise MeError("DISARM")
        ''' Parse place and time '''
        if len(params) < 5:
            raise CommandError("BOMB - {}".format(" ".join(params)))
        month = params.pop(0)
        day = params.pop(0)
        minute = params.pop(0)
        second = params.pop(0)
        place = " ".join(params)

        central = pytz.timezone("US/Central")
        chi_dt = datetime(2016,
                          int(month),
                          int(day),
                          int(minute),
                          int(second),
                          tzinfo=central)
        utc_dt = Util.chi_to_utc(chi_dt)
        logging.debug("CHI time: {}".format(chi_dt))
        logging.debug("UTC time: {}".format(utc_dt))

        if utc_dt < datetime.now():
            cur_time = Util.utc_to_chi(datetime.now())
            logging.error(
                "BOMB: trying to set time {} before now {} (UTC)".format(
                    utc_dt.isoformat(' '),
                    datetime.now().isoformat(' ')))
            raise TimeError(chi_dt, cur_time)
        '''Make new bomb'''
        bomb = Bomb()
        bomb.attacker = attacker.key.id()
        bomb.place = place
        bomb.time = utc_dt
        bomb.trigger = False
        bomb_key = bomb.put()
        ''' Invalidate old bomb '''
        try:
            old_bomb = Bomb.get_by_id(attacker.item)
            logging.info("BOMB: invalidating old bomb with id {}".format(
                attacker.item))
            old_bomb.deprecated = True
            old_bomb.put()
        except:
            logging.info("BOMB: unable to invalidate old bomb")
        ''' Setting new bomb '''
        attacker.item = bomb_key.id()
        attacker.put()

        task = taskqueue.Task(url="/bomb",
                              params={"id": bomb_key.id()},
                              eta=utc_dt)
        task.add(queue_name="bomb")

        logging.info("BOMB: set for {} at {}".format(utc_dt, place))

        return [(bomb.attacker, "Your bomb in {} will explode at {}".format(
            bomb.place, chi_dt.strftime("%m-%d %I:%M%p")))]