Virtual Pet Game
Learn to implement the pet unicorn game.
We'll cover the following
We’re going to finish this chapter by creating a virtual pet game, based on the classic Tamagotchi toys. This game will involve the player looking after a pet unicorn. The player gets to name their pet unicorn and then needs to decide when to feed it, play with it, and put it to bed.
The game will use a Unicorn
class to instantiate an object that represents a pet unicorn. The object will have properties that keep track of how the unicorn is feeling, and methods that allow the player to interact with their pet unicorn. This game will run entirely in the console by entering the methods manually.
Defining the properties
The Unicorn
class will need the following properties:
name
: For referring to the unicorn.food
: For keeping track of how much food the unicorn has in its belly.fun
: For recording how much fun the unicorn is having.energy
: For keeping track of how much energy the unicorn has.
Defining the methods
The Unicorn
class will also need the following methods:
eat
: This will increase the value offood
, because eating will put food in the unicorn’s belly, but it will decrease the value offun
, because standing around eating can be a bit dull.sleep
: This will increase the value ofenergy
, because sleeping provides the unicorn with some rest, but the value offood
will decrease as the food is digested. It will also decrease the value offun
, because sleeping can be a bit boring.play
: This will increase the value offun
, because playing is fun, but it will decrease the value ofenergy
, because playing can be hard work!
Components of the class
Let’s create the constructor function that will be used to instantiate a new instance of the Unicorn
class. It should define the properties outlined above. Let’s add the following class definition to the index.js
file:
Get hands-on with 1200+ tech skills courses.