Virtual Pet: an Exercise in XML and XSLT

Total Page:16

File Type:pdf, Size:1020Kb

Virtual Pet: an Exercise in XML and XSLT

VIRTUAL PET: AN EXERCISE IN XML & XSLT Jeanine Meyer Mathematics/Computer Science & New Media Purchase College/State University of New York Purchase, New York, 10577 914-251-6679 [email protected]

ABSTRACT EXtensible Markup Language (XML) and eXtensible Stylesheet Language: Transformations (XSLT) are tools for creating and maintaining content-rich applications, such as Web documents. A virtual pet is a computer representation of a [simple] model of pet behavior incorporating mechanisms for owner actions. Starting with a HTML/JavaScript virtual dog script, the author describes the use of eXtended Markup Language (XML) and eXtended Stylesheet Language: Transformations (XSLT) to produce a generalized system for producing simulations. The project has been used in a course on creating user interfaces.

BACKGROUND A virtual pet is a computer representation of a [simple] model of pet behavior incorporating mechanisms for owner actions. One example would be a virtual dog that can be fed or petted. If the virtual dog is fed too little or too much, it dies. When the virtual dog is petted, the dog may wag its tail, but it may, instead, show its teeth in a snarl. This behavior appears unpredictable since it is based on a calculation using a pseudo-random function with input the length of time since the last feeding. Such applications are amusing to students and also serve more profound roles in teaching. Experienced practitioners can learn from simple examples how tools work and can synthesize an assortment of features to build complex applications. Students generally cannot do so. The ability to put different features together may be the defining trait of an expert. At Purchase College/State University of New York, we decided to offer a course called Creating User Interfaces. This course focuses on analysis of usability and functionality and also critical technologies for a variety of media, including the Web (XML, XSLT), wireless phones (WML, WMLS) and directed speech recognition (VoiceXML). It is taken by mathematics/computer science majors, New Media majors and Continuing Education students. EXtended Markup Language (XML) is emerging as a significant technology for its role in Web applications, as the basis for connecting different applications and as the basis for other languages, including eXtended Stylesheet Language: Transformations (XSLT), Wireless Markup Language (WML), and VoiceXML. XSLT is used to specify how an XML document is to be transformed into something else, typically, HyperText Markup Language. The XML and XSLT combination supports a structured, robust approach to formatting documents. Examples of XML and XSLT typically show contact lists, soccer scores and, in an attempt to reach the youth market, CD catalogs. The underlying content is routine and the resulting displays, though varied, are not especially compelling. That is, the non- expert may fail to appreciate the power of the technology. It was the author's experience that students had trouble with XML because examples seemed too obvious and troubles with XSLT because the pattern-matching approach to transformation was different from ordinary programming. The virtual pet example demonstrates that XML content can be multifaceted, even including code fragments. Moreover, this example, and others like it, affords students opportunities to integrate graphics and story telling into their projects. Simulations, along with games, have the distinct feature that students run their programs more than once, a necessary attribute of real-world testing. A basic virtual dog application, coded directly in HTML and JavaScript, is used in our course entitled Creating Web Documents. This is a required course for New Media majors and a popular elective for others. The generalized virtual pet application is one of several examples (following the standard examples showing contact list and soccer scores) to demonstrate the power of XML and XSLT in a course entitled Creating User Interfaces.

VIRTUAL DOG IN HTML AND JAVASCRIPT The original virtual dog was implemented using HTML and JavaScript. The initial screen shows that the dog is in the normal state, as indicated by the graphic and the label. A textbox shows the dog's weight. The next screen shot shows an underfed dog.

If the situation continues with no feeding of the dog, the dog dies. Just as it is possible to starve the virtual pet, it is also possible to overfeed the pet. Overfeeding also can lead to the death of the virtual pet

The action of petting the dog can lead to a happy dog wagging its tail or a dog that snarls. The tail wagging dog is implemented using an animated gif file. The original implementation of the virtual dog was done by 'straight' hand coding of HTML and JavaScript. The HTML consists of a single, named image tag, a

element with 2 input tags (used to display the status and the weight), and 4 hyperlinks using JavaScript calls for the 4 actions. JavaScript has functions that establish timed events and the associated event handling. The call tid = setInterval("change()", 1000); establishes that every 1000 milliseconds a call is to be made to the function change(). The variable tid is set to a number that identifies this particular timed event. A call to window.clearInterval(tid); turns off the timed event pointed to by the variable tid. The change() function examines the weight of the dog, held in a variable and contains a nested if statement to determine what image file is to be placed in the image tag. Note that the model is similar to but not, strictly speaking, a finite state machine because of the presence of the weight variable as well as the calculation of time done to produce time since last feeding. The actions designated by the 4 labels are implemented using HTML tags. For example, the Pet Dog action is implemented using Pet dog where petdog() designates a function. This function performs a calculation using the Math.random() method of JavaScript. Depending on the results, the wag.gif or the mean.gif is placed in the image tag. function petdog() { function header var e; variable to hold elapsed time var p; variable to hold limit var r; variable to hold random value e = seconds_elapsed(); set time elapsed since feeding p = 1-(e/20); calculate limit if (p<.1) { re-adjust limit if less than .1 p = .1; } r = Math.random(); get random value if (r

The result of this formulation is that there is always a chance of either friendly or mean behavior on the part of the dog. It is part of the appeal of the project, though it also led one student to say, "It is obvious that you don't like dogs."

VIRTUAL PET IN XML AND XSLT An XML/XSLT version of the virtual dog would mean that the model of the pet behavior could be separated from the details of the implementation and either one could be modified or completely changed. The application really would be 'virtual pet' with other people able to define their own pet. However, to do that, it is necessary to abstract the content. The framework chosen here is to define a pet behavior in terms of states, state variables, actions, and the base interactions done at each iteration of the simulation. For the generalized virtual pet, the pet designer gives each state a name, furnishes a graphics file, and defines a set of zero or more switch conditions. A switch condition contains the parts that when put together are the code to check for a condition and then change to another state. It can designate only the new state to change to if the condition is true or both true and false new states. At least one state is designated the starting state. Zero or more states can be designated stopping states. State variables are exactly what they sound like: variables that maintain information. They can be viewed as a way of parameterizing any of the states. An obvious candidate for a state variable for this application is weight. Actions are implementations for player moves. In this case, the actions correspond to the Pet Dog and Feed Dog links. The two other links, starting and stopping, are created automatically for all applications. This application assumes some sort of cycle. However, two features of that cycle are up to the individual specification for each virtual pet. These are the timing interval, specified by a state variable named interval and the code that is executed each interval (in addition to the state switch conditions). This code is designated as the intervalaction. The XML file The design of the XML file follows the requirements indicated in the previous section. It is important to point out to students that someone else may have done things differently. For the simple XML examples such as a contact list, most everyone would define the XML tags the same way. It is only when applications reach some degree of complexity that differences can appear. Notice especially the use of attributes versus child elements. The information for specifying a virtual pet is to  animal name  any number of state variables. One must have the name interval.  any number of states. Each state will have a name, label, associated image file, and zero or more switch conditions. One state must have an attribute of start equal to yes. Note that XML rules requires attributes to have values: it would not be valid to have . Zero or more states could have the attribute of stop set to yes.  any number of actions. Actions have labels and procedures. Each action generates a button.  interval action. This specifies code executed at each iteration of the simulation.

The scripting language for the code in the switch conditions, actions and the interval action is in JavaScript. This could be in any language, for example, VBScript, though that would require modest changes to the XML and XSLT. The following is an outline for the vdog.xml file.  XML standard opening instructional tags, including a pointer to the XSL file  The root node is the tag. Everything is contained in this tag.  The animalname tag contains the name output to the title of the HTML document.  There are 4 state variables (statevar): interval, elapsed, wagtime and weight. An attribute indicates if a variable is to be shown. The contents of the element are the initial values of these variables.  There are 7 states: normal, fat, fatdead, thin, thindead, wag, and mean. Attributes indicate the start and the stopping states. Both fatdead and thindead are stopping states. A switch condition contains a condition tag and a truestate tag containing the state to switch to if the condition is true. The implementation allows for a falsestate tag, but it was not used for this example.  There are two designated actions: petting the dog and feeding the dog. These elements contain procedure names and procedures.  The so-called intervalaction specifies code to add the interval value to the elapsed variable and to decrement the weight by one.

The full text of vdog.xml, that is, the XML content that will be transformed into a replica of the original HTML/JavaScript application, is in the Appendix. Implementation of virtual pet using XSLT The transformation of the XML content into a working project is done using an XSLT file, named virtual.xsl. It must create the HTML document with all the necessary JavaScript coding, including variables and functions in the head section and calls to functions in the tags. The XSLT file operates in what is called pull processing to produce the final result. The required elements are selected and manipulated as needed as opposed to using multiple templates and apply-templates to push nodes out to the HTML document. The XSLT program examines certain nodes, for example, the state nodes, more than one time. The XSLT operates in both a procedural and pattern-matching style. Here is an outline of the XSLT file. The complete XSL file is supplied in the Appendix.

 XML and XSLT standard boilerplate  One template: for the topmost node: animal  Set a variable interval to hold the value of the statevar named interval  Output the html and head tags. Include in the title the value of the animalname tag  Output the tags for JavaScript in the head section. Note that the contents of the script element are not commented out. This could be done using < and >  Output the declaration (var statement) of a variable called curstate. It is initialized to be the value of the state with attribute start equal to yes.  Output declarations for all the state variables designated in the xml file.  Output a declaration for a variable called tid, used by setInterval and clearInterval  Output declarations and initializations for two arrays, statepictures and statelabels. These are to be associative arrays. The index is the state name and the value is the picture image file and the label, respectively. The initialization is done using the for-each construct.  Output the change function. This starts with the content of the intervalaction element. The next part of the change function is a switch statement, with each case corresponding to a state. Within each case, each switchcondition produces an if test with condition, code for the true clause and, optionally, code for a false clause. The label for the current state and the picture for the current state are picked up using the associative arrays and placed in the label tag and the image tag. Then, for each state variable designated as show='true', the value is placed in the appropriate input tag. The last part of the change function concerns the states that are designated as stopping states. For each of these, code is output to test for that state being the current state. The contents of the if true clause is a call to stop the timing event using (window.clearInterval(tid)). Note the multiple meanings of 'name'.  The start and stop functions, which are constants, independent of the xml content, are output. A variable named started is used to alert players if they click the start button when play already has started.  For each action designated, functions are defined using the contents of the action elements. This ends the End script element Standard HTML - Standard HTML - This is the start of the img tag to hold the picture of the pet - src set to start = yes state pic1 pic1
- Start of form that will hold values to be displayed - f Form given a name to be referenced by the code - These are designated input field, but only used for output! - Set up the type text … to be text - set the name label .. to be label - Set the (initial) value to be state End input element - that are to be displayed - input element within the form - type attribute set to text text - HTML attribute name to be set to value of XML attribute name. x Add 'x' to prevent confusion. - value attribute set to contents of statevar, the initial value End iteration over statevar nodes End form element


- XSL loop over all actions - corresponding procedure: the one named procedurename by XSL above. node. It is what the player sees. Outputs non-breaking space. Ends XSL loop iterating over actions Start play to start play Inserts blank. Stop play to stop play Standard HTML Standard closing XSL

BIBLIOGRAPHY Michael Kay, XSLT 2nd Edition, Wrox Press, 2001

Tennison, Jeni, Beginning XSLT, Wrox Press, 2002

Recommended publications