Saturday, July 3, 2021

Virtual Pet (Part 3)

 


Step I: First we will display the last feeding time on screen.


Step II: Open firebase database and create a node named 'gameState' which will take a string value "hungry".


Step III: In sketch.js, create two variables named gameState and readState.


Step IV: In setup() function, we will refer the gameState from database and store its value inside gameState variable.


Step V: Preload the images of bedroom, garden and washroom and more if you want.


Step VI: Now, in Food.js file, create three methods - bedroom(), garden(), washroom() and add background function with their respective images.


Step VII: Change the width and height of canvas and x and y coordinate of dog and bottle(Food.js).



Step VIII: In draw() function write condition for gamestate that if gameState is not hungry then hide the AddFood and FeedFood button else show the AddFood and FeedFood button, food class and dog sprites. For that, move food.display() and drawsprites()  functions in else part of this condition.


Step IX: Now, create a variable currentTime and in setup() function, store the hour in it using hour() function.


Step X: In draw() function, write a condition that if current time is greater than 1 hour of feeding time, the background will be changed to garden. Similarly, if current time is greater than 2 hour of feeding time, the background will be changed to bedroom and if current time is between 3 to 4 hour of feeding time, the background will be changed to washroom. To change the background, we will call the functions which we have created in Food.js where we have loaded the images of background (Step VI).


Step XI: Now, create an updateState() function which will take an argument which we are going to use to update the gameState in database.


Step XII: Come back to the condition where we changed the background (which is created in step x) and after changing the background, update the gameState.


Step XIII: Now, there is a bug that when we press AddFood button the bottle increases and there is no limit to add the bottled which overlaps the dog sprite. To fix it, we will write an if condition so that there will be a limited number of bottles only.  So, in AddFood() function, write an if condition that if bottle is smaller than 60 then only the bottle will increase.


Step XIV: Now, if you want, you can change the time format from 24 hours to 12 hours. For that, you have to write the conditions to display the time.



Now your game is completed and ready to play.

Video:








Previous Post
Next Post

post written by:

0 Comments: