Exemple #1
0
class TestSwordMethods(unittest.TestCase):
    def setUp(self):
        self.sword = Sword()

    def test_get_name(self):
        self.assertEqual(self.sword.name, 'Sword')

    def test_get_damage(self):
        self.assertEqual(self.sword.damage, 10)

    def test_set_damage(self):
        self.sword.damage = 20
        self.assertEqual(self.sword.damage, 20)

    def test_get_durability(self):
        self.assertEqual(self.sword.durability, 1)

    def test_set_durability(self):
        self.sword.wearout()
        self.assertEqual(self.sword.durability, 0.9)

    def test_attack(self):
        self.assertEqual(self.sword.attack(), 10)

    def test_set_durability_after_attack(self):
        self.assertIn(self.sword.durability, [0.9, 1])

    def test_le(self):
        b = Sword(damage=20)
        self.assertEqual(self.sword <= b, True)

    def test_str(self):
        string = 'Название: Sword; Урон: 10'
        self.assertEqual(str(self.sword), string)
def update_weapon(id):
    """ update a weapon in the weapon in the WeaponManager """
    content = request.json
    try:
        if content["type"] == "Sword":
            sword = Sword(
                content["name"], content["materials"],
                bool(content["is_cold_weapon"]), bool(content["is_inuse"]),
                datetime.strptime(content["manufacture_date"], "%Y-%m-%d"),
                float(content["sharp"]), float(content["length"]),
                bool(content["is_double_edged"]))
            sword.id = int(id)
            my_weapon_warehouse.update(sword)
        else:
            firearm = Firearm(
                content["name"], content["materials"],
                bool(content["is_cold_weapon"]), bool(content["is_inuse"]),
                datetime.strptime(content["manufacture_date"], "%Y-%m-%d"),
                int(content["bullets_num"]), float(content["range"]))
            firearm.id = int(id)
            my_weapon_warehouse.update(firearm)
        response = app.response_class(status=200,
                                      response="Success",
                                      mimetype='application/json')
    except ValueError as e:
        response = app.response_class(response=str(e), status=404)
    return response
Exemple #3
0
 def test_setter(self):
     sw = Sword('Sword', 0, 0)
     sw.name = 'Owowsword'
     sw.damage = 1
     sw.durability = 1
     self.assertFalse(sw.name == 'Sword')
     self.assertFalse(sw.damage == 0)
     self.assertFalse(sw.durability == 0)
Exemple #4
0
 def __init__(self, world, x, y, width, height, speed=5):
     super().__init__(world, x, y, width, height)
     self.world = world
     self.health = 10
     self.image = pygame.image.load('assets/chessman-knight.png')
     self.my_sword = Sword('Excalibur', 10, 'assets/Small_Sword_icon.png',
                           self.x - 18, self.y + 14)
     self.speed = speed
     self.attacking = False
Exemple #5
0
    def setUp(self) -> None:
        engine = create_engine('sqlite:///test_weapons.sqlite')

        # Creates all the tables
        Base.metadata.create_all(engine)
        Base.metadata.bind = engine

        self.test_weapon_manager = WeaponManager('test_weapons.sqlite')

        self.logPoint()

        self.test_firearm_1 = Firearm("Armsel Striker", "iron", False, True, datetime.datetime.strptime('24052010', "%d%m%Y"), 50, 50.0)
        self.test_firearm_2 = Firearm("Beretta A303", "iron", False, False, datetime.datetime.strptime('11032002', "%d%m%Y"), 0, 100.0)
        self.test_sword_1 = Sword("Skull Cleaver", "iron", True, True, datetime.datetime.strptime('11071992', "%d%m%Y"), 0.91, 3.1, False)
        self.test_sword_2 = Sword("Dawn Splitter", "wood", True, False, datetime.datetime.strptime('01081974', "%d%m%Y"), 0.82, 2.7, True)
        self.test_sword_3 = Sword("Grimfrost", "wood", True, True, datetime.datetime.strptime('18121988', "%d%m%Y"), 0.82, 2.7, True)
def add_weapon():
    """ Add a new Sword or Firearm to WeaponManager """
    content = request.json
    try:
        if content["type"] == "Sword":
            sword = Sword(
                content["name"], content["materials"],
                bool(content["is_cold_weapon"]), bool(content["is_inuse"]),
                datetime.strptime(content["manufacture_date"], "%Y-%m-%d"),
                float(content["sharp"]), float(content["length"]),
                bool(content["is_double_edged"]))
            my_weapon_warehouse.add(sword)
        else:
            firearm = Firearm(
                content["name"], content["materials"],
                bool(content["is_cold_weapon"]), bool(content["is_inuse"]),
                datetime.strptime(content["manufacture_date"], "%Y-%m-%d"),
                int(content["bullets_num"]), float(content["range"]))
            my_weapon_warehouse.add(firearm)
        response = app.response_class(status=200  # success
                                      )
    except ValueError as e:
        response = app.response_class(
            response=str(e),
            status=400  # failure
        )
    return response
Exemple #7
0
    def __init__(self, x=0, y=0, layer=0):
        super(Player, self).__init__(ika.Entity(x, y, layer, PLAYER_SPRITE),
                                     _playerAnim)

        self._animator = _Anim()

        self.state = self.standState()
        self.stats = initialStats.clone()

        self.baseStats = self.stats.clone()

        self.expFactor = 50.0
        self.exponent = 1.9

        self.sword = Sword()
        self.spear = Spear()
        self.spear.item = item.Item('Fishing Pole')
        self.sword.item = item.Item('Sharp Slicer')
        self.armor = None

        self.grapple = Grapple()

        self.items = []

        #self.weapon = self.spear
        self.weapon = self.sword
Exemple #8
0
def main():
    #stick = Weapon()
    # throws new excetion
    #print(stick.name, stick.damage)
    #stick.attack(None)
    common_sword = Sword()
    #print(common_sword.pro)
    common_bow = Bow()
    common_bow.damage = 4
    common_bow.accuracy = 5
    highest_damage_weapon = common_sword <= common_bow
    print(highest_damage_weapon, common_sword, common_bow)
Exemple #9
0
 def gen_enemies(self):
     if sum(self.current_wave) <= 0 and len(self.enemies) == 0:
         self.wave += 1
         self.current_wave = waves[self.wave]
         self.pause = True
         self.playPauseButton.change_img()
     else:
         wave_enemies = [Scorpion(), Wizard(), Invader(), Sword()]
         for x in range(len(self.current_wave)):
             if self.current_wave[x] != 0:
                 self.enemies.append(wave_enemies[x])
                 self.current_wave[x] -= 1
                 break
Exemple #10
0
 def test_deal_damage(self):
     sw1 = Sword('StrongSword', 100, 1)
     sw1.deal_damage(r=1)
     self.assertTrue(sw1.durability == 0.9)
     sw1.deal_damage(r=0)
     self.assertTrue(sw1.durability == 0.9)
Exemple #11
0
 def setUp(self):
     self.sword = Sword()
Exemple #12
0
 def __init__(self, conf, hermes):
     self.conf = conf
     self.processor = Processor(conf)
     self.sword = Sword(conf)
     self.hermes = hermes
Exemple #13
0
class Hades(object):
    def __init__(self, conf, hermes):
        self.conf = conf
        self.processor = Processor(conf)
        self.sword = Sword(conf)
        self.hermes = hermes

    def process_train_data(self):
        """
        Process the training data
        :return: x:np.array, y: np.array
        """
        sequences = self.processor.on(system="hades")

        word_feature, cxn_feature, labels, max_len = [], [], [], 0
        for sentence, index, sequence, label in sequences:
            if max_len < len(sentence):
                max_len = len(sentence)

            word_feature.append(index)
            cxn_feature.append(sequence)
            labels.append(label)
        max_len += 1

        word_feature = pad_sequences(word_feature, max_len)
        cxn_feature = pad_sequences(cxn_feature, max_len)

        seq_features = []
        for seq in cxn_feature:
            seq_features.append(to_categorical(seq, num_classes=4))

        seq_features = npy.array(seq_features)

        y = pad_sequences(labels, max_len, value=4)
        y = [to_categorical(i, num_classes=5) for i in y]

        x = merge(word_feature, seq_features)

        return x, y

    def process_test_data(self):
        """
        Process the test data
        :return: x: np.array
        """
        sequences, belonging = self.processor.up(system="hades")

        sentences, word_feature, cxn_feature, max_len = [], [], [], 0
        for sentence, index, sequence in sequences:
            if max_len < len(sentence):
                max_len = len(sentence)

            word_feature.append(index)
            cxn_feature.append(sequence)
            sentences.append(sentence)
        max_len += 1

        word_feature = pad_sequences(word_feature, max_len)
        cxn_feature = pad_sequences(cxn_feature, max_len)

        seq_features = []
        for seq in cxn_feature:
            seq_features.append(to_categorical(seq, num_classes=4))

        seq_features = npy.array(seq_features)
        x = merge(word_feature, seq_features)

        return sentences, x, belonging

    def train(self):
        """
        Train the model
        :return:
        """
        # Model Configuration
        model = self.sword.draw()

        # Load the data
        x, y = self.process_train_data()

        # Create the train data and validate data
        train_x, test_x, train_y, test_y = train_test_split(x,
                                                            y,
                                                            test_size=0.3,
                                                            random_state=24)
        train_x_kanji, train_x_cxn = resolve(train_x)

        with open(self.conf.validate_set.format("hades"), "wb") as fp:
            pickle.dump((test_x, test_y), fp)
        fp.close()

        # Train the model
        model.fit([train_x_kanji, train_x_cxn],
                  npy.array(train_y),
                  batch_size=16,
                  epochs=self.sword.epochs,
                  validation_split=0.2)
        model.save(self.conf.model_path.format("hades"))

    def evaluate(self):
        """
        Evaluate the model
        :return:
        """
        # Model Configuration
        model = self.sword.draw()

        # Load the test data
        # sentences, x = self.process_test_data()
        # x_kanji, x_cxn = resolve(x)
        with open(self.conf.validate_set.format("hades"), "rb") as fp:
            test_x, test_y = pickle.load(fp)
        fp.close()
        test_x_kanji, test_x_cxn = resolve(test_x)
        test_y = npy.argmax(test_y, axis=-1)

        # Load the model
        self.hermes.info("Load the model.bin.hades...")
        model.load_weights(self.conf.model_path.format("hades"))
        self.hermes.info("Load the model.bin.hades...Finished!")

        # Make the predictions
        predictions = model.predict([test_x_kanji, test_x_cxn])
        predictions = npy.argmax(predictions, axis=-1)

        self.hermes.info("Begin to predict...")

        pred_y, gold_y, count = [], [], 0
        for prediction in tqdm(predictions, desc="Predict"):
            sentence = test_x_kanji[count]
            len_of_sentence = get_length(sentence)
            prediction = prediction[-len_of_sentence:]
            labels = [
                self.conf.labels[label]
                for label in test_y[count][-len_of_sentence:]
            ]
            gold_y.append(labels)

            label_index = [self.conf.labels[row] for row in prediction]
            pred_y.append(label_index)

            count += 1

        report = classification_report(gold_y, pred_y)
        print(report)

        self.hermes.info("Begin to predict...Finished!")

    def predict(self):
        """
        Predict the test set with trained model
        :return:
        """
        # Model Configuration
        model = self.sword.draw()

        # Load the test data
        sentences, x, belonging = self.process_test_data()
        x_kanji, x_cxn = resolve(x)

        # Load the model
        self.hermes.info("Load the model.bin.hades...")
        model.load_weights(self.conf.model_path.format("hades"))
        self.hermes.info("Load the model.bin.hades...Finished!")

        # Make the predictions
        predictions = model.predict([x_kanji, x_cxn])
        predictions = npy.argmax(predictions, axis=-1)

        self.hermes.info("Begin to predict...")

        results, count = [], 0
        for prediction in tqdm(predictions, desc="Predict"):
            sentence = sentences[count]
            len_of_sentence = get_length(sentence)
            prediction = prediction[-len_of_sentence:]

            labels = [self.conf.labels[row] for row in prediction]

            result = []
            for i in range(0, len_of_sentence):
                result.append((sentence[i], labels[i]))

            construction = belonging["".join(sentence)]
            results.append((construction, result))

            count += 1

        self.hermes.info("Begin to predict...Finished!")

        return results

    def write(self, results):
        self.hermes.info("Begin to write the annotation...")

        output = {}
        for construction, result in results:
            if construction not in output.keys():
                output[construction] = []

            output[construction].append(txt_to_xml(result))

        # Write the data to output file
        today = datetime.date.today().__format__('%Y_%m_%d')
        for construction, sentences in tqdm(output.items(),
                                            desc="Output the predictions"):
            with open(self.conf.output.format("hades", today, construction),
                      "w") as fp:
                fp.write("<?xml version='1.0' encoding='UTF-8'?>" + "\r\n")
                fp.write("<document>" + "\r\n")

                for sentence in sentences:
                    fp.write("\t" + sentence + "\r\n")

                fp.write("</document>")

            fp.close()

        self.hermes.info("Begin to write the annotation...Finished!")
Exemple #14
0
 def test_get_damage(self):
     self.assertEqual(Sword('Sw1', 10, 0.5).get_damage(), 5)
     self.assertEqual(Sword('Sw2', 100, 0.7).get_damage(), 70)
     self.assertEqual(Sword('Sw3', 40, 0.3).get_damage(), 12)
Exemple #15
0
def main():
    args = usage()
    context = {}
    if args.configure:
        with codecs.open(args.configure, 'r', encoding='utf-8') as conf:
            context = json.load(conf)

    if args.project_name:
        context["ProjectName"] = args.project_name
    if args.package:
        context["Package"] = args.package
    if not "Seed" in context:
        context["Seed"] = ""

    templateDir = args.template if args.template else "Templates"
    targetDir = args.target if args.target else "."

    if not os.path.exists(targetDir):
        Sword.mkdir(targetDir)

    sword = Sword()
    sword.registryFunction("randomPassword", RandomPassword)
    sword.registryFunction("randomSecret", RandomSecret)
    print("Begin to render directory \"" + templateDir + "\" to \"" +
          targetDir + "\"")
    file_lists = os.listdir(templateDir)
    for items in file_lists:
        path = os.path.join(templateDir, items)
        tarPath = os.path.join(targetDir, items)
        if os.path.isfile(path):
            try:
                target = sword.renderLine(tarPath, context)
                sword.renderFile(path, target, context)
            except KeyError as err:
                print("Parse key error: " + str(err) + ", file name: \" " +
                      path + "\"")
        else:
            if not os.path.exists(tarPath):
                os.mkdir(tarPath)
            if not items in DIRECT_COPY:
                sword.renderDir(path, tarPath, context)
            else:
                print("Copy directory \"" + path + "\" to \"" + tarPath + "\"")
                Sword.copyDir(path, tarPath)
    print("End of render!")
Exemple #16
0
def startGame(screen, map_selection, skin_selection1, skin_selection2, audio):
    paused = False
    resetMetaData(p1_meta_info)
    resetMetaData(p2_meta_info)
    current_map = mapSelectionList.selectMap(
        map_selection)  # returns a child of the map class

    entities = current_map.getCollidableEntities()
    left_wall = Rect(-20, 0, 20, 1000)
    right_wall = Rect(-20, 0, 20, 1000)

    swords = []

    player1 = Player(current_map.getP1InitialPosition()["X"],
                     current_map.getP1InitialPosition()["Y"], 1, 2, False,
                     True, getSkin(skin_selection1),
                     1)  # Initializes player1 -50, 100
    player2 = Player(current_map.getP2InitialPosition()["X"],
                     current_map.getP2InitialPosition()["Y"], 1, 2, False,
                     False, getSkin(skin_selection2),
                     -1)  # Initializes player2 675, 100

    display, camera = gameFrame.init(current_map)

    clock = pygame.time.Clock()

    active_match = True

    audio.changeSong(current_map.songName)
    leftover = 0
    while active_match:
        # Delta time is implemented to help make sure that player's models will move at the same speed regardless of monitor refresh rate and processor speed.
        # Could use further optimizing and troubleshooting.

        Millisec_Goal = .0166

        timer = time()
        for event in pygame.event.get():
            # What to do on quit
            if event.type == pygame.QUIT:
                audio.closeAudioEngine()
                pygame.mixer.quit()
                pygame.quit()
                sys.exit()

            # Pressed a key so perform said action
            if event.type == pygame.KEYDOWN:

                if player1.getPlayerState(
                        "ghost_counter"
                ) == -1 or player1.getPlayerState("ghost_counter") > 150:
                    if event.key == pygame.K_d:
                        adjustPlayer(1, "right", True)
                    elif event.key == pygame.K_a:
                        adjustPlayer(1, "left", True)
                    if event.key == pygame.K_SPACE:
                        adjustPlayer(1, "up", True)
                    if event.key == pygame.K_s:
                        if player1.getPlayerState("sword_height") == 1:
                            player1.setPlayerState("ducking", True)
                        adjustPlayer(1, "sword_movement", -1)
                        player1.setPlayerState("sword_moving", True)
                    elif event.key == pygame.K_w:
                        adjustPlayer(1, "sword_movement", 1)
                        player1.setPlayerState("sword_moving", True)
                    else:
                        player1.setPlayerState("sword_moving", False)
                    if event.key == pygame.K_f:
                        adjustPlayer(1, "attack_count", 30)
                if player2.getPlayerState(
                        "ghost_counter"
                ) == -1 or player2.getPlayerState("ghost_counter") > 150:
                    if event.key == pygame.K_LEFT:
                        adjustPlayer(2, "left", True)
                    elif event.key == pygame.K_RIGHT:
                        adjustPlayer(2, "right", True)
                    if event.key == pygame.K_RSHIFT:
                        adjustPlayer(2, "up", True)
                    if event.key == pygame.K_DOWN:
                        if player2.getPlayerState("sword_height") == 1:
                            player2.setPlayerState("ducking", True)
                        adjustPlayer(2, "sword_movement", -1)
                        player2.setPlayerState("sword_moving", True)
                    elif event.key == pygame.K_UP:
                        adjustPlayer(2, "sword_movement", 1)
                        player2.setPlayerState("sword_moving", True)
                    else:
                        player2.setPlayerState("sword_moving", False)
                    if event.key == pygame.K_RCTRL:
                        adjustPlayer(2, "attack_count", 30)
                        player2.setPlayerState("attacking", True)
                if event.key == pygame.K_ESCAPE:
                    mainMenuFrame.pauseMenu(screen, p1_meta_info, p2_meta_info,
                                            audio)

            # Let go of key so stop performing said action
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d:
                    adjustPlayer(1, "right", False)
                elif event.key == pygame.K_a:
                    adjustPlayer(1, "left", False)
                if event.key == pygame.K_SPACE:
                    adjustPlayer(1, "up", False)
                if event.key == pygame.K_s:
                    player1.setPlayerState("ducking", False)
                if event.key == pygame.K_LEFT:
                    adjustPlayer(2, "left", False)
                elif event.key == pygame.K_RIGHT:
                    adjustPlayer(2, "right", False)
                if event.key == pygame.K_RSHIFT:
                    adjustPlayer(2, "up", False)
                if event.key == pygame.K_DOWN:
                    player2.setPlayerState("ducking", False)

        # NON EVENT BASED ACTIONS
        # Player 1 Sprite/Movement
        player1.setPlayerState("running", False)
        player2.setPlayerState("running", False)

        if p1_meta_info["attack_count"] > 0:
            player1.setPlayerState("thrusting", True)
            p1_meta_info["attack_count"] -= 1
        else:
            player1.setPlayerState("thrusting", False)
            if p1_meta_info["sword_movement"] != 0:
                player1.adjustSwordHeight(p1_meta_info["sword_movement"])
                p1_meta_info["sword_movement"] = 0

        if player1.rect.x > player2.rect.x:
            player1.setDirection("left")
        else:
            player1.setDirection("right")

        if p1_meta_info["left"]:
            player1.moveLeft()
        elif p1_meta_info["right"]:
            player1.moveRight()
        elif player1.getPlayerState("x_velocity") != 0:
            player1.standingStill()
        if p1_meta_info["up"] and player1.getPlayerState("on_ground") and (
                player1.getPlayerState("ghost_counter") > 150
                or player1.getPlayerState("ghost_counter") == -1):
            player1.jump(time())
        elif not player1.getPlayerState("on_ground"):
            player1.calculateGravity(time())

        # Player 2 Sprite/Movement

        if p2_meta_info["attack_count"] > 0:
            player2.setPlayerState("thrusting", True)
            p2_meta_info["attack_count"] -= 1
        else:
            player2.setPlayerState("thrusting", False)
            if p2_meta_info["sword_movement"] != 0:
                player2.adjustSwordHeight(p2_meta_info["sword_movement"])
                p2_meta_info["sword_movement"] = 0

        if player2.rect.x > player1.rect.x:
            player2.setDirection("left")
        else:
            player2.setDirection("right")

        if p2_meta_info["left"]:
            player2.moveLeft()
        elif p2_meta_info["right"]:
            player2.moveRight()
        elif player2.getPlayerState("x_velocity") != 0:
            player2.standingStill()
        if p2_meta_info["up"] and player2.getPlayerState("on_ground") and (
                player2.getPlayerState("ghost_counter") > 150
                or player2.getPlayerState("ghost_counter") == -1):
            player2.jump(time())
        elif not player2.getPlayerState("on_ground"):
            player2.calculateGravity(time())

        #Collision stuffs
        if player1.getPlayerState(
                "ghost_counter") > 150 or player1.getPlayerState(
                    "ghost_counter") == -1:
            if player1.getPlayerState("ducking") == False:
                player1body = Rect(player1.rect.x + 127, player1.rect.y - 16,
                                   15, 140)
            else:
                player1body = Rect(player1.rect.x + 127, player1.rect.y + 54,
                                   15, 70)
        else:
            player1body = Rect(-100, -100, 1, 1)

        if player2.getPlayerState(
                "ghost_counter") > 150 or player2.getPlayerState(
                    "ghost_counter") == -1:
            if player2.getPlayerState("ducking") == False:
                player2body = Rect(player2.rect.x + 127, player2.rect.y - 16,
                                   15, 140)
            else:
                player2body = Rect(player2.rect.x + 127, player2.rect.y + 54,
                                   15, 70)
        else:
            player2body = Rect(-100, -100, 1, 1)

        while getSwordLine(player1).colliderect(getSwordLine(player2)):
            player1.setPlayerState("x_velocity", 0)
            player2.setPlayerState("x_velocity", 0)
            if player1.getPlayerState(
                    "sword_moving") and player2.getPlayerState("thrusting"):
                player2.setPlayerState("sword", False)
                swordInfo = getSwordDisarm(player2)
                swords.append(
                    Sword(swordInfo[0], swordInfo[1], 0,
                          player2.getPlayerState("direction_facing")))
            elif player2.getPlayerState(
                    "sword_moving") and player1.getPlayerState("thrusting"):
                player1.setPlayerState("sword", False)
                swordInfo = getSwordDisarm(player1)
                swords.append(
                    Sword(swordInfo[0], swordInfo[1], 0,
                          player1.getPlayerState("direction_facing")))
            else:
                if player1.getDirection() == "left":
                    player1.moveRight()
                    player2.moveLeft()
                    player1.move(entities, camera)
                    player2.move(entities, camera)
                else:
                    player1.moveLeft()
                    player2.moveRight()
                    player1.move(entities, camera)
                    player2.move(entities, camera)
        else:
            if player1body.colliderect(
                    getSwordLine(player2)) and player2body.colliderect(
                        getSwordLine(player1)):
                player1.setPlayerState("ghost_counter", 0)
                player2.setPlayerState("ghost_counter", 0)
                camera.setActive(False)

                #screen locked in place
            elif player1body.colliderect(getSwordLine(player2)):
                player1.setPlayerState(
                    "ghost_counter", 0
                )  #Should start a counter for each frame of death animation, followed by a respawn delay, followed by drawing them as a ghost in that spot
                player2.setPlayerState("ghost_counter", -1)
                player2.setPlayerState("ghost", False)
                camera.setActive(True)
                camera.setTarget(player2)
                player1.setPlayerState("sword", True)

                #screen follows player 2
            elif player2body.colliderect(getSwordLine(player1)):
                print("player 2 had an ouchie")
                player2.setPlayerState(
                    "ghost_counter", 0
                )  #Should start a counter for each frame of death animation, followed by a respawn delay, followed by drawing them as a ghost in that spot
                player1.setPlayerState("ghost_counter", -1)
                player1.setPlayerState("ghost", False)
                camera.setActive(True)
                camera.setTarget(player1)
                player2.setPlayerState("sword", True)
                #screen follows player 1

        #sword pickups
        if player1.getPlayerState(
                "ducking") and not player1.getPlayerState("sword"):
            for sword in swords:
                if player1body.colliderect(sword.rect):
                    player1.setPlayerState("sword", True)
                    swords.remove(sword)
        if player2.getPlayerState(
                "ducking") and not player2.getPlayerState("sword"):
            for sword in swords:
                if player2body.colliderect(sword.rect):
                    player2.setPlayerState("sword", True)
                    swords.remove(sword)

        #Just died
        if player1.getPlayerState("ghost_counter") == 0:
            player1.setPlayerState("ducking", False)
        if player2.getPlayerState("ghost_counter") == 0:
            player2.setPlayerState("ducking", False)

        if player1.getPlayerState("ghost_counter") > -1:
            #print("woooooowie")
            player1.setPlayerState("ghost_counter",
                                   player1.getPlayerState("ghost_counter") + 1)
        if player2.getPlayerState("ghost_counter") > -1:
            #print("woooooowie 2")
            player2.setPlayerState("ghost_counter",
                                   player2.getPlayerState("ghost_counter") + 1)
        if player1.getPlayerState("ghost_counter") == 150:
            #print("woooooowie")
            player1.respawn(player2.getXPos(), player2.getYPos())
        if player2.getPlayerState("ghost_counter") == 150:
            #print("woooooowie 2")
            player2.respawn(player1.getXPos(), player1.getYPos())
        if player1.getPlayerState("ghost_counter") == 151:
            player1.setPlayerState("ignore_gravity", True)
        if player2.getPlayerState("ghost_counter") == 151:
            player2.setPlayerState("ignore_gravity", True)
        if player1.getPlayerState(
                "ghost_counter") == 175 or player1.getPlayerState(
                    "ghost_counter") == -1:
            player1.setPlayerState("ignore_gravity", False)
        if player2.getPlayerState(
                "ghost_counter") == 175 or player2.getPlayerState(
                    "ghost_counter") == -1:
            player2.setPlayerState("ignore_gravity", False)

        for sword in swords:
            if not sword.getState("on_ground"):
                sword.calculateGravity(time())
            sword.move(entities)

        player1.move(entities, camera)
        player2.move(entities, camera)
        #print(player2.getPlayerState("ignore_gravity"))

        shotClock = time() - timer
        # while shotClock - leftover >= Millisec_Goal:
        #     for sword in swords:
        #         if not sword.getState("on_ground"):
        #             sword.calculateGravity(time())
        #         sword.move(entities)
        #     player1.move(entities, camera)
        #     player2.move(entities, camera)
        #     leftover = shotClock % Millisec_Goal
        #     shotClock -= Millisec_Goal
        while shotClock < Millisec_Goal:
            shotClock = time() - timer
        timer = time()
        #render
        gameFrame.render(display, screen, player1, player2, entities, camera,
                         swords, current_map.assets_dict)
        if player1.getPlayerState("player_won") or player2.getPlayerState(
                "player_won"):
            break

    if player1.getPlayerState("player_won"):
        mainMenuFrame.endGameMenu(screen, audio, 1)
    elif player2.getPlayerState("player_won"):
        mainMenuFrame.endGameMenu(screen, audio, 2)


#if player1.getPlayerState("ghost_counter") >= 0 and player1.getPlayerState("ghost_counter") < 11:
class TestSword(unittest.TestCase):
    """ Unit Tests for the Sword Class """

    # create the sword objects
    def setUp(self) -> None:
        self.test_sword_1 = Sword("Skull Cleaver", "iron", True, True, 0.91,
                                  3.1, False)
        self.test_sword_2 = Sword("Dawn Splitter", "wood", False, False, 0.82,
                                  2.7, True)

    def tearDown(self) -> None:
        self.test_sword_1 = None
        self.test_sword_2 = None

    def test_sword(self):
        """ 001 - Test the constructor """
        self.assertIsNotNone(self.test_sword_1)
        self.assertIsNotNone(self.test_sword_2)

    def test_sword_invalid_parameters(self):
        """ 002 - Invalid Construction Parameters """

        # 002A - Must reject an undefined Weapon name
        self.assertRaisesRegex(ValueError, "Weapon name cannot be undefined.",
                               Sword, None, "iron", False, True, 0.82, 2.7,
                               True)

        # 002B - Must reject an empty Weapon name
        self.assertRaisesRegex(ValueError, "Weapon name cannot be empty.",
                               Sword, "", "iron", False, True, 0.82, 2.7, True)

        # 002C - Must reject a non-string Weapon name
        self.assertRaisesRegex(ValueError,
                               "Weapon name should be a string value.", Sword,
                               99, "iron", False, True, 0.82, 2.7, True)

        # 002D - Must reject an undefined Weapon materials
        self.assertRaisesRegex(ValueError,
                               "Weapon materials cannot be undefined.", Sword,
                               "Skull Cleaver", None, False, True, 0.82, 2.7,
                               True)

        # 002E - Must reject an empty Weapon materials
        self.assertRaisesRegex(ValueError, "Weapon materials cannot be empty.",
                               Sword, "Skull Cleaver", "", False, True, 0.82,
                               2.7, True)

        # 002F - Must reject a non-string Weapon materials
        self.assertRaisesRegex(ValueError,
                               "Weapon materials should be a string value.",
                               Sword, "Armsel Striker", 99, False, True, 0.82,
                               2.7, True)

        # 002G - Must reject an undefined Weapon is_cold_weapon
        self.assertRaisesRegex(ValueError,
                               "Weapon is_cold_weapon cannot be undefined.",
                               Sword, "Skull Cleaver", "iron", None, True,
                               0.82, 2.7, True)

        # 002H - Must reject a non-boolean Weapon is_cold_weapon
        self.assertRaisesRegex(
            ValueError, "Weapon is_cold_weapon should be a boolean value.",
            Sword, "Skull Cleaver", "iron", "False", True, 0.82, 2.7, True)

        # 002I - Must reject an undefined Weapon is_inuse
        self.assertRaisesRegex(ValueError,
                               "Weapon is_inuse cannot be undefined.", Sword,
                               "Skull Cleaver", "iron", False, None, 0.82, 2.7,
                               True)

        # 002J - Must reject a non-boolean Weapon is_inuse
        self.assertRaisesRegex(ValueError,
                               "Weapon is_inuse should be a boolean value.",
                               Sword, "Skull Cleaver", "iron", False, "True",
                               0.82, 2.7, True)

        # 002K - Must reject an undefined Sword sharp
        self.assertRaisesRegex(ValueError, "Sword sharp cannot be undefined.",
                               Sword, "Skull Cleaver", "iron", False, True,
                               None, 2.7, True)

        # 002L - Must reject a non-float Sword sharp
        self.assertRaisesRegex(ValueError,
                               "Sword sharp should be a float value.", Sword,
                               "Skull Cleaver", "iron", False, True, "0.82",
                               2.7, True)

        # 002M - Must reject an undefined Sword length
        self.assertRaisesRegex(ValueError, "Sword length cannot be undefined.",
                               Sword, "Skull Cleaver", "iron", False, True,
                               0.82, None, True)

        # 002N - Must reject a non-float Sword length
        self.assertRaisesRegex(ValueError,
                               "Sword length should be a float value.", Sword,
                               "Skull Cleaver", "iron", False, True, 0.82,
                               "2.7", True)

        # 002O - Must reject a undefined Sword is_double_edged
        self.assertRaisesRegex(ValueError,
                               "Sword is_double_edged cannot be undefined.",
                               Sword, "Skull Cleaver", "iron", False, True,
                               0.82, 2.7, None)

        # 002P - Must reject a non-boolean Sword is_double_edged
        self.assertRaisesRegex(
            ValueError, "Sword is_double_edged should be a boolean value.",
            Sword, "Skull Cleaver", "iron", False, True, 0.82, 2.7, "True")

    def test_get_sharp(self):
        """ 003 - Test the get_sharp method """

        # should show up 0.91 if the sword's sharp is 0.91
        self.assertEqual(self.test_sword_1.get_sharp(), 0.91)

    def test_get_double_edged(self):
        """ 004 - Test the get_double_edged method """

        # False - should show up false since sword_1's is a single edged sword
        self.assertFalse(self.test_sword_1.get_double_edged())

    def test_get_length(self):
        """ 005 - Test the get_length method """

        # should show up 3.1 if the sword's length is 3.1
        self.assertEqual(self.test_sword_1.get_length(), 3.1)

    def test_get_type(self):
        """ 006 - Test the get_type method """

        # 006A - Should return 'Sword' string
        self.assertEqual(self.test_sword_1.get_type(), "Sword")

    def test_to_dict(self):
        """ 007 - Test the to_dict method """

        test_sword = {
            "id": 0,
            "name": "Skull Cleaver",
            "materials": "iron",
            "is_cold_weapon": True,
            "is_inuse": True,
            "sharp": 0.91,
            "length": 3.1,
            "is_double_edged": False,
            "type": "Sword"
        }

        # 007A - should return a dictionary same as the test_sword
        self.assertEqual(self.test_sword_1.to_dict(), test_sword)
Exemple #18
0
def extract_and_load(dirc):
    sword = Sword(dirc)
    # pap = PeerAssessPro(dirc)
    LoadToStaging(sword).load_to_warehouse()
Exemple #19
0
 def swingSword(self, evt):
     if evt.key == pygame.K_w:
         sword = Sword('up', self.player.rect.centerx,
                       self.player.rect.centery - 10)
         sword.swing(0, 1)
         self.sword_count = 5
         self.sword_list.add(sword)
     elif evt.key == pygame.K_a:
         sword = Sword('left', self.player.rect.centerx - 12,
                       self.player.rect.centery)
         sword.swing(-1, 0)
         self.sword_count = 5
         self.sword_list.add(sword)
     elif evt.key == pygame.K_s:
         sword = Sword('down', self.player.rect.centerx,
                       self.player.rect.centery + 6)
         sword.swing(0, -1)
         self.sword_count = 5
         self.sword_list.add(sword)
     elif evt.key == pygame.K_d:
         sword = Sword('right', self.player.rect.centerx + 6,
                       self.player.rect.centery)
         sword.swing(1, 0)
         self.sword_count = 5
         self.sword_list.add(sword)
Exemple #20
0
                        text="Iniciar el juego",
                        command=lambda: startGame())
startButton.place(x=(width / 2 - 45), y=25)

#espada = Espada()

print("--------------------")
print("Creando Caballero")
hero = Knight("Rhys", 50, 100)
hero.details()
#hero.equipment()

print("--------------------")

print("\nCreando Espada")
heroSword = Sword("Storm Song", 1, 11, 100)

print("Equipando espada ...")
hero.equip(heroSword)

print("\nCreando Arco")
heroBow = Bow("Armatus", 4, 7, 70)
print("Equipando arco ...")
hero.equip(heroBow)

print("\nCreando Escudo")
heroShield = Shield("Aegis", 10, 10)
print("Equipando escudo ...")
hero.equip(heroShield)

print("--------------------")
Exemple #21
0
class Player(Character):
    def __init__(self, world, x, y, width, height, speed=5):
        super().__init__(world, x, y, width, height)
        self.world = world
        self.health = 10
        self.image = pygame.image.load('assets/chessman-knight.png')
        self.my_sword = Sword('Excalibur', 10, 'assets/Small_Sword_icon.png',
                              self.x - 18, self.y + 14)
        self.speed = speed
        self.attacking = False

    def update(self):  # moves the Player
        event = pygame.event.poll()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                self.y -= self.speed
                self.my_sword.update_y(-self.speed)
            if event.key == pygame.K_s:
                self.y += self.speed
                self.my_sword.update_y(+self.speed)
            if event.key == pygame.K_a:
                self.x -= self.speed
                self.my_sword.update_x(-self.speed)
            if event.key == pygame.K_d:
                self.x += self.speed
                self.my_sword.update_x(+self.speed)
            if event.key == pygame.K_e:
                # Allow 1 attack per key pressed
                if self.attacking is False:
                    self.attack()
                    self.attacking = True

        elif event.type == pygame.KEYUP:
            if self.attacking:
                self.release()
                self.attacking = False

        self.check_boundary()

    def attack(self):
        self_right_side = self.x + self.width + 25
        self_left_side = self.x + self.width
        self_top_side = self.y
        self_bottom_side = self.height + self.y
        self.my_sword.attack()

        for enemy in self.world.enemy_list:
            if self.is_touching_rectangle(right=self_right_side,
                                          left=self_left_side,
                                          top=self_top_side,
                                          bottom=self_bottom_side,
                                          other_character=enemy):
                enemy.died()

    def release(self):
        self.my_sword.release()

    def draw(self, world_surface):
        world_surface.blit(self.image, (self.x, self.y))
        self.draw_health(0, 0)
        pygame.display.flip()
        self.my_sword.draw(world_surface)
 def setUp(self) -> None:
     self.test_sword_1 = Sword("Skull Cleaver", "iron", True, True, 0.91,
                               3.1, False)
     self.test_sword_2 = Sword("Dawn Splitter", "wood", False, False, 0.82,
                               2.7, True)
Exemple #23
0
 def test_getter(self):
     sw = Sword('Bow', 0, 0)
     self.assertTrue(sw.name == 'Bow')
     self.assertTrue(sw.damage == 0)
     self.assertTrue(sw.durability == 0)
def swing_sword(sk_settings, screen, knight, sword_container):
	'''Function to create sword hit box next to knight.'''
	sk_settings.sword_swinging = True
	sword = Sword(sk_settings, screen, knight)
	sword_container.add(sword)
Exemple #25
0
 def test_le(self):
     b = Sword(damage=20)
     self.assertEqual(self.sword <= b, True)