Advertisement
gogio8

03. P!rates

Mar 24th, 2023
8
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.95 KB | None | 0 0
  1. function thePirates(input){
  2. let sailHasPassed = 0;
  3. function createCity(cityName, population, gold){
  4. let city = {
  5. name: cityName,
  6. population: population,
  7. gold: gold,
  8. plunder(town, people, gold){
  9. let buffPeople = this.population - people;
  10. let buffGold = this.gold - gold;
  11. if (buffGold <= 0 || buffPeople <= 0 || buffGold <= 0 && buffPeople <= 0){
  12. console.log(`${town} plundered! ${gold} gold stolen, ${people} citizens killed.`);
  13. console.log(`${town} has been wiped off the map!`);
  14. map.delete(this.name);
  15. } else {
  16. this.population -= people;
  17. this.gold -= gold;
  18. console.log(`${town} plundered! ${gold} gold stolen, ${people} citizens killed.`);
  19. }
  20. },
  21. propser(town, gold){
  22. if (gold < 0){
  23. console.log("Gold added cannot be a negative number!");
  24. } else {
  25. this.gold += gold;
  26. console.log(`${gold} gold added to the city treasury. ${town} now has ${this.gold} gold.`);
  27. }
  28. },
  29.  
  30. }
  31. return city;
  32. }
  33. let indexOfSail = input.indexOf('Sail');
  34. let indexOFEnd = input.indexOf('End');
  35. let map = new Map();
  36.  
  37. for (let i = 0; i < indexOfSail; i++){
  38. let tokens= input[i].split('||');
  39. let cityName = tokens[0];
  40. let population = Number(tokens[1]);
  41. let gold = Number(tokens[2]);
  42. let city = createCity(cityName, population, gold);
  43. if (map.has(cityName)){
  44. let city = map.get(cityName);
  45. city.population += population;
  46. city.gold += gold;
  47. } else{
  48. map.set(cityName, city);
  49. }
  50.  
  51. }
  52.  
  53. for (let i = indexOfSail + 1; i <= indexOFEnd; i++){
  54. let tokens = input[i].split('=>');
  55. let command = tokens.shift();
  56. let name = tokens.shift();
  57. let values = tokens;
  58.  
  59. switch(command){
  60. case 'Plunder':{
  61. let city = map.get(name);
  62. let people = Number(values[0]);
  63. let gold = Number(values[1]);
  64. city.plunder(name, people, gold);
  65. break;
  66. }
  67. case 'Prosper':{
  68. let city = map.get(name);
  69. let gold = Number(values);
  70. city.propser(name, gold);
  71. break;
  72. }
  73. case 'End':
  74. console.log(`Ahoy, Captain! There are ${map.size} wealthy settlements to go to: `);
  75. for(let city of map){
  76. console.log(`${city[1].name} -> Population: ${city[1].population} citizens, Gold: ${city[1].gold} kg`)
  77. }
  78. break;
  79. }
  80. }
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement