From 04caa32ee7b557c18ff0f06c2595aff6e0ef32fe Mon Sep 17 00:00:00 2001 From: javierdastas <43615461+javierdastas@users.noreply.github.com> Date: Fri, 6 Dec 2024 09:30:48 -0400 Subject: [PATCH 1/2] Update Vikings Mini Project Update Vikings Mini Project on Week 1 Day 5. Required challenge for the Week. --- .../1-testsSoldier-checkpoint.py | 48 +++ .../3-testsSaxons-checkpoint.py | 57 +++ .ipynb_checkpoints/4-testsWar-checkpoint.py | 130 +++++++ .ipynb_checkpoints/README-checkpoint.md | 337 ++++++++++++++++++ .ipynb_checkpoints/file-checkpoint.py | 71 ++++ .../vikingsClasses-checkpoint.py | 186 ++++++++++ .ipynb_checkpoints/wargame-checkpoint.py | 27 ++ 3-testsSaxons.py | 8 +- __pycache__/vikingsClasses.cpython-312.pyc | Bin 0 -> 7662 bytes file.py | 71 ++++ vikingsClasses.py | 178 +++++++-- 11 files changed, 1085 insertions(+), 28 deletions(-) create mode 100644 .ipynb_checkpoints/1-testsSoldier-checkpoint.py create mode 100644 .ipynb_checkpoints/3-testsSaxons-checkpoint.py create mode 100644 .ipynb_checkpoints/4-testsWar-checkpoint.py create mode 100644 .ipynb_checkpoints/README-checkpoint.md create mode 100644 .ipynb_checkpoints/file-checkpoint.py create mode 100644 .ipynb_checkpoints/vikingsClasses-checkpoint.py create mode 100644 .ipynb_checkpoints/wargame-checkpoint.py create mode 100644 __pycache__/vikingsClasses.cpython-312.pyc create mode 100644 file.py diff --git a/.ipynb_checkpoints/1-testsSoldier-checkpoint.py b/.ipynb_checkpoints/1-testsSoldier-checkpoint.py new file mode 100644 index 0000000..ab6095a --- /dev/null +++ b/.ipynb_checkpoints/1-testsSoldier-checkpoint.py @@ -0,0 +1,48 @@ +import unittest +from vikingsClasses import Soldier +from inspect import signature + + +class TestSoldier(unittest.TestCase): + + @classmethod + def setUp(cls): + cls.strength = 150 + cls.health = 300 + cls.soldier = Soldier(cls.health, cls.strength) + + def testConstructorSignature(self): + self.assertEqual(len(signature(Soldier).parameters), 2) + + def testHealth(self): + self.assertEqual(self.soldier.health, self.health) + + def testStrength(self): + self.assertEqual(self.soldier.strength, self.strength) + + def testAttackShouldBeFunction(self): + self.assertEqual(callable(self.soldier.attack), True) + + def testAttackHasNoParams(self): + self.assertEqual(len(signature(self.soldier.attack).parameters), 0) + + def testAttackRetunsStrength(self): + self.assertEqual(self.soldier.attack(), self.strength) + + def testReceivesDamage(self): + self.assertEqual(callable(self.soldier.receiveDamage), True) + + def testReceivesDamageHasParams(self): + self.assertEqual( + len(signature(self.soldier.receiveDamage).parameters), 1) + + def testReceiveDamageReturnNone(self): + self.assertEqual(self.soldier.receiveDamage(50), None) + + def testCanReceiveDamage(self): + self.soldier.receiveDamage(50) + self.assertEqual(self.soldier.health, self.health - 50) + + +if __name__ == '__main__': + unittest.main() diff --git a/.ipynb_checkpoints/3-testsSaxons-checkpoint.py b/.ipynb_checkpoints/3-testsSaxons-checkpoint.py new file mode 100644 index 0000000..b7c58f7 --- /dev/null +++ b/.ipynb_checkpoints/3-testsSaxons-checkpoint.py @@ -0,0 +1,57 @@ +import unittest +from vikingsClasses import Saxon +from inspect import signature + + +class TestSaxon(unittest.TestCase): + + @classmethod + def setUp(cls): + cls.health = 60 + cls.strength = 25 + cls.saxon = Saxon(cls.health, cls.strength) + + def testSaxonShouldReceiveTwoParams(self): + self.assertEqual(len(signature(Saxon).parameters), 2) + + def testHealth(self): + self.assertEqual(self.saxon.health, self.health) + + def testStrength(self): + self.assertEqual(self.saxon.strength, self.strength) + + def testAttack(self): + self.assertEqual(callable(self.saxon.attack), True) + + def testAttackShouldReceiveNoParams(self): + self.assertEqual(len(signature(self.saxon.attack).parameters), 0) + + def testAttackREturnStrength(self): + self.assertEqual(self.saxon.attack(), self.strength) + + def testReceiveDamageIsFunction(self): + self.assertEqual(callable(self.saxon.receiveDamage), True) + + def testReceiveDamageShouldReceiveOneParam(self): + self.assertEqual( + len(signature(self.saxon.receiveDamage).parameters), 1) + + def testReceiveDamage(self): + self.saxon.receiveDamage(1) + self.assertEqual(self.saxon.health, self.health - 1) + + def testReceiveDamageString45(self): + self.assertEqual(self.saxon.receiveDamage( + 45), 'A Saxon has received 45 points of damage') + + def testReceiveDamageString10(self): + self.assertEqual(self.saxon.receiveDamage( + 10), 'A Saxon has received 10 points of damage') + + def testReceiveDamageStringDied(self): + self.assertEqual(self.saxon.receiveDamage(self.health), + 'A Saxon has died in combat') + + +if __name__ == '__main__': + unittest.main() diff --git a/.ipynb_checkpoints/4-testsWar-checkpoint.py b/.ipynb_checkpoints/4-testsWar-checkpoint.py new file mode 100644 index 0000000..cebe317 --- /dev/null +++ b/.ipynb_checkpoints/4-testsWar-checkpoint.py @@ -0,0 +1,130 @@ +import unittest +from vikingsClasses import War, Viking, Saxon +from inspect import signature + + +class TestWar(unittest.TestCase): + + @classmethod + def setUp(cls): + cls.war = War() + + def testWarShouldReciveNoParams(self): + self.assertEqual(len(signature(War).parameters), 0) + + def testVikingArmy(self): + self.assertEqual(self.war.vikingArmy, []) + + def testSaxonArmy(self): + self.assertEqual(self.war.saxonArmy, []) + + +class TestWar2(unittest.TestCase): + @classmethod + def setUp(cls): + def generateViking(): + cls.name = 'Harald' + cls.strength = 150 + cls.health = 300 + return Viking(cls.name, cls.health, cls.strength) + + def generateSaxon(): + cls.health = 60 + cls.strength = 25 + return Saxon(cls.health, cls.strength) + + cls.viking = generateViking() + cls.saxon = generateSaxon() + cls.war = War() + cls.war.addSaxon(cls.saxon) + cls.war.addViking(cls.viking) + + def testAddViking(self): + self.assertEqual(callable(self.war.addViking), True) + + def testAddVikingShouldReceiveOneParam(self): + self.assertEqual(len(signature(self.war.addViking).parameters), 1) + + def testAddVikingInList(self): + self.assertEqual(self.war.vikingArmy, [self.viking]) + + def testAddVikingReturnNull(self): + self.assertEqual(self.war.addViking(self.viking), None) + + def testAddSaxonShouldBeFunction(self): + self.assertEqual(callable(self.war.addSaxon), True) + + def testAddSaxonReceiveOneParam(self): + self.assertEqual(len(signature(self.war.addSaxon).parameters), 1) + + def testSaxonArmyReturnEmptyList(self): + self.assertEqual(self.war.saxonArmy, [self.saxon]) + + def testAddSaxonReturnNone(self): + self.assertEqual(self.war.addSaxon(self.saxon), None) + + def testVikingAttackIsFunction(self): + self.assertEqual(callable(self.war.vikingAttack), True) + + def testVikingAttackReceiveNoParam(self): + self.assertEqual(len(signature(self.war.vikingAttack).parameters), 0) + + def testSaxonHealth(self): + oldHealt = self.saxon.health + self.war.vikingAttack() + self.assertEqual(self.saxon.health, oldHealt - self.viking.strength) + + def testVikingAttack(self): + self.war.vikingAttack() + self.assertEqual(len(self.war.saxonArmy), 0) + + def testAddSaxon(self): + print(self.war.__dict__) + self.assertEqual(self.war.vikingAttack(), 'A Saxon has died in combat') + + def testSaxonAttackIsFunction(self): + self.assertEqual(callable(self.war.saxonAttack), True) + + def testSaxonAttackReceiveNoParam(self): + self.assertEqual(len(signature(self.war.saxonAttack).parameters), 0) + + def testVikingHealth(self): + oldHealt = self.viking.health + self.war.saxonAttack() + self.assertEqual(self.viking.health, oldHealt - self.saxon.strength) + + def testVikingArmyList(self): + for i in range(12): + if(len(self.war.vikingArmy) == 0): + break + self.war.saxonAttack() + self.assertEqual(len(self.war.vikingArmy), 0) + + def testReturnOfSaxonAttack(self): + self.assertEqual(self.war.saxonAttack(), self.viking.name + + ' has received ' + str(self.saxon.strength) + ' points of damage') + + def testShowStatusShouldIsFunction(self): + self.assertEqual(callable(self.war.showStatus), True) + + def testShowStatusReceiveNoParams(self): + self.assertEqual(len(signature(self.war.showStatus).parameters), 0) + + def testShouldReturnStringVikingsWon(self): + self.war.vikingAttack() + self.assertEqual(self.war.showStatus(), + 'Vikings have won the war of the century!') + + def testShouldReturnStringSaxonsWon(self): + for i in range(12): + self.war.saxonAttack() + self.assertEqual(self.war.showStatus( + ), 'Saxons have fought for their lives and survive another day...') + + def testShouldReturnStringStillFighting(self): + self.assertEqual( + self.war.showStatus(), 'Vikings and Saxons are still in the thick of battle.') + + +if __name__ == '__main__': + unittest.main() diff --git a/.ipynb_checkpoints/README-checkpoint.md b/.ipynb_checkpoints/README-checkpoint.md new file mode 100644 index 0000000..12e42ec --- /dev/null +++ b/.ipynb_checkpoints/README-checkpoint.md @@ -0,0 +1,337 @@ +![logo_ironhack_blue 7](https://user-images.githubusercontent.com/23629340/40541063-a07a0a8a-601a-11e8-91b5-2f13e4e6b441.png) + +# Mini Project | Vikings + +## Introduction + +The Vikings and the Saxons are at War. Both are Soldiers but they have their own methods to fight. Vikings are ported to Python. YAY!! + +In this laboratory you will work with the concept of inheritance in Python. + +### Getting Started + +You will find the following files in the folder of this laboratory: + +- `vikingsClasses.py` +- `1-testSoldier.py` +- `2-testVikings.py` +- `3-testSaxons.py` +- `4-testWar.py` + +You are free to use any of the code editors you have to open these files. + +### Challenge Question + +Modify the file `vikingsClasses.py` so that all the tests are correct. + +## Submission + +- Modify `vikingsClasses.py` and save your changes. + +## Tests + +Best way to know how our code is doing is to work with tests. You will test the `vikingsClases.py` file step by step. + +You will **only** be **editing** the vikingsClasses.py. The files you will **running** to test your code are the following: 1-testsSoldier.py, 2-testsVikings.py, 3-testsSaxons.py & 4-testsWar.py, depending on how far you have written your code. + +So, let's say you have already created the class for Soldiers. + +1. You wrote your code +2. Make sure you save the changes in your editor +3. In your terminal, run the test file for that class + +```bash +$ python3 1-testsSoldier.py --v +``` + +### Correct Test + +When the tests are all correct you will receive the following message in the terminal. + +``` +$ python3 1-testsSoldier.py --v + +testAttackHasNoParams (__main__.TestSoldier) ... ok +testAttackRetunsStrength (__main__.TestSoldier) ... ok +testAttackShouldBeFunction (__main__.TestSoldier) ... ok +testCanReceiveDamage (__main__.TestSoldier) ... ok +testConstructorSignature (__main__.TestSoldier) ... ok +testHealth (__main__.TestSoldier) ... ok +testReceiveDamageReturnNone (__main__.TestSoldier) ... ok +testReceivesDamage (__main__.TestSoldier) ... ok +testReceivesDamageHasParams (__main__.TestSoldier) ... ok +testStrength (__main__.TestSoldier) ... ok + +---------------------------------------------------------------------- +Ran 10 tests in 0.001s + +OK +``` + +### Failed Test + +When any test is incorrect you will receive the following message in the terminal. It means that you must keep making changes in the `vikingsClasses.py` file. + +``` +$ python3 1-testsSoldier.py --v + +testAttackHasNoParams (__main__.TestSoldier) ... ok +testAttackRetunsStrength (__main__.TestSoldier) ... ok +testAttackShouldBeFunction (__main__.TestSoldier) ... ok +testCanReceiveDamage (__main__.TestSoldier) ... FAIL +testConstructorSignature (__main__.TestSoldier) ... ok +testHealth (__main__.TestSoldier) ... ok +testReceiveDamageReturnNone (__main__.TestSoldier) ... ok +testReceivesDamage (__main__.TestSoldier) ... ok +testReceivesDamageHasParams (__main__.TestSoldier) ... ok +testStrength (__main__.TestSoldier) ... ok + +====================================================================== +FAIL: testCanReceiveDamage (__main__.TestSoldier) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "1-testsSoldier.py", line 44, in testCanReceiveDamage + self.assertEqual(self.soldier.health, self.health + 50) +AssertionError: 250 != 350 + +---------------------------------------------------------------------- +Ran 10 tests in 0.001s +``` + +## Exercise + +![](https://i.imgur.com/5TPElt8.jpg) + +--- + +**Write the code** + +Now we have to write the correct code in the `vikingsClasses.py` file to make the test pass. The starter code you will find in the file is the following: + +``` +# Soldier +class Soldier: + +# Viking +class Viking: + +# Saxon +class Saxon: + +# War +class War: +``` + +In this case, the test says that _Soldier constructor function should receive 2 arguments (health & strength)_, so we have to write the correct code that passes this test. Let's make the `Soldier` constructor function receive two arguments: + +``` +# Soldier +class Soldier: + def __init__(self, health, strength): + # add code here + +# Viking +class Viking: + +# Saxon +class Saxon: + +# War +class War: + +``` + +### Soldier + +Modify the `Soldier` constructor function and add 2 methods to its prototype: `attack()`, and `receiveDamage()`. + +#### constructor function + +- should receive **2 arguments** (health & strength) +- should receive the **`health` property** as its **1st argument** +- should receive the **`strength` property** as its **2nd argument** + +#### `attack()` method + +- should be a function +- should receive **0 arguments** +- should return **the `strength` property of the `Soldier`** + +#### `receiveDamage()` method + +- should be a function +- should receive **1 argument** (the damage) +- should remove the received damage from the `health` property +- **shouldn't return** anything + +--- + +### Viking + +A `Viking` is a `Soldier` with an additional property, their `name`. They also have a different `receiveDamage()` method and new method, `battleCry()`. + +Modify the `Viking` constructor function, have it inherit from `Soldier`, reimplement the `receiveDamage()` method for `Viking`, and add a new `battleCry()` method. + +#### inheritance + +- `Viking` should inherit from `Soldier` + +#### constructor function + +- should receive **3 arguments** (name, health & strength) +- should receive the **`name` property** as its **1st argument** +- should receive the **`health` property** as its **2nd argument** +- should receive the **`strength` property** as its **3rd argument** + +#### `attack()` method + +(This method should be **inherited** from `Soldier`, no need to reimplement it.) + +- should be a function +- should receive **0 arguments** +- should return **the `strength` property of the `Viking`** + +#### `receiveDamage()` method + +(This method needs to be **reimplemented** for `Viking` because the `Viking` version needs to have different return values.) + +- should be a function +- should receive **1 argument** (the damage) +- should remove the received damage from the `health` property +- **if the `Viking` is still alive**, it should return **"NAME has received DAMAGE points of damage"** +- **if the `Viking` dies**, it should return **"NAME has died in act of combat"** + +#### `battleCry()` method + +[Learn more about battle cries](http://www.artofmanliness.com/2015/06/08/battle-cries/). + +- should be a function +- should receive **0 arguments** +- should return **"Odin Owns You All!"** + +--- + +### Saxon + +A `Saxon` is a weaker kind of `Soldier`. Unlike a `Viking`, a `Saxon` has no name. Their `receiveDamage()` method will also be different than the original `Soldier` version. + +Modify the `Saxon`, constructor function, have it inherit from `Soldier` and reimplement the `receiveDamage()` method for `Saxon`. + +#### inheritance + +- `Saxon` should inherit from `Soldier` + +#### constructor function + +- should receive **2 arguments** (health & strength) +- should receive the **`health` property** as its **1st argument** +- should receive the **`strength` property** as its **2nd argument** + +#### `attack()` method + +(This method should be **inherited** from `Soldier`, no need to reimplement it.) + +- should be a function +- should receive **0 arguments** +- should return **the `strength` property of the `Saxon`** + +#### `receiveDamage()` method + +(This method needs to be **reimplemented** for `Saxon` because the `Saxon` version needs to have different return values.) + +- should be a function +- should receive **1 argument** (the damage) +- should remove the received damage from the `health` property +- **if the Saxon is still alive**, it should return _**"A Saxon has received DAMAGE points of damage"**_ +- **if the Saxon dies**, it should return _**"A Saxon has died in combat"**_ + +--- + +### War + +Now we get to the good stuff: WAR! Our `War` constructor function will allow us to have a `Viking` army and a `Saxon` army that battle each other. + +Modify the `War` constructor and add 5 methods to its prototype: + +- `addViking()` +- `addSaxon()` +- `vikingAttack()` +- `saxonAttack()` +- `showStatus()` + +#### constructor function + +When we first create a `War`, the armies should be empty. We will add soldiers to the armies later. + +- should receive **0 arguments** +- should assign an empty array to the **`vikingArmy` property** +- should assign an empty array to the **`saxonArmy` property** + +#### `addViking()` method + +Adds 1 `Viking` to the `vikingArmy`. If you want a 10 `Viking` army, you need to call this 10 times. + +- should be a function +- should receive **1 argument** (a `Viking` object) +- should add the received `Viking` to the army +- **shouldn't return** anything + +#### `addSaxon()` method + +The `Saxon` version of `addViking()`. + +- should be a function +- should receive **1 argument** (a `Saxon` object) +- should add the received `Saxon` to the army +- **shouldn't return** anything + +#### `vikingAttack()` method + +A `Saxon` (chosen at random) has their `receiveDamage()` method called with the damage equal to the `strength` of a `Viking` (also chosen at random). This should only perform a single attack and the `Saxon` doesn't get to attack back. + +- should be a function +- should receive **0 arguments** +- should make a `Saxon` `receiveDamage()` equal to the `strength` of a `Viking` +- should remove dead saxons from the army +- should return **result of calling `receiveDamage()` of a `Saxon`** with the `strength` of a `Viking` + +#### `saxonAttack()` method + +The `Saxon` version of `vikingAttack()`. A `Viking` receives the damage equal to the `strength` of a `Saxon`. + +- should be a function +- should receive **0 arguments** +- should make a `Viking` `receiveDamage()` equal to the `strength` of a `Saxon` +- should remove dead vikings from the army +- should return **result of calling `receiveDamage()` of a `Viking`** with the `strength` of a `Saxon` + +#### `showStatus()` method + +Returns the current status of the `War` based on the size of the armies. + +- should be a function +- should receive **0 arguments** +- **if the `Saxon` array is empty**, should return _**"Vikings have won the war of the century!"**_ +- **if the `Viking` array is empty**, should return _**"Saxons have fought for their lives and survive another day..."**_ +- **if there are at least 1 `Viking` and 1 `Saxon`**, should return _**"Vikings and Saxons are still in the thick of battle."**_ + + +## BONUS + +Create a game using the classes you defined. For this, you will need to: +- Create a new `file.py` +- Import the classes you defined earlier +- Define functions to create the workflow of the game: i.e. functions to create teams (maybe you can create random teams with your classmates' names), run the game, etc. + +## Deliverables + +- REQUIRED: `vikingsClases.py` modified with your solution to the challenge question. + +## Resources + +- https://docs.python.org/3/library/unittest.html +- https://www.python-course.eu/python3_inheritance.php + +## Additional Challenge for the Nerds + +You can try to make your own tests for your code by creating another test file. diff --git a/.ipynb_checkpoints/file-checkpoint.py b/.ipynb_checkpoints/file-checkpoint.py new file mode 100644 index 0000000..b5d060d --- /dev/null +++ b/.ipynb_checkpoints/file-checkpoint.py @@ -0,0 +1,71 @@ +# With a correction already implemented: dont forget to initialize an instance of Class "War" + + +from vikingsClasses import Soldier, Viking, Saxon, War +import random + + +valhalla_war = War() + +#Create Vikings Army +def create_vikings_army(vikings): + """ + Initialize the Saxon Army List. + Args: + vikings (str list): a list of possible vikings names. + """ + for viking in vikings: + valhalla_war.addViking( Viking(viking, 100, random.randint(0,100)) ) + +#Create Saxons Army +def create_saxons_army(army_size): + """ + Initialize the Saxon Army List. + Args: + army_size (int): the Saxon Army size, same as Vinkings Army size + """ + for i in range(0, army_size): + valhalla_war.addSaxon( Saxon( 100,random.randint(0,100) ) ) + +def setup_game(): + """ + Initialize the Vinking's and Saxon's Armies + Args: + no arguments + """ + vikings_names = ["Ragnar","Olaf","Bjorn","Ivar the Boneless", "Gerard","Lagertha","Torvi","Floki"] + random.shuffle(vikings_names) # shuffle the vinkings names + + army_size = len(vikings_names) + + create_vikings_army(vikings_names) + create_saxons_army(army_size) + +def start_war(): + """ + Run all necessary functions for the war. + Args: + no arguments + """ + battle_round = 0 + while valhalla_war.showStatus() == "Vikings and Saxons are still in the thick of battle.": + valhalla_war.vikingAttack() + valhalla_war.saxonAttack() + print(f"Round {battle_round}: Viking army: {len(valhalla_war.vikingArmy)} warriors",end=' ') + print(f"and Saxon army: {len(valhalla_war.saxonArmy)} warriors") + print(f" {valhalla_war.showStatus()}") + battle_round += 1 + +def main(): + """ + The main function or caller for the program. + Args: + no arguments + """ + setup_game() # setup all variables and list + print("\n¡Let's The War Begin!") + start_war() # game simulation AI + +# Call the Main Funtion +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/.ipynb_checkpoints/vikingsClasses-checkpoint.py b/.ipynb_checkpoints/vikingsClasses-checkpoint.py new file mode 100644 index 0000000..cab79f9 --- /dev/null +++ b/.ipynb_checkpoints/vikingsClasses-checkpoint.py @@ -0,0 +1,186 @@ +import random + +# Soldier +class Soldier: + def __init__(self, health, strength): + """ + Initialize Soldier properties. + Args: + healt (int): soldier health + strength (int): soldier strength + """ + self.health = health + self.strength = strength + + def attack(self): + """ + Returns the Soldier's Strength. + Args: + no arguments + """ + return self.strength + + def receiveDamage(self, damage): + """ + Set Soldier received damage. + Args: + damage (int): receive damage by the soldier + """ + self.health -= damage + + +# Viking Class - inheritance from Soldier +class Viking(Soldier): + def __init__(self, name, health, strength): + """ + Initialize the viking soldier properties. + Args: + name (str): viking name + healt (int): soldier health + strength (int): soldier strength + """ + super().__init__(health, strength) #taking the things from PARENT class + self.name = name + + def battleCry(self): + """ + Return the Viking Yahl Message. + Args: + no arguments + Return: + string + """ + return "Odin Owns You All!" + + def receiveDamage(self, damage): + """ + Return the Viking Yahl Message. + Args: + damage (int): damage received by the viking + Return: + string message + """ + super().receiveDamage( damage ) + if self.health > 0: + return f"{self.name} has received {damage} points of damage" + else: + return f"{self.name} has died in act of combat" + +# Saxon Class - inheritance from Soldier +class Saxon(Soldier): + def __init__(self, health, strength): + """ + Initialize the saxon soldier properties. + Args: + healt (int): soldier health + strength (int): soldier strength + """ + super().__init__(health, strength) #taking the things from PARENT class + + def receiveDamage(self, damage): + """ + Return the Saxon battle message. + Args: + damage (int): damage received by the viking + Return: + string message + """ + super().receiveDamage( damage ) + if self.health > 0: + return f"A Saxon has received {damage} points of damage" + else: + return f"A Saxon has died in combat" + +# Davicente +class War(): + def __init__(self): + """ + Initialize the War armies + vikingArmy (Viking): list of Vikings + saxonArmy (Saxon): list of Saxons + Args: + no arguments + """ + self.vikingArmy = [] + self.saxonArmy = [] + + def addViking(self, viking): + """ + Add Vikings to Viking Army List + Args: + viking (object): viking object (name, health, strength) + """ + self.vikingArmy.append(viking) + + def addSaxon(self, saxon): + """ + Add Saxon to Saxon Army List + Args: + saxon (object): saxon object (health, strength) + """ + self.saxonArmy.append(saxon) + + def vikingAttack(self): + """ + Realize a Viking Attack + Args: + no arguments + Returns: + string (str): Saxon Army status and/or Saxon soldier damage status (Viking or Saxon) + """ + if not self.saxonArmy: + return self.showStatus() + elif not self.vikingArmy: + return "Viking Army not have soldiers!" # Optional: for testing + else: + # Randon selection for the Saxon and the Viking + saxon = random.randint(0, len(self.saxonArmy) - 1) + viking = random.randint(0, len(self.vikingArmy) - 1) + + # attack the Saxon + attack_result_msg = self.saxonArmy[saxon].receiveDamage( self.vikingArmy[viking].attack()) + + # Remove the Saxon from the Saxon Army if die + if self.saxonArmy[saxon].health <= 0: + self.saxonArmy.pop(saxon) + return attack_result_msg + + def saxonAttack(self): + """ + Realize a Saxon Attack + Args: + no arguments + Returns: + string (str): Viking Army status and/or Viking soldier damage status (Viking or Saxon) + """ + if not self.vikingArmy: + return self.showStatus() # No more vikings + elif not self.saxonArmy: + return "Saxon Army not have soldiers!" # Optional: for testing + else: + # Randon selection for the Saxon and the Viking + saxon = random.randint(0, len(self.saxonArmy) - 1) + viking = random.randint(0, len(self.vikingArmy) - 1) + + # attack the Viking + attack_result_msg = self.vikingArmy[viking].receiveDamage(self.saxonArmy[saxon].attack()) + + # Remove the Viking from the Viking Army if die + if self.vikingArmy[viking].health <= 0: + self.vikingArmy.pop(viking) + return attack_result_msg + + def showStatus(self): + """ + Return the Army Status + Args: + no arguments + Returns: + string (str): Army status (Viking or Saxon) + """ + if not self.saxonArmy: + return "Vikings have won the war of the century!" + elif not self.vikingArmy: + return "Saxons have fought for their lives and survive another day..." + elif self.vikingArmy and self.saxonArmy: + return "Vikings and Saxons are still in the thick of battle." \ No newline at end of file diff --git a/.ipynb_checkpoints/wargame-checkpoint.py b/.ipynb_checkpoints/wargame-checkpoint.py new file mode 100644 index 0000000..31a2adb --- /dev/null +++ b/.ipynb_checkpoints/wargame-checkpoint.py @@ -0,0 +1,27 @@ +# With a correction already implemented: dont forget to initialize an instance of Class "War" + + +from .vikingsClasses import Soldier, Viking, Saxon, War +import random + + +soldier_names = ["albert","andres","archie","dani", "david","gerard","german","graham","imanol","laura"] +great_war = War() + +#Create 5 Vikings +for i in range(0,5): + if i: + great_war.addViking(Viking(soldier_names[random.randint(0,9)],100,random.randint(0,100))) + +#Create 5 Saxons +for i in range(0,5): + if i: + great_war.addSaxon(Saxon(100,random.randint(0,100))) + +round = 0 +while great_war.showStatus() == "Vikings and Saxons are still in the thick of battle.": + great_war.vikingAttack() + great_war.saxonAttack() + print(f"round: {round} // Viking army: {len(great_war.vikingArmy)} warriors",f"and Saxon army: {len(great_war.saxonArmy)} warriors") + print(great_war.showStatus()) + round += 1 \ No newline at end of file diff --git a/3-testsSaxons.py b/3-testsSaxons.py index b7c58f7..3ae16ae 100644 --- a/3-testsSaxons.py +++ b/3-testsSaxons.py @@ -53,5 +53,9 @@ def testReceiveDamageStringDied(self): 'A Saxon has died in combat') -if __name__ == '__main__': - unittest.main() +def main(): + print("¡T!") + +# Bloque condicional para ejecutar la función main +if __name__ == "__main__": + main() diff --git a/__pycache__/vikingsClasses.cpython-312.pyc b/__pycache__/vikingsClasses.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b4096e8069f672148d9f8d68f3f7dae5db97204 GIT binary patch literal 7662 zcmd5>TTGnC75@LdvB0vsn2T=#4-TNm(2W& z%?4l8S_)WA9nw}%Rgp-VDj=&$`j$theaJ&!c8x7o+df3QYYrbWR%87b!tR()*{(D=m0w+Tlnpu9*P>I zDH1aRM+g&p5}kv2e9WMFY`_>SWVQMwb9ca&b@5pTvu=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z#0CYAYa*4ha$K&j0)F7B%SbR1ifOHJYMPb#&|y7)m@Fpn6N@b%Hw zbis_|(9u(TlE_wym!=@qSt4o#N7w*EJwUf5o~Aqk>N>;&l^>BUx94qOW_N&ygs}S7 z)tgr{Rhwtpr`s2+8dILeOl8f?j`w$Ds=l}CQfju(bWeBB?f*DD-}q_ELd)W=mp<=E z?>fF%ePXin?=bqt^c!;>AG7%bpSCZwFYZ42c__WReX-``WY+_i((uA3-VeR=i8ML5 zL{6p2sXIUZGWbO>b>U*V^QTLl;dEzsu~T0p{V7i!u)}-V)v2qqdfL~xL8UGSrPjd|iZ6(ODH!0; zgGdlv=piJBk$fKs58)+>(3h|eW4i*FC}%uo6)53Dl*sA$HS*s9Vu8f9o7WxziTd~J zGgWO*10;MO`aW}|$>Al^nI@fgv@c^{#8MY}(_I&ry86;xeT!Y%BGDyCT${Q!JC^qC zTJklgea)X$-u1O1Ncg6GOaAB6{^#eq?)mqw2NDPvJn)D@W!=C70tj$(m}e9e2rba8 zii}WiamPs2ar?M~XSBb~QB?d#1%FQDQJruOa`@@_zC5?Lflo7snDAwn;9&!wmoGtn z1n*T?4a5J25_G&Fd7LY%$=DxH3=A5iAG{>rV* z6^Nz5+|3=A&h31rqViVoW^k_hllqT9k6(UZS9b23405m19VjiD9piko4aqSiCy;PE ztif7268!HF#iuGxFe_yZK=9uWrOxM;YhBLW%kb}q7nc2-fwTcxX{&IaQ^nW#A-sWe zi$?#!pTl_8E#}N$C+j{Y{xx!fo&;vpY=-9kz^ 0: + return f"{self.name} has received {damage} points of damage" + else: + return f"{self.name} has died in act of combat" + +# Saxon Class - inheritance from Soldier class Saxon(Soldier): def __init__(self, health, strength): - # your code here + """ + Initialize the saxon soldier properties. + Args: + healt (int): soldier health + strength (int): soldier strength + """ + super().__init__(health, strength) #taking the things from PARENT class def receiveDamage(self, damage): - # your code here + """ + Return the Saxon battle message. + Args: + damage (int): damage received by the viking + Return: + string message + """ + super().receiveDamage( damage ) + if self.health > 0: + return f"A Saxon has received {damage} points of damage" + else: + return f"A Saxon has died in combat" # Davicente - class War(): def __init__(self): - # your code here + """ + Initialize the War armies + vikingArmy (Viking): list of Vikings + saxonArmy (Saxon): list of Saxons + Args: + no arguments + """ + self.vikingArmy = [] + self.saxonArmy = [] def addViking(self, viking): - # your code here + """ + Add Vikings to Viking Army List + Args: + viking (object): viking object (name, health, strength) + """ + self.vikingArmy.append(viking) def addSaxon(self, saxon): - # your code here + """ + Add Saxon to Saxon Army List + Args: + saxon (object): saxon object (health, strength) + """ + self.saxonArmy.append(saxon) def vikingAttack(self): - # your code here + """ + Realize a Viking Attack + Args: + no arguments + Returns: + string (str): Saxon Army status and/or Saxon soldier damage status (Viking or Saxon) + """ + if not self.saxonArmy: + return self.showStatus() + elif not self.vikingArmy: + return "Viking Army not have soldiers!" # Optional: for testing + else: + # Randon selection for the Saxon and the Viking + saxon = random.randint(0, len(self.saxonArmy) - 1) + viking = random.randint(0, len(self.vikingArmy) - 1) + + # attack the Saxon + attack_result_msg = self.saxonArmy[saxon].receiveDamage( self.vikingArmy[viking].attack()) + + # Remove the Saxon from the Saxon Army if die + if self.saxonArmy[saxon].health <= 0: + self.saxonArmy.pop(saxon) + return attack_result_msg def saxonAttack(self): - # your code here + """ + Realize a Saxon Attack + Args: + no arguments + Returns: + string (str): Viking Army status and/or Viking soldier damage status (Viking or Saxon) + """ + if not self.vikingArmy: + return self.showStatus() # No more vikings + elif not self.saxonArmy: + return "Saxon Army not have soldiers!" # Optional: for testing + else: + # Randon selection for the Saxon and the Viking + saxon = random.randint(0, len(self.saxonArmy) - 1) + viking = random.randint(0, len(self.vikingArmy) - 1) + + # attack the Viking + attack_result_msg = self.vikingArmy[viking].receiveDamage(self.saxonArmy[saxon].attack()) + + # Remove the Viking from the Viking Army if die + if self.vikingArmy[viking].health <= 0: + self.vikingArmy.pop(viking) + return attack_result_msg def showStatus(self): - # your code here - pass - - + """ + Return the Army Status + Args: + no arguments + Returns: + string (str): Army status (Viking or Saxon) + """ + if not self.saxonArmy: + return "Vikings have won the war of the century!" + elif not self.vikingArmy: + return "Saxons have fought for their lives and survive another day..." + elif self.vikingArmy and self.saxonArmy: + return "Vikings and Saxons are still in the thick of battle." \ No newline at end of file From 37b2601800714927a6a3ae1dcec95a08b93c88e2 Mon Sep 17 00:00:00 2001 From: javierdastas <43615461+javierdastas@users.noreply.github.com> Date: Fri, 6 Dec 2024 11:24:26 -0400 Subject: [PATCH 2/2] Update the Vikings Challenge Update the Vikings Challenge, Week 1, Day 5. --- .../vikingsClasses-checkpoint.py | 23 ++++++++++-------- __pycache__/vikingsClasses.cpython-313.pyc | Bin 0 -> 6906 bytes vikingsClasses.py | 23 ++++++++++-------- 3 files changed, 26 insertions(+), 20 deletions(-) create mode 100644 __pycache__/vikingsClasses.cpython-313.pyc diff --git a/.ipynb_checkpoints/vikingsClasses-checkpoint.py b/.ipynb_checkpoints/vikingsClasses-checkpoint.py index cab79f9..655fd5e 100644 --- a/.ipynb_checkpoints/vikingsClasses-checkpoint.py +++ b/.ipynb_checkpoints/vikingsClasses-checkpoint.py @@ -134,15 +134,18 @@ def vikingAttack(self): return "Viking Army not have soldiers!" # Optional: for testing else: # Randon selection for the Saxon and the Viking - saxon = random.randint(0, len(self.saxonArmy) - 1) - viking = random.randint(0, len(self.vikingArmy) - 1) + # saxon = random.randrange(len(self.saxonArmy)) # random.choice( + # viking = random.randrange(len(self.vikingArmy)) + saxon = random.choice(self.saxonArmy) + viking = random.choice(self.vikingArmy) # attack the Saxon - attack_result_msg = self.saxonArmy[saxon].receiveDamage( self.vikingArmy[viking].attack()) + # attack_result_msg = self.saxonArmy[saxon].receiveDamage( self.vikingArmy[viking].attack()) + attack_result_msg = saxon.receiveDamage( viking.attack() ) # Remove the Saxon from the Saxon Army if die - if self.saxonArmy[saxon].health <= 0: - self.saxonArmy.pop(saxon) + if saxon.health <= 0: + self.saxonArmy.remove(saxon) return attack_result_msg def saxonAttack(self): @@ -159,15 +162,15 @@ def saxonAttack(self): return "Saxon Army not have soldiers!" # Optional: for testing else: # Randon selection for the Saxon and the Viking - saxon = random.randint(0, len(self.saxonArmy) - 1) - viking = random.randint(0, len(self.vikingArmy) - 1) + saxon = random.choice(self.saxonArmy) + viking = random.choice(self.vikingArmy) # attack the Viking - attack_result_msg = self.vikingArmy[viking].receiveDamage(self.saxonArmy[saxon].attack()) + attack_result_msg = viking.receiveDamage(saxon.attack()) # Remove the Viking from the Viking Army if die - if self.vikingArmy[viking].health <= 0: - self.vikingArmy.pop(viking) + if viking.health <= 0: + self.vikingArmy.remove(viking) return attack_result_msg def showStatus(self): diff --git a/__pycache__/vikingsClasses.cpython-313.pyc b/__pycache__/vikingsClasses.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4e8b5cc4745508571d4cff47646582988aafbcc GIT binary patch literal 6906 zcmdT|&2tpT74O+E&8}9f75d=Il3Q4SmVjhH5F!kOKn%tPQd-N#1$aE{4!dJkySRH+ z1jX2-D&>g8M23Wtj&d%*&6E%RCvuQVP;5`??-<(%1wo^ZaHUw8q;EpjSd5^5Bu zXvrOoz-&Te7ZR_PP0Q3v=9od99_d9^xo9xUG{}1cg*I^pZt;&9aplq+AXz zl|@m`EoPJpRxwz`)hABe4cRf#OVL(cZ6<6-xKTRKRG1!%gWx!K7|(vIf0!GL_vdwP z>Ae4NC089W$`P5=lV@nDHrwJg>5DM9Pb}7%jPzi`TIuB+BRxlFv|tL%_#Rf zpNC31=dhrQmu*$kpsuB9cG_8SpQ}M<;3*JS$>S7R-T7%_Z4JHNv;Z2C^DGA${1!G| z2Oqb{Fd2gXVCo?mWo%Dk$grxc%&ArMOuU)XtYa>}iOUtLvw~b@BBKa%+*KGlFUJun zYXoV>bjyNu+bMVYGT)5VoXICix^3dhwJS5~3k+2`$BE%nPFzgB4>CCUeadpvA6B*j zSa@j3eT2)rnaCQJ=PS&}8Rn>wr+IxuFBtySNR8_bPDQ64J$G5y!||iU30N(9Kqe$s zYsX|`j?<>jvYVVP4vUfOc6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