Печать статуса consloge.log()

#javascript

#javascript

Вопрос:

Я работаю над назначением javascript:

Напишите себе виртуальную кошку — животные с CLI намного приятнее, чем животные с мехом.

Создайте объект, представляющий cat. У него должны быть свойства усталости, голода, одиночества и счастья. Затем напишите методы, которые увеличивают и уменьшают эти свойства. Назовите их чем-то, что на самом деле представляет то, что увеличит или уменьшит эти вещи, например «feed», «sleep» или «pet». Наконец, напишите метод, который выводит статус cat в каждой области. (Проявите творческий подход, например, Paws действительно голоден, Paws ОЧЕНЬ счастлив.)

Итак, в моей последней строке кода я хочу проверить, могу ли я распечатать статус и посмотреть, какой ответ я получу, но не думаю, что мой последний consol.log() верен. Кто-нибудь может мне помочь? Кроме того, как вы думаете, есть ли какие-либо ошибки в этом коде или способ, которым я могу его сократить?

  class Paws {
 constructor() {
 this.tiredness = 0;
 this.hunger = 0;
 this.loneliness = 0;
 this.happiness = 0;
 }

play(tirednessVal, lonelinessVal, hungerVal) {
this.tiredness  = tirednessVal;
this.loneliness -= lonelinessVal;
this.hunger  = hungerVal;
 }
sleep(tirednessVal, lonelinessVal) {
this.tiredness -= tirednessVal;
this.loneliness  = lonelinessVal;
}

eat(hungerVal, happinessVal) {
this.hunger -= hungerVal;
this.happiness  = happinessVal;
}

getAngry(happinessVal) {
  this.happiness -= happinessVal;
}

printStatus() {
 const isTired = "The cat is very tired";
 const isNotTired = "The cat is not tired";
 const isHungry = "The cat is very hungry";
 const isNotHungry = "The cat is not hungry";
 const isLonely = "The cat is very lonely";
 const isNotLonely = "The cat is not lonely";
 const isHappy = "The cat is super happy";
 const isNotHappy = "The cat is not happy";

if (this.tiredness > 10) {
  console.log(isTired);
} else {
  console.log(isNotTired);
}
if (this.hunger > 10) {
  console.log(isHungry);
} else {
  console.log(isNotHungry);
}
if (this.loneliness > 10) {
  console.log(isLonely);
} else {
  console.log(isNotLonely);
}
if (this._happiness > 10) {
  console.log(isHappy);
} else {
  console.log(isNotHappy);
 }
 }

pet() {
  if (this.happiness < 5) {
   console.log("Meow. Don't touch me!");
  } else {
    meow();
  }
}   
 meow() {
  console.log("Moew. Pet me more");
 }

 console.log(Paws.tiredness(4));
 

Ответ №1:

интересное задание. вот мой

  class Cat {
   constructor(name, tiredness = 0, hunger = 10, loneliness = 10, happiness = 0) {
     this.name = name;
     this.tiredness = tiredness;
     this.hunger = hunger;
     this.loneliness = loneliness;
     this.happiness = happiness;
   }
   normalizeValue(val) {
    if (val < 0) {
        return 0;
    }
    if (val > 10) {
        return 10;
    }
    return val;
   }
   play(val = 1) {
     this.loneliness = this.normalizeValue(this.loneliness - val);
     this.happiness = this.normalizeValue(this.happiness   val);
   }
   feed(val = 1) {
     this.hunger = this.normalizeValue(this.hunger - val);
   }
   pet(val = 1) {
     this.loneliness = this.normalizeValue(this.loneliness - val);
   }
   sleep(val = 1) {
     this.tiredness = this.normalizeValue(this.tiredness - val);
   }
   getStatus() {
     return {
       tired: this.tiredness > 5,
       hungry: this.hunger > 5,
       lonely: this.loneliness > 5,
       happy: this.happiness > 5
     }
   }
   toString() {
     const status = this.getStatus();

     return Object.keys(status).map(k => {
       const state = status[k] ? "is" : "is not";
       return `${this.name} ${state} ${k}`;
     }).join(". ")   ".";
   }
 }

 const paws = new Cat("paws");
 paws.play(6);
 paws.feed(8);
 console.log(paws.toString()); 

Комментарии:

1. это здорово! единственное, я обнаружил, что работает только paws.play. Как бы я изменил это, если бы я также хотел заставить работать paws.sleep , paws.pet и paws.feed? Я поиграл, но не совсем понимаю, почему это не работает

2. можете ли вы подробнее рассказать о том, что не работает? вы получаете сообщение об ошибке? если вы добавите `paws.feed(6);`, то toString() напечатает «paws не голоден».

3. эй, да, так что, если вы изменили paws.feed, paws. значения sleep, paws.pet строка не изменится. так, например, если у нас есть paws.feed(8) или paws.feed(1) или paws.feed(12) и т. Д., Строка всегда выводит «paws голоден», и то же самое относится к paws.sleep. const paws = новый кот («лапы»); paws.play(6); paws.feed(2); paws.sleep(8) paws.pet(3) console.log(paws.toString()); //лапы не устали. лапы голодны. paws не одинок. paws доволен.

4. Я только что добавил `paws.feed (8);` в свое решение и консоль. журнал показывает «не голоден»

5. вы абсолютно правы, извините за это

Ответ №2:

вам необходимо создать экземпляр класса Paws. let paws = new Paws();

Ответ №3:

Много чего можно сказать об этом коде. Прежде всего, если вы помещаете аргументы в конструктор, вы можете определить начальные свойства cat, но это всего лишь деталь

     constructor(tiredness=0,hunger=0,loneliness=0,happiness=0) {
        this.tiredness = tiredness;
        this.hunger = hunger;
        this.loneliness = loneliness;
        this.happiness = happiness;
    }
 

и чтобы ответить на ваш вопрос, вы должны создать экземпляр объекта.

 const paws = new Paws({tiredness : 4});
paws.play(2,4,6)
paws.printStatus();
/*
The cat is not tired
The cat is not hungry
The cat is not lonely
The cat is not happy
*/
 

Ответ №4:

@KyleDePace уже ответил на это:

 let paws = new Paws();
console.log(paws.tiredness);
 

Как вы спрашивали о сокращении кода, в printStatus() вы можете использовать троичные операторы.

 class Paws {
 constructor() {
  this.tiredness = 0;
  this.hunger = 0;
  this.loneliness = 0;
  this.happiness = 0;
 }

 play(tirednessVal, lonelinessVal, hungerVal) {
  this.tiredness  = tirednessVal;
  this.loneliness -= lonelinessVal;
  this.hunger  = hungerVal;
 }

 sleep(tirednessVal, lonelinessVal) {
  this.tiredness -= tirednessVal;
  this.loneliness  = lonelinessVal;
 }

 eat(hungerVal, happinessVal) {
  this.hunger -= hungerVal;
  this.happiness  = happinessVal;
 }

 getAngry(happinessVal) {
  this.happiness -= happinessVal;
 }

 printStatus() {
  console.log(this.tiredness > 10 ? "The cat is very tired" : "The cat is not tired");
  console.log(this.hunger > 10 ? "The cat is very hungry" : "The cat is not hungry");
  console.log(this.loneliness > 10 ? "The cat is very lonely" : "The cat is not lonely");
  console.log(this._happiness > 10 ? "The cat is super happy" : "The cat is not happy");
 }

 pet() {
  if (this.happiness < 5)
   console.log("Meow. Don't touch me!");
  else
    meow();
 }   
 
 meow() {
  console.log("Moew. Pet me more");
 }
}
 

Ответ №5:

Тот, который вам нужен для создания объекта из вашего класса Paws с использованием new ключевого слова.

Но также для того, чтобы ваши методы работали в соответствии с логикой, для переменных класса должны быть значения, которые вы также можете указать при создании самого объекта.

 const paw = new Paws(6,7,9,8); 
 
 class Paws {
     constructor(tiredness,hunger,loneliness,happiness) {
       this.tiredness = tiredness;
       this.hunger = hunger;
       this.loneliness = loneliness;
       this.happiness = happiness;
      }

      play(tirednessVal, lonelinessVal, hungerVal) {
       this.tiredness  = tirednessVal;
       this.loneliness -= lonelinessVal;
       this.hunger  = hungerVal;
      }
  
      sleep(tirednessVal, lonelinessVal) {
      this.tiredness -= tirednessVal;
      this.loneliness  = lonelinessVal;
     }

      eat(hungerVal, happinessVal) {
      this.hunger -= hungerVal;
      this.happiness  = happinessVal;
     }

      getAngry(happinessVal) {
       this.happiness -= happinessVal;
     }

     printStatus() {
      const isTired = "The cat is very tired";
      const isNotTired = "The cat is not tired";
      const isHungry = "The cat is very hungry";
      const isNotHungry = "The cat is not hungry";
      const isLonely = "The cat is very lonely";
      const isNotLonely = "The cat is not lonely";
      const isHappy = "The cat is super happy";
      const isNotHappy = "The cat is not happy";

      if (this.tiredness > 10) {
        console.log(isTired);
      } else {
          console.log(isNotTired);
      }
  
      if (this.hunger > 10) {
        console.log(isHungry);
      } else {
       console.log(isNotHungry);
      }
  
      if (this.loneliness > 10) {
        console.log(isLonely);
      } else {
      console.log(isNotLonely);
     }
  
     if (this._happiness > 10) {
       console.log(isHappy);
     } else {
     console.log(isNotHappy);
     }
   }

     pet() {
      if (this.happiness < 5) {
       console.log("Meow. Don't touch me!");
      } else {
       meow();
      }
    }   
    meow() {
  console.log("Moew. Pet me more");
 }
 }
 

const paw = new Paws(6,7,9,8); 

console.log(paw.tiredness);