Lab 3: Virtual Pet Simulation

Pam Cutter and Kelly Schultz 2003
Nathan Sprague 2009
Kalamazoo College, Kalamazoo, MI
Based on work done at Drexel University
by JL Popyack & Paul Zoski

Introduction

In the following lab you will be incorporating your new knowledge of if-then statements to create a small, simple virtual pet. You interact with the virtual pet by pressing buttons to feed and care for your pet. Sometimes the pet moves from state to state and can be influenced by the owner. Sometimes the pet reaches a state where no more interaction can occur. If this happens, we say that the pet has died.

Using your finite state machine that shows the different states your pet can reach, you will create a web page that simulates a virtual pet. Depending on your finite state machine, your pet will have some actions, sounds, or other behavior. This lab exercise will be the basis for your first programming project.

Design:

The design of your user interface is entirely up to you (except for some guidelines). The page you are creating should contain two text fields to indicate the behavior or actions of your virtual pet, two buttons that allow the "owner" to interact with the virtual pet, and two text fields that will show the current state of the pet and the number of seconds the simulation has run so far. (This will be the number of simulation steps that have been executed, since the simulation is advancing by one step each second.) You will also need a picture of your pet.

Exercise 1 - Design: Your first exercise is to create a web page that will contain your design. Then create a form and include the objects specified above. The fields do not need any information, and the buttons do not need to do anything when clicked on. The purpose of this exercise is merely to set up the display. Don't forget to assign names and id's to all of the elements inside the form. We will need to access these elements in the next exercises. Feel free to add a background and add descriptive text now or at a later date. Don't spend too much time on this exercise now or you will not have enough time to complete the rest of the lab.

Functions:

You will be writing functions to react to several different events: a page load and user clicks on the buttons. The page load event will be handled by an initialization function. The button clicks will be handled by functions that simulate the pet's responses. As you write these functions don't forget to make proper use of white space and indentation. You should also use comments to clarify the steps in your code.

Remember that there are two parts to implementing a function. The function needs to be defined in the HEADER part of the HTML file between the <script> and </script> tags. You also need to call the function, passing it the arguments that you want it to use, in order for the statements in the function to actually be executed.

Exercise 2 - Initializing Your Pet:
  1. The first function you need will be called when the form is first loaded. In this function, you should have 4 statements. The first 3 should set the state to the beginning state for your pet, initialize your counter and call a display function that you will define in the next exercise. To initialize the counter use a statement like: document.getElementById('counter').value = 0 where 'counter' is the id of your counter text field in your form. To set the state, use a similar statement except use the name of your state field instead of counter. The beginning state of your pet will be a name of one of the states from your state diagram. Be sure to use lower case and enclose the state in double quotes.
  2. The last statement will initialize your pet and begin the simulation: setInterval("simulate()",1000).
  3. To call this function when the form is loaded, add the following attribute inside (within the < and >) your <body> tag: onload="functionName()" where functionName is the name of your function.
  4. Preview your page. Your beginning state should appear in the state field and the counter should display 0. You may have an error because you have not yet written the simulate function.
Your second function will be more exciting. It will decide which action to display based on the current state of the pet.
Exercise 3 - Displaying Actions for Your Pet:
  1. In the body of the display function you will have "if" statements to decide what action or behavior your pet will select.
  2. First, retrieve the state of your pet from the state element using a command like: var state = document.getElementById('state').value; where 'state' is the name of your state text field.
  3. Next the value of the state is examined and the action element is updated as appropriate. This is where the information from your behavior table will be used. For example, if the state of the pet is "hungry" then the action of the pet could be "Begging". A sample portion of this function might look like the following, where petaction is the id of the text field representing the pet action.
          var actionElement = document.getElementById('petaction');
    
          if( state == "hungry" )
          {
    	   actionElement.value = "Begging";
          }
          else if( state == "asleep" )
          {
    	   actionElement.value = "Snoring";
          }
          else 
    	  actionElement.value = "";
    
  4. Your "If-Else" statement will have a condition for each possible state of your pet. This function will be called from the simulate function described below.
The next function is the heart of a simulation of state transitions reflected in a finite-state machine.
Exercise 4 - Updating the Pet's State:
  1. The function governing your pet's state transitions will be named simulate. It will be called as a result of the call to setInterval that you created in Exercise 2.
  2. First, retrieve the state of your pet from the appropriate element.
  3. Next, increment the counter number from the counter element by one (the best way to increment is to use the ++ operator).
  4. Preview your page. Depending on the beginning state of your pet, you may see the text boxes change. You should see the counter change from 0 to 1. You should not get any errors.
  5. Now, generate a random number in the interval [0,1) using the following command:
    	var n = Math.random();
    
    This number will be used to determine what state a pet transitions to when the change is driven by chance rather than by an owner action.
  6. You will need to write an "if" statement to check which state the pet is in and to determine if the pet should change state. You will need an "if" statement for each change that the pet makes by chance. For example, if the pet is in the "content" state and changes to the "angry" state 40% of the time and stays in the "content" state the rest of the time the if statement would look like this:
    	if (state == "content" && n < .4)
    		stateElement.value = "angry";
    
    where stateElement is a variable containing your state text element. Your "if" statement will need to continue with an "else" part if there are more possible states.
  7. You will also need to call your display function (created in Exercise 3).
  8. Preview your page. Your pet should now eventually change state if the beginning state is one that changes randomly. You should have no errors. Your buttons will not work yet. Your counter should keep incrementing.
The last functions needed are those that are called when one of your buttons is pressed.
Exercise 5 - Interacting With Your Pet:
  1. You will need to create one function for each button on your form. The functions will be very similar and will contain only two statements. Each function should have its own descriptive name. For this exercise, assume that the button will simulate feeding your pet. A good name for the function would then be feed.
  2. First, retrieve the state of your pet from the state element.
  3. Next, simulate the pet's state transition using an if statement that checks the current state and changes the state to a new value based on the current state. For example, if the pet is "hungry" and is fed then the pet could become "content". That would be accomplished with an "if" statement like this:
    	if (state == "hungry")
    		stateElement.value = "content";
    
    You will need to continue this "if" statement with "else-if" clauses until you have told the pet what to do for each possible state of the pet.
  4. This function will be called when the button is clicked. Add the following attribute inside (within the < and >) your button tag: onclick="functionName()" where functionName is the name you gave your function.
  5. You do not need to call the display function since the simulate function is called every second. That function will display the pet's actions.
  6. Preview your page. Your buttons should now work and your pet should change states in a way that is consistent with your state diagram.
Finishing Up: Before publishing your page to the web server, add comments to your page containing the following information: Add a link from your course home page to your virtual pet page.