Lab 3: Virtual Pet Simulation

Pam Cutter and Kelly Schultz 2003
Nathan Sprague 2009
Alyce Brady 2017
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 diagram 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 diagram, your pet will have some actions, sounds, or other behavior. This lab exercise will be the basis for your first programming project.

Design and User Interface:

The design of this project is described in Virtual Pet Pre-Lab Design Assignment.

In addition to the text fields described in the Design Assignment, you should add two additional text fields to help you see what's going on as you implement the actions and interactions of your page:

Exercise 1 - User Interface: Your first exercise is to create a web page that represents your design, including the additional text fields described above. For now, your text fields do not need to contain any information, and the buttons do not need to do anything when clicked. The purpose of this exercise is merely to set up the elements on the page. Don't forget to assign names and id's to all of the HTML elements. 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 HEAD section 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. To call this initialization function (even though it hasn't been defined yet), modify your body tag to look like the following:
        <body onload="functionName()">
    
    where functionName is the name you plan to give the initialization function.
  2. Now define your initialization function in the HEAD section of your page. This function should have 4 statements.
    • Initialize your counter, using a statement like counter.value = 0 (where counter should be the actual id you used in your counter text field, whatever that was). Don't put the 0 in quotation marks, since you want to initialize the value to the numeric value, not to a string.
    • Set the state to the beginning state for your pet, using a similar statement except with the name of your state field instead of counter. The beginning state of your pet should be the name of one of the states from your state diagram. Be careful about spelling (including the use of lowercase and capital letters), and enclose the state in double quotes.
    • Call a function to set and display the values in the two "action" text fields. You will define this function in the next exercise. You can choose your own name for it; it does not require any parameters.
    • Start the simulated action of the page by setting up a timer that will call a function every 1000 milliseconds; for example, setInterval("update()",1000). Again, you can choose your own name for this function.
  3. Preview your page. Your beginning state should appear in the state field and the counter should display 0. You may have errors because you have not yet written the display or update functions. You can create minimal, do-nothing versions of them to eliminate those errors; for example:
        function minimalFunction()  // use the actual names you used above
        {
        }
    
Your next function will display the appropriate action(s) for your pet action to display based on the current state of the pet.
Exercise 3 - Updating the Counter:
  1. In the HEAD section, define a new update function (if you didn't already create a minimal version of it in Exercise 1). Be sure to name it with the same name you used when you called it in the setInterval statement you wrote in Exercise 2.
  2. Increment the counter value from the counter element using the ++ operator, e.g., counter.value++. (Warning: if you increment the counter with "+ 1" instead, it may treat the counter value as a string rather than as a number and do string concatenation instead of addition.)
  3. Preview your page. You should see the counter value increment from 0, to 1, to 2, to 3, etc.
  4. Edit your function to call the display function you are about to write in Exercise 4, using the same name you used when you called it in your initialize function in Exercise 2. (You could just copy-and-paste that call into the current function.)
Your next function will display the appropriate action(s) for your pet action to display based on the current state of the pet.
Exercise 4 - Displaying Actions for Your Pet:
  1. In the HEAD section, define a new display function (if you didn't already create a minimal version of it in Exercise 1). Be sure to name it with the same name you used when you called it in your initialization function.
  2. This function will have "if" statements to decide what action or behavior to display for your pet's current state, corresponding to the table you created in Part b of the Pre-Lab Design Assignment.

    You can get the state of your pet by looking at the value of the text field. Since JavaScript allows you to use the id attribute of an HTML element as a variable name, you can use state.value to refer to the value of the field with the id "state". (If the id is something else, you would use that instead.)

    For now, set one of your attribute/behavior text fields based on the pet's current state. For example, if you have text fields with id "state" and "petAction", you might have:

          if ( state.value == "hungry" )
          {
    	   petAction.value = "Begging";
          }
          else if ( state.value == "asleep" )
          {
    	   petAction.value = "Snoring";
          }
          else   // state.value is neither hungry nor asleep
    	  petAction.value = "";
    
  3. Preview your page. The appropriate action associated with the pet's initial state should now appear.
  4. Update your "if-else" statements to set both actions for each state. Preview your page again to test your results.

Now we get to the heart of this program, implementing the state transitions in your finite-state diagram.

First, you will implement the functions that are called when one of your buttons is pressed, corresponding to pet owner actions that cause changes in the pet's state.

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. Each function should have its own descriptive name. For example, if the button simulates feeding your pet, a good name for the function would be feed. (You may want to fully implement and test one button/function before moving on to the second.)
  2. 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. This is similar to what you did in the display function in Exercise 4, except that now you are changing the state rather than a pet action. 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.value == "hungry" )
            state.value = "content";
    
    You will need to continue this "if" statement with "else-if" clauses until you have told the pet what to do in each possible state.
  3. To have this function called when the button is clicked, add the following attribute inside your button tag (within the < and >): onclick="functionName()" where functionName is the name you gave your function.
  4. You do not need to call the display function since the update function is already called every second. That function will display the pet's actions.
  5. Preview your page. Your buttons should now work and your pet should change states in a way that is consistent with those aspects of your state diagram. The pet's actions, implemented in Exercise 4, should also change as the pet's state changes, corresponding to the table you created in your design. (If you implement your buttons one at a time, be sure that both work before moving on to the next exercise.)
Next, you will implement the chance-driven transitions from one state to another.
Exercise 6 - Implementing Random State Changes:
  1. In the update function you wrote in Exercise 3, generate a random number in the interval [0,1) using the following command:
    	var randomVal = 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.
  2. For any state changes that are driven by chance, you will need to write an "if" statement to check if the pet is in the initial state and whether the pet should change or not. For example, if a pet in the "content" state changes to the "angry" state 40% of the time and stays in the "content" state the rest of the time, then the if statement would look like this:
        if (state.value == "content" && randomVal < .4)
             state.value = "angry";
    
    where state is whatever id you gave to your state text field element. Your "if" statement will need to continue with an "else" part if there are other probabilistic state transitions.
  3. Preview your page. Your pet should now change state at random intervals as well as when you click on the owner action buttons, corresponding to your finite 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.