예제 #1
0
class IterateGameManager(GameManager):
    def __init__(self, config):
        self.set_up_boards()

        if config == []:
            enemy_config = self.player
        else:
            enemy_config = config

        self.attacker = Attack(enemy_config, HuntType.LINES, self)
        self.do_player_attack()

    def do_player_attack(self):
        self.attacker.begin_attacking()

    def after_attack_event(self):
        pass

    def attack_from_below(self, attack):
        """
        called from the attack class, should return the result
        """

        i, j = attack[0]

        return self.attacker.enemy_config[i][j] == constants.OCCUPIED
예제 #2
0
    def test_CharacterGainsTenExperienceOnSuccessful(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        roll = testCharacter2.armor + 1
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(10, testCharacter1.experiencePoints)
예제 #3
0
    def test_ifRollIs20CriticalHitDoubleDamage(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        roll = 20
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(3, testCharacter2.hitPoints)
예제 #4
0
    def test_MinDmgAlwaysOne(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter1.strength = 1
        roll = 20
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()
        self.assertEqual(4, testCharacter2.hitPoints)
예제 #5
0
    def test_tripleDmgOnCritHit(self):
        testCharacter1 = Rogue()
        testCharacter2 = Character()
        roll = Roll(testCharacter1, testCharacter2, 20)
        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(2, testCharacter2.hitPoints)
예제 #6
0
    def test_ifTargetCharacterHitTakesOneDamage(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        roll = testCharacter2.armor
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(4, testCharacter2.hitPoints)
예제 #7
0
    def test_attack_pubkey_deception_jwk(self):
        rsa256_token_header = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
        rsa256_token_payload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"
        rsa256_token_signature = "ZR8EJ-ssd7b3Z9ZrCODkK_tJvOVXNZbcUn_FQAbLlKjPdEkNNCP_i5h84QfRXA8cWu1Z83UOb25Oogw0GIE9k-Q4AJO-BwEC2muHKRdzgHGrO6_2abeFJxAZapSf4ww39UlGzYX22b2kRYECLmsVaa0NV1KyQIf147h460wDGDr1wd2OCvUZXYULA_vzzRo3HHX440XOx_CnBvrR7shqnIjOLycEG61Ganq6oJsujVXHTQUtKdNB1Amu9NEQRRQzYWSTLuUMwV9mJnCuyr9bWp5srd3VPOC1bMXU2UgJiauw8eYu_w2_bbgZOn0jwajiygkfuJXNJGi8k_09sJmJ0w"
        rsa_token_ser = ".".join([
            rsa256_token_header, rsa256_token_payload, rsa256_token_signature
        ])
        rsa_token = TestJWT.deserialize(rsa_token_ser)
        self.assertEqual("RS256", rsa_token.get_algorithm())
        self.assertEqual("JWT", rsa_token.header['typ'])
        self.assertEqual(2, len(rsa_token.header))
        self.assertEqual("1234567890", rsa_token.payload['sub'])
        self.assertEqual("John Doe", rsa_token.payload['name'])
        self.assertEqual(1516239022, rsa_token.payload['iat'])
        self.assertEqual(3, len(rsa_token.payload))
        pk: RSAPrivateKey = load_pem_private_key(
            utils.read_pem_file("./keys/pk1.pem"), None, default_backend())
        pubkey: RSAPublicKey = pk.public_key()
        self.assertTrue(
            rsa_token.verify_signature(
                pubkey, utils.base64url_decode(rsa256_token_signature)))

        rsa_token_jwk = TestJWT.deserialize(rsa_token_ser)
        kid = "my_own_key"
        attack = Attack(rsa_token_ser)
        attack.attack_pubkey_deception_jwk(pk, kid)
        payloads = attack.payloads
        rsa_token_jwk = TestJWT.deserialize(
            payloads['attack_pubkey_deception_jwk'])
        self.assertEqual("RS256", rsa_token_jwk.get_algorithm())
        self.assertEqual("JWT", rsa_token_jwk.header['typ'])
        self.assertEqual("RSA", rsa_token_jwk.header['jwk']['kty'])
        self.assertEqual(kid, rsa_token_jwk.header['jwk']['kid'])
        self.assertEqual("sig", rsa_token_jwk.header['jwk']['use'])
        e = pk.public_key().public_numbers().e
        n = pk.public_key().public_numbers().n
        expected_n = utils.force_unicode(
            utils.base64url_encode(
                n.to_bytes((n.bit_length() + 7) // 8, byteorder='big')))
        expected_e = utils.force_unicode(
            utils.base64url_encode(
                e.to_bytes((e.bit_length() + 7) // 8, byteorder='big')))
        self.assertEqual(expected_n, rsa_token_jwk.header['jwk']['n'])
        self.assertEqual(expected_e, rsa_token_jwk.header['jwk']['e'])
        self.assertEqual(3, len(rsa_token_jwk.header))
        self.assertEqual("1234567890", rsa_token_jwk.payload['sub'])
        self.assertEqual("John Doe", rsa_token_jwk.payload['name'])
        self.assertEqual(1516239022, rsa_token_jwk.payload['iat'])
        self.assertEqual(3, len(rsa_token_jwk.payload))
        rsa_token_jwk_signature = rsa_token_jwk.compute_signature(pk)
        self.assertTrue(
            rsa_token_jwk.verify_signature(
                pubkey, utils.base64url_decode(rsa_token_jwk_signature)))
        expected_signature = "jheDPqm8kxisAUcuDX-gHdTEIQDan_qRphZddj2VkcW-wJbVARly1Wzaw4of96Dl0xJXqJBV_kKG5UmmEiiEjQWUZzY4_XuZmI_STEf7FvVe_OPbN6fmyzGJQZSJVaoXTMYw8_yhQ1fIip6ctGVKrt6752RolratwDsYVZawQ1J9V3WIioPvXjQoyEGbothy7yOxemZXB71SMcQ-mmLKc8v0mirA8kyR8Wg0lw_JkRVRbViItn6SMFg2_Fuf12P1rkxx2qo3BVPzvgz1Nln4U8kFe2HGdtpc2IMTrAvzO0hOhc8cBe2-9HZJAFdGd_6SPhkp1VVlx-qTIL2y0EqH4Q"
        self.assertEqual(expected_signature,
                         utils.force_unicode(rsa_token_jwk_signature))
예제 #8
0
    def test_ifOpponentDexModIsPositiveModIsNotAppliedToArmor(self):
        testCharacter1 = Rogue()
        testCharacter2 = Character()
        testCharacter2.dexterity = 12
        roll = Roll(testCharacter1, testCharacter2, 10)
        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(4, testCharacter2.hitPoints)
예제 #9
0
    def test_addsDexModToAttacksInsteadOfStrength(self):
        testCharacter1 = Rogue()
        testCharacter2 = Character()
        testCharacter1.dexterity = 12
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor - 1)
        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(3, testCharacter2.hitPoints)
예제 #10
0
    def test_does3DmgInsteadOf1OnSuccessfulAttack(self):
        testCharacter1 = Monk()
        testCharacter2 = Character()
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor)

        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(2, testCharacter2.hitPoints)
예제 #11
0
    def test_attackRollNotIncreasedIfNot2ndOr3rdLevel(self):
        testCharacter1 = Monk()
        testCharacter2 = Character()
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor-1)

        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(5, testCharacter2.hitPoints)
예제 #12
0
    def test_StrModIsAppliedToAttack(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter1.strength = 12
        roll = testCharacter2.armor - 1
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(3, testCharacter2.hitPoints)
예제 #13
0
    def test_CharacterLevelsAfter1000ExperiencePoints(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter1.experiencePoints = 990
        roll = testCharacter2.armor
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(testCharacter1.level, 2)
예제 #14
0
    def test_dontAddWisdomModIfNegativeToArmor(self):
        testCharacter1 = Character()
        testCharacter2 = Monk()
        testCharacter2.wisdom = 8
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor)

        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(4, testCharacter2.hitPoints)
예제 #15
0
    def test_attackRollIncreasedBy1Every3rdLevel(self):
        testCharacter1 = Monk()
        testCharacter2 = Character()
        testCharacter1.level = 3
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor-1)

        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(2, testCharacter2.hitPoints)
예제 #16
0
    def test_DeadCharacterCannotBeAttacked(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter2.isAlive = False
        testCharacter2.hitPoints = 0
        roll = testCharacter2.armor
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(0, testCharacter2.hitPoints)
예제 #17
0
    def test_ifTargetCharacterHP0OrLessTargetIsDead(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter2.hitPoints = 1
        roll = testCharacter2.armor
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()
        testCharacter2.checkLivingStatus()

        self.assertFalse(testCharacter2.isAlive)
예제 #18
0
    def test_monkGains6HPPerLevel(self):
        testCharacter1 = Monk()
        testCharacter2 = Character()
        testCharacter1.experiencePoints = 990
        roll = Roll(testCharacter1, testCharacter2, testCharacter2.armor)

        attack = Attack(testCharacter1, testCharacter2, roll.initialRoll)

        attack.attemptAttack()

        self.assertEqual(11, testCharacter1.hitPoints)
예제 #19
0
    def test_CharacterOnlyLevelsEvery1000ExperiencePoints(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter1.experiencePoints = 1001
        testCharacter1.level = 2
        roll = testCharacter2.armor
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()

        self.assertEqual(testCharacter1.level, 2)
예제 #20
0
    def test_StrModIsDoubleOnCritHit(self):
        testCharacter1 = Character()
        testCharacter2 = Character()
        testCharacter1.strength = 12
        testCharacter2.hitPoints = 6
        roll = 20
        attack = Attack(testCharacter1, testCharacter2, roll)

        attack.attemptAttack()
        testCharacter2.checkLivingStatus()

        self.assertFalse(testCharacter2.isAlive)
예제 #21
0
    def test_attack_payload(self):
        header = "eyJhbGciOiJIUzI1NiIsImtpZCI6Im15X2tleSIsInR5cCI6IkpXVCJ9"
        payload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"
        signature = "-HQAruitA6V6IPPAFmo5nGpFVp2zvb3rF9fwkDiCVI0"
        token_kid = ".".join([header, payload, signature])
        # sample snippet from payload https://raw.githubusercontent.com/fuzzdb-project/fuzzdb/master/attack/json/JSON_Fuzzing.txt
        attack = Attack(token_kid)
        attack.attack_payload("./test_resources/fuzzdb_json_snippet.txt")
        attacks = attack.payloads
        self.assertEqual(len(attacks), 4)
        expected_header1 = {
            "alg": "HS256",
            "kid": "{\"1\":\"0\"}",
            "typ": "JWT"
        }
        header1 = json.loads(
            utils.base64url_decode(attacks['attack_payload_1'].split(".")[0]))
        self.assertEqual(expected_header1, header1)
        self.assertEqual(payload, attacks['attack_payload_1'].split(".")[1])
        self.assertEqual(signature, attacks['attack_payload_1'].split(".")[2])

        expected_header2 = {"alg": "HS256", "kid": "{\"1\":0}", "typ": "JWT"}
        header2 = json.loads(
            utils.base64url_decode(attacks['attack_payload_2'].split(".")[0]))
        self.assertEqual(expected_header2, header2)
        self.assertEqual(payload, attacks['attack_payload_2'].split(".")[1])
        self.assertEqual(signature, attacks['attack_payload_2'].split(".")[2])

        expected_header3 = {
            "alg": "HS256",
            "kid": "{\"0\":\"\\x00\"}",
            "typ": "JWT"
        }
        header3 = json.loads(
            utils.base64url_decode(attacks['attack_payload_3'].split(".")[0]))
        self.assertEqual(expected_header3, header3)
        self.assertEqual(payload, attacks['attack_payload_3'].split(".")[1])
        self.assertEqual(signature, attacks['attack_payload_3'].split(".")[2])

        expected_header4 = {
            "alg": "HS256",
            "kid": "{\"0\":[1,2]}",
            "typ": "JWT"
        }
        header4 = json.loads(
            utils.base64url_decode(attacks['attack_payload_4'].split(".")[0]))
        self.assertEqual(expected_header4, header4)
        self.assertEqual(payload, attacks['attack_payload_4'].split(".")[1])
        self.assertEqual(signature, attacks['attack_payload_4'].split(".")[2])
예제 #22
0
파일: Attacker.py 프로젝트: ydnzol/AnyScan
 def createTask(self, param):
     id = str(uuid.uuid1())
     ip = param["ip"]
     port = param["port"]
     attack_task_id_dict = param["attack_task_id_dict"]
     attack_type = param["attack_type"]
     callback = param["callback"]
     __create_status, id = self.create_task(id, self.attackObject.pid,
                                            attack_type,
                                            self.attackObject.type, ip,
                                            port, attack_task_id_dict)
     if __create_status is False:
         return False
     # 设置该任务的任务id
     sshAttacker = Attack(self.attackObject)
     t = threading.Thread(target=sshAttacker.attack,
                          args=({
                              "ip": ip,
                              "port": port,
                              "id": id,
                              "callback": callback,
                              "attack_type": attack_type
                          }, ))
     t.start()
     return True
예제 #23
0
    def test_attack_pubkey_deception_jku(self):
        rsa256_token_header = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
        rsa256_token_payload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"
        rsa256_token_signature = "ZR8EJ-ssd7b3Z9ZrCODkK_tJvOVXNZbcUn_FQAbLlKjPdEkNNCP_i5h84QfRXA8cWu1Z83UOb25Oogw0GIE9k-Q4AJO-BwEC2muHKRdzgHGrO6_2abeFJxAZapSf4ww39UlGzYX22b2kRYECLmsVaa0NV1KyQIf147h460wDGDr1wd2OCvUZXYULA_vzzRo3HHX440XOx_CnBvrR7shqnIjOLycEG61Ganq6oJsujVXHTQUtKdNB1Amu9NEQRRQzYWSTLuUMwV9mJnCuyr9bWp5srd3VPOC1bMXU2UgJiauw8eYu_w2_bbgZOn0jwajiygkfuJXNJGi8k_09sJmJ0w"
        rsa_token_ser = ".".join([
            rsa256_token_header, rsa256_token_payload, rsa256_token_signature
        ])
        rsa_token = TestJWT.deserialize(rsa_token_ser)
        self.assertEqual("RS256", rsa_token.get_algorithm())
        self.assertEqual("JWT", rsa_token.header['typ'])
        self.assertEqual(2, len(rsa_token.header))
        self.assertEqual("1234567890", rsa_token.payload['sub'])
        self.assertEqual("John Doe", rsa_token.payload['name'])
        self.assertEqual(1516239022, rsa_token.payload['iat'])
        self.assertEqual(3, len(rsa_token.payload))
        pk: RSAPrivateKey = load_pem_private_key(
            utils.read_pem_file("./keys/pk1.pem"), None, default_backend())
        pubkey: RSAPublicKey = pk.public_key()
        self.assertTrue(
            rsa_token.verify_signature(
                pubkey, utils.base64url_decode(rsa256_token_signature)))

        rsa_token_jwk = TestJWT.deserialize(rsa_token_ser)
        kid = "my_own_key"
        jku = "https://webhook.site/4820366e-4acf-4492-8b8b-2fd4e0b26be2"
        attack = Attack(rsa_token_ser)
        attack.attack_pubkey_deception_jku(pk, jku, jwt=None, kid=kid)
        ser_rsa_token_jwk = attack.payloads['attack_pubkey_deception_jku']
        rsa_token_jwk = TestJWT.deserialize(ser_rsa_token_jwk)
        jku_signature = TestJWT.split_jwt(ser_rsa_token_jwk)[2]
        expected_signature = "e5xKg2xAMXeDD2BLCYAaSueV3wuKMeqSl0YPXaL1y84Z2uDZiwLGLUV92Pmcl7qfhWjJtJQ-LXn2g95-lU5kOXkj9Si1onsVk3ZUHcXQcAKRrY1B2KFe4IbCBhQFpiI34Sm6Xr8MrqjrPrILYvhXE8ZLEBxDG_JebWOqL3H6Hef09J-rvb1XJqqLtHj7vpvuKmll7vG8LHM8BKws1GyVfzkqk3jvmUGJCF3lWQ4npXI2eSc5aGxGWJEkd3XpFkMUriWk0bkKwYyF3VTr1VfSlEq5xkiX-WA92psXRQZsjEX90sL5-qYKLzrvdBqhssL1T5LQAAGAkXAwLFqXGZ5NUw"
        self.assertEqual(expected_signature, jku_signature)
        self.assertEqual("RS256", rsa_token_jwk.get_algorithm())
        self.assertEqual("JWT", rsa_token_jwk.header['typ'])
        self.assertEqual(kid, rsa_token_jwk.header['kid'])
        self.assertEqual(jku, rsa_token_jwk.header['jku'])
        self.assertEqual("1234567890", rsa_token_jwk.payload['sub'])
        self.assertEqual("John Doe", rsa_token_jwk.payload['name'])
        self.assertEqual(1516239022, rsa_token_jwk.payload['iat'])
        self.assertEqual(3, len(rsa_token_jwk.payload))
        jwks = json.loads(attack.payloads['attack_pubkey_deception_jku_jwks'])
        jku_pubkey: RSAPublicKey = utils.rsa_jwks_to_pubkey(jwks, kid)
        rsa_token_jwk.verify_signature(jku_pubkey,
                                       utils.base64url_decode(jku_signature))
예제 #24
0
    def __init__(self, config):
        self.set_up_boards()

        if config == []:
            enemy_config = self.player
        else:
            enemy_config = config

        self.attacker = Attack(enemy_config, HuntType.LINES, self)
        self.do_player_attack()
예제 #25
0
    def __init__(self):
        self.set_up_boards()
        self.attacker = Attack([], HuntType.LINES, self)
        self.print_boards()

        first_move = input("Do I take the first move? (y/n) ")

        if first_move.lower() == "y":
            self.do_player_attack()

        self.do_opponent_attack()
        self.do_player_attack()
예제 #26
0
 def force_attack(self, enemy):
     if enemy.position == 'air':
         getAttack = Attack(self.air_attack, self.air_attack_type, self.name)
         getAttack.sendAttack(enemy)
     else:
         getAttack = Attack(self.attack, self.attack_type, self.name)
         getAttack.sendAttack(enemy)
예제 #27
0
    def test_attack_alg_none(self):
        ser_jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.\
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

        test_jwt: TestJWT = TestJWT.deserialize(ser_jwt)
        attack = Attack(ser_jwt)
        attack.attack_none()
        attacks = attack.payloads
        self.assertEqual(len(attacks), 3)
        self.assertEqual(
            attacks['attack_alg_none'], "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0"
            ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."
        )
        self.assertEqual(
            attacks['attack_alg_None'], "eyJhbGciOiJOb25lIiwidHlwIjoiSldUIn0"
            ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."
        )
        self.assertEqual(
            attacks['attack_alg_NONE'], "eyJhbGciOiJOT05FIiwidHlwIjoiSldUIn0"
            ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."
        )
예제 #28
0
파일: main.py 프로젝트: Denise-Yang/rosg
 def createSpell(self,sx,sy,endx,endy, size, power, isSpAttk):
     #shoots spell in certain direction
     if endx-sx != 0:
         angle = math.atan((endy-sy)/(endx-sx))
     elif endy > sy:
         angle = math.pi/2
     else:
         angle = -math.pi/2
     if endx < sx:
         angle -= math.pi
     if isSpAttk:
         attk = SpAttack(sx + size//2,sy + size//2, angle, power)
     else:
         attk = Attack(sx + size//2,sy + size//2, angle, power)
     return attk
예제 #29
0
 def delete(self):
     attack = Attack.find_by_attacker_or_target(self, self.connection)
     if attack is not None and attack.boss_id is None:
         # TODO: fix problem is person is attacked during boss battle and dies by boss.
         self.Parent.Log(
             "rpgGame",
             "something is wrong in the code, char got deleted while still in a fight."
         )
     elif attack is not None:
         attack.delete()
     for bounty in Bounty.find_all_by_character(self, self.connection):
         bounty.delete()
     SpecialCooldown.delete_all_from_character(self, self.connection)
     ActiveEffect.delete_all_by_target(self, self.connection)
     self.connection.execute(
         """DELETE FROM characters WHERE character_id = ?""",
         (self.char_id, ))
예제 #30
0
def test_Attack_with_Spear():
    ctx = Ctx(app_username='******')
    db = InvokePSQL()
    a = Weapon(db=db, ctx=ctx, name='Spear')
    c = PlayerCharacter(ctx=ctx, db=db, race_candidate='Hill dwarf',
                        class_candidate='Fighter', ability_array_str='point_buy_even')
    c.set_name_str(group_str="Heroes",index_position=0)
    d = PlayerCharacter(ctx=ctx, db=db, race_candidate='Hill dwarf',
                        class_candidate='Fighter', ability_array_str='point_buy_even')
    d.set_name_str(group_str="Opponents",index_position=0)
    b = Attack(ctx=ctx, weapon_obj=a, attack_modifier=0,
               damage_modifier=0,
               attack_type='Ranged', attacker=c,
               target=d, versatile_use_2handed=False, vantage='Normal')
    assert(b.weapon_obj.name == 'Spear')
    assert(b.vantage == 'Normal')
    assert(b.die_used == 6)
    assert(b.rolls_used == 1)
    assert(b.possible_damage > 0 and b.possible_damage <= 8)
    assert(b.attack_value)
예제 #31
0
    def update(self, keysDown, screenWidth, screenHeight, attacks, dt):
        if (self.player == 0):
            #Move The Charecter
            if keysDown(pygame.K_LEFT):
                self.x -= self.xSpeed
            if keysDown(pygame.K_RIGHT):
                self.x += self.xSpeed
            if keysDown(pygame.K_UP):
                if (self.canJump):
                    self.jump()

            self.attackDelay -= dt

            if keysDown(pygame.K_DOWN and self.attackDelay <= 0):
                attacks[self.player].add(
                    Attack(self.x + self.width // 2, self.y))
                self.attackDelay = 500 + random.randint(1, 1000)
        #Gravity
        if (self.ySpeed < 10):
            self.ySpeed += 1
        self.y += self.ySpeed
        #Update Box
        self.updateRect()

        #Check for collitions
        if (self.rect.left < 0):
            self.x = self.width // 2
        if (self.rect.right > screenWidth):
            self.x = screenWidth - self.width // 2
        if (self.rect.top < 0):
            self.y = self.height // 2
        if (self.rect.bottom > screenHeight):
            self.y = screenHeight - self.height // 2
            self.canJump = True
        #Update Box
        self.updateRect()
예제 #32
0
                   base_hp=bot["base_hp"],
                   is_ad=bot["is_ad"])

    while range(0, 10):
        print("""
                Rakiple Karşılaştınız!!!
                Saldırmak için : 1
                Çıkmak için : quit
                """)
        komut = input("\nseçiminizi yapın : ")
        if komut == "1":
            player.mevcut_durumu_görüntüle()
            yetenek = input("Yeteneği seçiniz (Q-W-E-R) : ")
            if yetenek == "Q":
                skill = player.skill_q
            elif yetenek == "W":
                skill = player.skill_w
            elif yetenek == "E":
                skill = player.skill_e
            elif yetenek == "R":
                skill = player.ulti
            else:
                skill = player.skill_q

            attack = Attack(player, player2, skill)
            attack.attack()
            öldü_mü = player2.öldümü()
            if öldü_mü:
                print("kazandınız")
                break
예제 #33
0
def main(opt):

    dataset = VideoDataset(opt, 'inference')
    opt["vocab_size"] = dataset.get_vocab_size()
    opt["seq_length"] = dataset.max_len

    if opt['beam_size'] != 1:
        assert opt["batch_size"] == 1
    if opt["model"] == 'S2VTModel':
        model = S2VTModel(opt["vocab_size"],
                          opt["max_len"],
                          opt["dim_hidden"],
                          opt["dim_word"],
                          opt['dim_vid'],
                          n_layers=opt['num_layers'],
                          rnn_cell=opt['rnn_type'],
                          bidirectional=opt["bidirectional"],
                          rnn_dropout_p=opt["rnn_dropout_p"])
    elif opt["model"] == "S2VTAttModel":
        encoder = EncoderRNN(opt["dim_vid"],
                             opt["dim_hidden"],
                             n_layers=opt['num_layers'],
                             rnn_cell=opt['rnn_type'],
                             bidirectional=opt["bidirectional"],
                             input_dropout_p=opt["input_dropout_p"],
                             rnn_dropout_p=opt["rnn_dropout_p"])
        decoder = DecoderRNN(opt["vocab_size"],
                             opt["max_len"],
                             opt["dim_hidden"],
                             opt["dim_word"],
                             n_layers=opt['num_layers'],
                             rnn_cell=opt['rnn_type'],
                             input_dropout_p=opt["input_dropout_p"],
                             rnn_dropout_p=opt["rnn_dropout_p"],
                             bidirectional=opt["bidirectional"])
        model = S2VTAttModel(encoder, decoder)
    else:
        return

    # if torch.cuda.device_count() > 1:
    #     print("{} devices detected, switch to parallel model.".format(torch.cuda.device_count()))
    #     model = nn.DataParallel(model)

    #model, videopath, targetcap, dataset, config, optimizer, crit, window

    #config: batch_size, c, learning rate, num it,input shape

    config = {
        #lr 0.005 and dimensions 224, c was 100. #Best was 0.06 lr, c = 1 for show and fool.
        #
        "batch_size": BATCH_SIZE,
        "c": 10000,
        "learning_rate": 0.2,
        "num_iterations": 1000,
        "input_shape": (224, 224),
        "num_frames": 288,
        "dimensions": 224,
        "k": 0.1,
        # "attack_algorithm": "showandfool"
        "attack_algorithm": "carliniwagner"
    }

    convnet = 'vgg16'
    # convnet = 'nasnetalarge'
    # convnet = 'resnet152'
    full_decoder = ConvS2VT(convnet, model, opt)
    '''
    Layer freezing experiment.
    
    Top 10 contributing layers: 
    conv.cell_stem_1.comb_iter_0_right.separable_1.depthwise_conv2d.weight
    conv.cell_stem_1.comb_iter_2_right.separable_2.depthwise_conv2d.weight
    conv.cell_stem_1.comb_iter_1_right.separable_1.depthwise_conv2d.weight
    conv.cell_16.comb_iter_4_left.separable_1.depthwise_conv2d.weight
    conv.cell_17.comb_iter_4_left.separable_1.depthwise_conv2d.weight
    conv.cell_16.comb_iter_4_left.separable_1.pointwise_conv2d.weight
    conv.cell_13.comb_iter_4_left.bn_sep_1.weight
    conv.reduction_cell_0.conv_prev_1x1.bn.weight
    conv.cell_17.comb_iter_4_left.separable_2.depthwise_conv2d.weight
    conv.cell_13.comb_iter_0_left.bn_sep_1.weight
    
    
    '''

    top = open("top_layers.txt", "r")
    top_layers = top.readlines()
    top.close()
    print(top_layers)

    #set the gradients on the layers you don't want to contribute to 0
    top_layers = []

    for name, parameters in full_decoder.named_parameters():
        reset = True
        for f in top_layers:
            if name in f:
                reset = False

        if reset:
            parameters.require_grad = False
            if parameters.grad is not None:
                print(name)
                parameters.grad.data.zero_()

    # for name, parameters in full_decoder.named_parameters():
    #     for f in top_layers:
    #         if name not in f:
    #             print(name)
    #             parameters.require_grad = False
    #             if parameters.grad is not None:
    #                 # parameters.data = 0
    #                 parameters.grad.data.zero_()
    #         else:
    #             # print(name)
    #             continue

    #'A woman is cutting a green onion'
    video_path = opt['videos'][0]

    tf_img_fn = ptm_utils.TransformImage(full_decoder.conv)
    load_img_fn = PIL.Image.fromarray
    vocab = dataset.get_vocab()

    vid_id = video_path.split('/')[-1]
    vid_id = vid_id.split('.')[0]

    viable_ids = dataset.splits['test'] + dataset.splits['val']
    viable_target_captions = []
    for v_id in viable_ids:
        if v_id == vid_id:
            continue
        plausible_caps = [
            ' '.join(toks)
            for toks in dataset.vid_to_meta[v_id]['final_captions']
        ]
        viable_target_captions.extend(plausible_caps)

    #target_caption = np.random.choice(viable_target_captions)
    # 5 captions:
    '''
    <sos> A person is typing into a laptop computer <eos>
    <sos> A boy is kicking a soccer ball into the goal <eos>
    <sos> Someone is frying fish <eos>
    <sos> A dog is running with a ball <eos>
    <sos> The cat approaches on grass <eos>
    
    '''
    captions = {
        1: '<sos> A woman is talking <eos>',
        2: '<sos> A boy is kicking a soccer ball into the goal <eos>',
        3: '<sos> A man is frying fish <eos>',
        4: '<sos> A dog is running with a ball <eos>',
        5: '<sos> A cat is walking on grass <eos>'
    }

    #1 doesn't work
    videos = {

        #2 is too high res or something, replaced X6uJyuD_Zso_3_17.avi with nc8hwLaOyZU_1_19.avi
        #5,'ceOXCFUmxzA_100_110.avi' out of memory, replaced with 'X7sQq-Iu1gQ_12_22'
        #1: 'RSx5G0_xH48_12_17.avi',
        2: 'nc8hwLaOyZU_1_19.avi',
        3: 'O2qiPS2NCeY_2_18.avi',
        4: 'kI6MWZrl8v8_149_161.avi',
        5: 'X7sQq-Iu1gQ_12_22.avi',
        6: '77iDIp40m9E_159_181.avi',
        7: 'SaYwh6chmiw_15_40.avi',
        8: 'pFSoWsocv0g_8_17.avi',
        9: 'HmVPxs4ygMc_44_53.avi',
        10: 'glii-kazad8_21_29.avi',
        11: 'AJJ-iQkbRNE_97_109.avi'
    }
    #"D:\College\Research\December 2018 Video Captioning Attack\video captioner\YouTubeClips\AJJ-iQkbRNE_97_109.avi"
    # video_path = ''

    video_path = 'D:\\College\\Research\\December 2018 Video Captioning Attack\\video captioner\\YouTubeClips\\' + videos[
        2]
    # target_caption = '<sos> A man is moving a toy <eos>'
    # target_caption = '<sos> A boy is kicking a soccer ball into the goal <eos>'

    #Just switch the number to get a target caption.
    target_caption = captions[1]

    #Should use the original caption function we use in the attack because the scaling is sightly different
    with torch.no_grad():
        frames = skvideo.io.vread(video_path, num_frames=config["num_frames"])

        # bp ---
        batches = create_batches(frames, load_img_fn, tf_img_fn)
        seq_prob, seq_preds = full_decoder(batches, mode='inference')
        sents = utils.decode_sequence(vocab, seq_preds)

        original_caption = sents[0]

    #video_path = 'D:\\College\Research\\December 2018 Video Captioning Attack\\video captioner\\YouTubeClips\\ACOmKiJDkA4_49_54.avi'

    #/96 gives 3 frames
    # length = math.ceil(len(skvideo.io.vread(video_path,num_frames=config["num_frames"]))/96)
    #12 frames
    length = 3
    print("Total number of frames: {}".format(length))
    adv_frames = []
    iteration = 1
    frame_counter = 0

    total_iterations = np.ceil(length / BATCH_SIZE)

    #model is full_decoder

    optimizer = ['Adam', (0.9, 0.999)]

    crit = utils.LanguageModelCriterion()
    seq_decoder = utils.decode_sequence

    # model, videopath, targetcap, dataset, config, optimizer, crit, window

    while (frame_counter < length):
        print("\n\n\nIteration {}/{}".format(iteration, int(total_iterations)))
        iteration = iteration + 1
        if length - frame_counter < BATCH_SIZE:
            window = [frame_counter, length]
            frame_counter = frame_counter + (length - frame_counter)
            print("Using frames {}".format(window))
            print("Frame counter at: {}\nTotal length is: {}\n".format(
                frame_counter, length))
            attack_package = S2VT_Attack(model=full_decoder,
                                         video_path=video_path,
                                         target=target_caption,
                                         dataset=dataset,
                                         config=config,
                                         optimizer=optimizer,
                                         crit=crit,
                                         seq_decoder=seq_decoder,
                                         window=window)
            carlini = Attack(attack_package=attack_package)
            finished_frames = carlini.execute(functional=True)
            adv_frames.append(finished_frames.detach().cpu().numpy())

        else:
            window = [frame_counter, frame_counter + BATCH_SIZE - 1]
            print("Using frames {}".format(window))
            print("Frame counter at: {}\nTotal length is: {}\n".format(
                frame_counter, length))

            attack_package = S2VT_Attack(model=full_decoder,
                                         video_path=video_path,
                                         target=target_caption,
                                         dataset=dataset,
                                         config=config,
                                         optimizer=optimizer,
                                         crit=crit,
                                         seq_decoder=seq_decoder,
                                         window=window)
            carlini = Attack(attack_package=attack_package)
            finished_frames = carlini.execute(functional=True)
            adv_frames.append(finished_frames.detach().cpu().numpy())
            frame_counter = frame_counter + BATCH_SIZE

    base_toks = video_path.split('/')
    base_dir_toks = base_toks[:-1]
    base_filename = base_toks[-1]
    base_name = ''.join(base_filename.split('.')[:-1])
    adv_path = os.path.join('/'.join(base_dir_toks),
                            base_name + '_adversarialWINDOW.avi')

    print("\nSaving to: {}".format(adv_path))
    # adv_frames_1 = np.concatenate(adv_frames, axis=0)
    # # batches = create_batches(adv_frames[0].astype(np.uint8), load_img_fn, tf_img_fn)
    # batches = exp_create_batches(adv_frames_1.astype(np.uint8), 3)
    # seq_prob, seq_preds = full_decoder(batches, mode='inference')
    # sents = utils.decode_sequence(vocab, seq_preds)

    # print("Adversarial Frames 1: {}".format(sents[0]))
    adv_frames = np.concatenate(adv_frames, axis=0)
    # batches = create_batches(adv_frames, load_img_fn, tf_img_fn)
    # seq_prob, seq_preds = full_decoder(batches, mode='inference')
    # sents = utils.decode_sequence(vocab, seq_preds)
    #
    # print("Adversarial Frames 2: {}".format(sents[0]))

    outputfile = adv_path

    writer = skvideo.io.FFmpegWriter(
        outputfile,
        outputdict={
            #huffyuv is lossless. r10k is really good

            # '-c:v': 'libx264', #libx264 # use the h.264 codec
            '-c:v': 'huffyuv',  #r210 huffyuv r10k
            # '-pix_fmt': 'rgb32',
            # '-crf': '0', # set the constant rate factor to 0, which is lossless
            # '-preset': 'ultrafast'  # ultrafast, veryslow the slower the better compression, in princple, try
        })
    for f in adv_frames:
        writer.writeFrame(f)

    writer.close()

    # np_path = os.path.join('/'.join(base_dir_toks), base_name + '_adversarialWINDOW')
    # np.save(np_path, adv_frames)
    #ffv1 0.215807946043995
    #huffyuv 0.21578424050191813
    #libx264 0.2341074901578537
    #r210 -0.7831487262059795, -0.7833399258537526
    #gif 0.6889478809555243
    #png 0.2158991440582696 0.21616862708842177
    #qtrle  0.21581286337807626
    #flashsv 0.21610510459932186 0.21600030673323545
    #ffvhuff 0.21620682250167533
    #r10k similar to r210
    #rawvideo 0.21595001

    with torch.no_grad():

        #getting a new model to see how it actually works now
        # full_decoder = ConvS2VT(convnet, model, opt)
        full_decoder = full_decoder.eval()

        frames = skvideo.io.vread(adv_path)

        frames = np.float32(frames)
        plt.imshow(frames[0] / 255.)
        plt.show()

        difference = np.array(adv_frames) - np.array(frames)
        np.save('difference_tmp', difference)
        #loadtxt to load np array from txt

        exp = np.load('difference_tmp.npy')

        # numpy_frames = np.load(np_path+'.npy')
        # print("Are numpy frames == adv frames: ", np.array_equal(numpy_frames, adv_frames))
        # print("Is the saved array equal to loaded array for difference: ", np.array_equal(exp, difference))

        frames = frames + difference

        # batches = exp_create_batches(numpy_frames, BATCH_SIZE)
        # feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        # seq_prob, seq_preds = full_decoder.encoder_decoder_forward(feats, mode='inference')
        #
        # # seq_prob, seq_preds = full_decoder(batches, mode='inference')
        # sents = utils.decode_sequence(vocab, seq_preds)
        # numpy_caption = sents[0]
        #
        # print("Numpy Frames exp: {}".format(numpy_caption))
        #

        # numpy_frames_tensor = torch.tensor(numpy_frames)
        # numpy_frames_tensor = numpy_frames_tensor.float()
        # batches = exp_create_batches(numpy_frames_tensor, BATCH_SIZE)
        # feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        # seq_prob, seq_preds = full_decoder.encoder_decoder_forward(feats, mode='inference')
        #
        # # seq_prob, seq_preds = full_decoder(batches, mode='inference')
        # sents = utils.decode_sequence(vocab, seq_preds)
        # numpy_caption_tensor = sents[0]
        #
        # print("Numpy Frames tensor: {}".format(numpy_caption_tensor))

        # numpy_frames = numpy_frames.astype(np.uint8)
        # batches = create_batches(numpy_frames, load_img_fn, tf_img_fn)
        #
        # # batches = exp_create_batches(adv_frames, BATCH_SIZE)
        # # feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        # # seq_prob, seq_preds = full_decoder.encoder_decoder_forward(feats, mode='inference')
        #
        # seq_prob, seq_preds = full_decoder(batches, mode='inference')
        # sents = utils.decode_sequence(vocab, seq_preds)
        #
        # print("Numpy Frames originalscale: {}".format(sents[0]))
        # # bp ---
        adv_frames = adv_frames.astype(np.uint8)
        batches = create_batches(adv_frames, load_img_fn, tf_img_fn)

        # batches = exp_create_batches(adv_frames, BATCH_SIZE)
        # feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        # seq_prob, seq_preds = full_decoder.encoder_decoder_forward(feats, mode='inference')

        seq_prob, seq_preds = full_decoder(batches, mode='inference')
        sents = utils.decode_sequence(vocab, seq_preds)

        print("Adversarial Frames old: {}".format(sents[0]))

        batches = exp_create_batches(adv_frames, BATCH_SIZE)
        feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        seq_prob, seq_preds = full_decoder.encoder_decoder_forward(
            feats, mode='inference')

        # seq_prob, seq_preds = full_decoder(batches, mode='inference')
        sents = utils.decode_sequence(vocab, seq_preds)

        print("Adversarial Frames new: {}".format(sents[0]))

        frames = frames.astype(np.uint8)
        batches = create_batches(frames, load_img_fn, tf_img_fn)

        # batches = exp_create_batches(frames, BATCH_SIZE)
        # feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        # seq_prob, seq_preds = full_decoder.encoder_decoder_forward(feats, mode='inference')

        seq_prob, seq_preds = full_decoder(batches, mode='inference')
        sents = utils.decode_sequence(vocab, seq_preds)
        print("frames old caption: ", sents[0])

        # frames = frames.astype(np.uint8)
        # batches = create_batches(frames, load_img_fn, tf_img_fn)

        batches = exp_create_batches(frames, BATCH_SIZE)
        feats = full_decoder.conv_forward((batches.unsqueeze(0)))
        seq_prob, seq_preds = full_decoder.encoder_decoder_forward(
            feats, mode='inference')

        # seq_prob, seq_preds = full_decoder(batches, mode='inference')
        sents = utils.decode_sequence(vocab, seq_preds)
        adv_caption = sents[0]

    print(
        "\nOriginal Caption: {}\nTarget Caption: {}\nAdversarial Caption: {}".
        format(original_caption, target_caption, adv_caption))
예제 #34
0
 def attack(self, attacks):
     attacks[self.player].add(
         Attack(self.x + self.width // 2 * self.direction, self.y,
                self.direction))
     self.attackDelay = 500 + random.randint(1, 1000)
예제 #35
0
class GameManager:
    def __init__(self):
        self.set_up_boards()
        self.attacker = Attack([], HuntType.LINES, self)
        self.print_boards()

        first_move = input("Do I take the first move? (y/n) ")

        if first_move.lower() == "y":
            self.do_player_attack()

        self.do_opponent_attack()
        self.do_player_attack()

    def do_player_attack(self):
        self.attacker.begin_attacking()

    def after_attack_event(self):
        self.print_boards()

        if game_logic.CheckWinner(self.attacker.view_of_opponent):
            print("Woohoo! I win")
            return

        self.do_opponent_attack()

        if game_logic.CheckWinner(self.player):
            # you check your own board to see if the opponent has won
            print("Boo! You win")

    def attack_from_below(self, attack):
        """
        called from the attack class, should return the result
        """

        i, j = attack[0]
        self.print_move(i, j)
        outcome = self.get_outcome()

        return outcome

    def do_opponent_attack(self):
        Player = self.player
        i1, i2 = self.get_opponent_move()

        if (Player[i1][i2] == 2) or (Player[i1][i2] == 4):
            # They may (stupidly) hit the same square twice so we check for occupied or hit
            Player[i1][i2] = constants.ENEMY_HIT
            print("Hit!")
        else:
            Player[i1][i2] = constants.ENEMY_MISS
            print("Missed!")

        self.print_boards()

    def set_up_boards(self):
        while True:
            self.player, self.opponent = game_logic.InitBoards()

            try:
                self.player = game_logic.DeployFleet(self.player, False)
            except RuntimeError as e:
                continue

            break

    def get_outcome(self):
        while True:
            entry = input("Outcome? (h/m) ")

            if entry.lower() == "h":
                return True
            elif entry.lower() == "m":
                return False
            else:
                print("Invalid input: must enter h (hit) or m (miss)")

    @staticmethod
    def print_move(i, j):
        print("my move: ", chr(i + 65), j + 1)

    @staticmethod
    def get_opponent_move():
        # We are expecting letter+number, e.g. C3
        is_valid = False
        while not is_valid:
            # Read opponent's move
            entry = input("Enter opponents move (e.g. C3): ")
            entry = entry.lower()
            if (len(entry) == 2) or (len(entry) == 3):
                # Convert letter coordinate into ASCII code and convert to index by subtracting code for 'a'
                i1 = ord(entry[0]) - 97
                # Convert number coordinate to zero-based indexing
                i2 = int(entry[1:]) - 1
                # Check whether they are valid coordinates
                if (i1 <= 5) and (i1 >= 0):
                    # Top half of board
                    is_valid = (i2 >= 0) and (i2 <= 5)
                elif (i1 >= 6) and (i1 <= 11):
                    # Bottom half of board
                    is_valid = (i2 >= 0) and (i2 <= 11)
            if not is_valid:
                print("Invalid coordinate, try again")
        return i1, i2

    def print_boards(self):
        """
        Clear the screen and draw the two boards side by side
        """

        Player = self.player
        Opponent = self.attacker.view_of_opponent

        # Clear the screen
        os.system("cls" if os.name == "nt" else "clear")
        # Print board labels
        print(" " * 10, "PLAYER", " " * 30, "OPPONENT")
        letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
        for x in range(6):
            print(
                letters[x],
                "  ".join(map(GameManager.display_char, Player[x])),
                " " * 18,
                "| ",
                "  ".join(map(GameManager.display_char, Opponent[x])),
            )
        for x in range(6, 12):
            print(
                letters[x],
                "  ".join(map(GameManager.display_char, Player[x])),
                " | ",
                "  ".join(map(GameManager.display_char, Opponent[x])),
            )
        print(" ", "  ".join(map(str, range(1, 10))), " 10 11 12", "  ", "  ".join(map(str, range(1, 10))), " 10 11 12")

    @staticmethod
    def display_char(x):
        """
        Mapping function that determines how each square state is displayed
        """

        if x == 0:
            return "?"
        elif x == constants.UNOCCUPIED or x == constants.BUBBLE:
            return " "
        elif x == constants.OCCUPIED:
            return "X"
        elif x == 3:
            return " "
        elif x == 4:
            return "*"
        elif x == constants.ENEMY_MISS:
            return "."