Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A JavaScript exercise to practice Object Oriented Programming

NotificationsYou must be signed in to change notification settings

Franmg94/lab-javascript-vikings

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

logo_ironhack_blue 7

LAB | JS Vikings

giphy

Learning Goals

This exercise allows you to practice and apply the concepts and techniques taught in class.

Upon completion of this exercise, you will be able to:

  • Run predefined tests in Jasmine to verify that the program meets the technical requirements.
  • Identify expected code behavior by reading and understanding test results and errors.
  • Define aclass and use it to create objects (instances).
  • Create a subclass that extends a parent class usingextends andsuper() to inherit properties and methods.
  • Define class methods that use thethis keyword to access object properties.
  • Add or remove items from an array using the array methods (push,pop,shift,unshift, andsplice).
  • Iterate over arrays using thefor andforEach loops.
  • Pass values as arguments to functions.
  • Use thereturn keyword to return a value from a function.


Introduction

We have learned Object-oriented programming and howclass and inheritance work in JavaScript. Now let's work with our Viking friends, applying the concepts we have just learned.


Requirements

  • Fork this repo.
  • Clone this repo.

Submission

  • Upon completion, run the following commands:
git add.git commit -m"Solved lab"git push origin master
  • Create a Pull Request so that your TAs can check your work.

Test Your Code

This LAB is equipped with unit tests to provide automated feedback on your lab progress. In case you want to check the tests, they are in thetests/viking.spec.js file.

To run the tests and your JavaScript code, open theSpecRunner.html file using theLive Server VSCode extension.

To see the outputs of theconsole.log in your JavaScript code, open theConsole in the Developer Tools.


Instructions

You will work on thesrc/viking.js file.

Your task is to write the correct code in thesrc/viking.js file to make the tests pass. In this file, you will find the following starter code:

// SoldierclassSoldier{}// VikingclassViking{}// SaxonclassSaxon{}// WarclassWar{}

Iteration 0: First test

Let's have a look at the first test case together to get you started.

The first test case says that "Soldier class >> should receive 2 arguments (health & strength)", so we have to write the correct code to pass this test. Let's make theSoldier class receive two arguments:

// SoldierclassSoldier{constructor(health,strength){}}// VikingclassViking{}// SaxonclassSaxon{}// WarclassWar{}

Iteration 1: Soldier

Modify theSoldier class and add 2 methods to it:attack(), andreceiveDamage().

class

  • should receive2 arguments (health & strength)
  • should receive thehealth property as its1st argument
  • should receive thestrength property as its2nd argument

attack() method

  • should be a function
  • should receive0 arguments
  • should returnthestrength property of theSoldier

receiveDamage() method

  • should be a function
  • should receive1 argument (the damage)
  • should remove the received damage from thehealth property
  • shouldn't return anything

Iteration 2: Viking

AViking is aSoldier with an additional property, theirname. They also have a differentreceiveDamage() method and a new method,battleCry().

Modify theViking class, have it inherit fromSoldier, re-implement thereceiveDamage() method forViking, and add a newbattleCry() method.

inheritance

  • Viking shouldextendSoldier

class

  • should receive3 arguments (name, health & strength)
  • should receive thename property as its1st argument
  • should receive thehealth property as its2nd argument
  • should receive thestrength property as its3rd argument

attack() method

(This method should beinherited fromSoldier, no need to re-implement it.)

  • should be a function
  • should receive0 arguments
  • should returnthestrength property of theViking

receiveDamage() method

This method needs to bere-implemented forViking because theViking version needs to have different return values.

  • should be a function
  • should receive1 argument (the damage)
  • should remove the received damage from thehealth property
  • if theViking is still alive, it should return"NAME has received DAMAGE points of damage"
  • if theViking dies, it should return"NAME has died in act of combat"

battleCry() method

Learn more about battle cries.

  • should be a function
  • should receive0 arguments
  • should return"Odin Owns You All!"

Iteration 3: Saxon

ASaxon is a weaker kind ofSoldier. Unlike aViking, aSaxon has no name. TheirreceiveDamage() method will also be different than the originalSoldier version.

Modify theSaxon, constructor function, have it inherit fromSoldier and re-implement thereceiveDamage() method forSaxon.

inheritance

  • Saxon should extendSoldier

class

  • You don't have to include a constructor method since this class will inherit perfectly from the parents class, both the health and the strength (itextends Soldier class 😉 )

attack() method

This method should beinherited fromSoldier, no need to re-implement it.

  • should be a function
  • should receive0 arguments
  • should returnthestrength property of theSaxon

receiveDamage() method

This method needs to bere-implemented forSaxon because theSaxon version needs to have different return values.

  • should be a function
  • should receive1 argument (the damage)
  • should remove the received damage from thehealth 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"

BONUS - Iteration 4: War

Now we get to the good stuff: WAR! OurWar class will allow us to have aViking army and aSaxon army that battle each other.

Modify theWar class and add 5 methods to itsclass:

  • addViking()
  • addSaxon()
  • vikingAttack()
  • saxonAttack()
  • showStatus()

class

When we first create aWar, the armies should be empty. We will add soldiers to the armies later.

  • should receive0 arguments
  • should assign an empty array to thevikingArmy property
  • should assign an empty array to thesaxonArmy property

addViking() method

Adds 1Viking to thevikingArmy. If you want a 10Viking army, you need to call this 10 times.

  • should be a function
  • should receive1 argument (aViking object)
  • should add the receivedViking to the army
  • shouldn't return anything

addSaxon() method

TheSaxon version ofaddViking().

  • should be a function
  • should receive1 argument (aSaxon object)
  • should add the receivedSaxon to the army
  • shouldn't return anything

vikingAttack() method

ASaxon (chosen at random) has theirreceiveDamage() method called with the damage equal to thestrength of aViking (also chosen at random). This should only perform a single attack and theSaxon doesn't get to attack back.

  • should be a function
  • should receive0 arguments
  • should make aSaxonreceiveDamage() equal to thestrength of aViking
  • should remove dead Saxons from the army
  • should returnresult of callingreceiveDamage() of aSaxon with thestrength of aViking

saxonAttack() method

TheSaxon version ofvikingAttack(). AViking receives damage equal to thestrength of aSaxon.

  • should be a function
  • should receive0 arguments
  • should make aVikingreceiveDamage() equal to thestrength of aSaxon
  • should remove dead Vikings from the army
  • should returnresult of callingreceiveDamage() of aViking with thestrength of aSaxon

BONUS - Iteration 5

Since there is a lot of repetitive code in the previous two iterations, methodsvikingAttack() andsaxonAttack(), try to create onegeneric method and call it in the case ofvikingAttack and in the case ofsaxonAttack instead of using almost the same code for both methods. (This iteration doesn't have the test, so ask your TAs and your instructor to give you feedback on the quality of your code after the refactor.)

showStatus() method

Returns the current status of theWar based on the size of the armies.

  • should be a function
  • should receive0 arguments
  • if theSaxon array is empty, should return"Vikings have won the war of the century!"
  • if theViking array is empty, should return"Saxons have fought for their lives and survived another day..."
  • if there are at least 1Viking and 1Saxon, should return"Vikings and Saxons are still in the thick of battle."

Happy Coding! ❤️


FAQs


I am stuck in the exercise and don't know how to solve the problem or where to start.

If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear question about the specific issue you are facing. This will help you narrow down the problem and come up with potential solutions.

For example, is it a concept that you don't understand, or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources.

Once you have a clear understanding of the problem, you will be able to start working toward the solution.

Back to top

All of the Jasmine tests are failing and in red. Why did this happen?

One possible reason why all of the Jasmine tests are failing is that there is a syntax error in the code being tested. If the code contains a syntax error, it will not be loaded properly and none of the tests will be able to run. This will cause all of the tests to fail.

To troubleshoot this issue, you will need to examine the code being tested for syntax errors. Look for missing brackets, semicolons, or other syntax issues that could be causing the problem. If you find a syntax error, correct it and try running the tests again.

Another possibility is that there is an issue with the tests. It is possible that you may have modified the test file and caused an issue. If you have made changes to the test file, try copying and pasting the original test file and running the tests again to see if this resolves the issue.

Back to top

How do I loop over an array using theforEach() method?

TheforEach() method executes a provided function once for each array element. It does not return a new array but rather executes the function on each element in the array.

The syntax of theforEach() method is as follows:

array.forEach(function(element){// code to be executed for each element});

Here is an example that uses theforEach() method to log each element and its index in an array to the console:

constfruits=['apple','banana','cherry'];fruits.forEach(function(element,index){console.log(`${index}:${element}`);});

You can also use an arrow function as the callback function forforEach():

fruits.forEach((element,index)=>{console.log(`${index}:${element}`);});

Back to top

How do I remove an element from an array?

You should use thesplice() method to remove an array element at a specified index. Thesplice() method modifies the original array and returns an array containing the removed elements.

Syntax:

array.splice(start,deleteCount,item1,item2, ...)
  • start: The index of the first element to be removed.
  • deleteCount: The number of elements to be removed.
  • item1, item2, ...: (optional) The elements to add to the array, starting at thestart index.

For example, to remove an array element at index2 (which is"c"):

letnumbers=["a","b","c","d","e"];// Remove 1 element starting at index 2 (removes "c")letremoved=numbers.splice(2,1);console.log(numbers);// Output: ["a", "b", "d", "e"]console.log(removed);// Output: ["c"]

For more information, check:MDN: splice()

Back to top

How can I extend a class and reuse methods through inheritance?

In JavaScript, you can use theextends keyword to create asubclass that extends asuperclass (also called a base class).

The subclass inherits methods and properties from the superclass and can also have its own methods and properties.

Here is an example of extending a class and reusing its methods in #"auto" data-snippet-clipboard-copy-content="class Dog { constructor (name) { this.name = name; } bark() { console.log(`${this.name} is barking.`); }}class Labradoodle extends Dog { constructor (name, color) { super(name); this.color = color; }}const dog1 = new Labradoodle("Daisy", "white");dog1.bark(); // Output: "Daisy is barking."">

classDog{constructor(name){this.name=name;}bark(){console.log(`${this.name} is barking.`);}}classLabradoodleextendsDog{constructor(name,color){super(name);this.color=color;}}constdog1=newLabradoodle("Daisy","white");dog1.bark();// Output: "Daisy is barking."

In this example, theLabradoodle classextends theDog class and inherits thename property and thebark() method. TheLabradoodle class also defines its own propertycolor.

When thebark() method is called on thedog1 object, it uses the methodbark() coming from theDog class, because theLabradoodle class extends theDog class and inherits its methods and properties.

Back to top

I am unable to push changes to the repository. What should I do?

There are a couple of possible reasons why you may be unable topush changes to a Git repository:

  1. You have not committed your changes: Before you can push your changes to the repository, you need to commit them using thegit commit command. Make sure you have committed your changes and try pushing again. To do this, run the following terminal commands from the project folder:
git add.git commit -m"Your commit message"git push
  1. You do not have permission to push to the repository: If you have cloned the repository directly from the main Ironhack repository without making aFork first, you do not have write access to the repository.To check which remote repository you have cloned, run the following terminal command from the project folder:
git remote -v

If the link shown is the same as the main Ironhack repository, you will need to fork the repository to your GitHub account first and then clone your fork to your local machine to be able to push the changes.

Note: You should make a copy of your local code to avoid losing it in the process.

Back to top

About

A JavaScript exercise to practice Object Oriented Programming

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript99.7%
  • HTML0.3%

[8]ページ先頭

©2009-2025 Movatter.jp