// JavaScript code for Animal Game example
// This is a 20-questions game where the computer tries to guess what animal
// the user is thinking of by asking yes/no questions.
// The program fetches data from the following URL:
// https://webster.cs.washington.edu/cse154/animalgame.php
// example: https://webster.cs.washington.edu/cse154/animalgame.php?nodeid=12
var yesID;
var noID;
window.onload = function() {
document.getElementById("yes").onclick = yesClick;
document.getElementById("no").onclick = noClick;
fetch(1);
};
// Retrieves the XML data about the given question node.
// Once the request comes back, the dataArrives function will be called.
function fetch(id) {
var ajax = new XMLHttpRequest();
ajax.onload = dataArrives;
ajax.open("GET", "https://webster.cs.washington.edu/cse154/animalgame.php?nodeid=" + id, true);
ajax.send();
}
// Called when XML question node data arrives.
// Parses the XML and shows the question to the user so he/she can answer it.
// Example XML data:
//
// Can it fly?
//
//
//
function dataArrives() {
// do something with this.responseXML;
var question = this.responseXML.getElementsByTagName("question")[0].firstChild.nodeValue;
yesID = this.responseXML.getElementsByTagName("yes")[0].getAttribute("nodeid");
noID = this.responseXML.getElementsByTagName("no")[0].getAttribute("nodeid");
document.getElementById("questionparagraph").innerHTML = question;
}
// Called when the 'Yes' button is clicked.
// Fetches the next question to ask based on the 'Yes' node ID.
function yesClick() {
fetch(yesID);
}
// Called when the 'No' button is clicked.
// Fetches the next question to ask based on the 'No' node ID.
function noClick() {
fetch(noID);
}
// or, if the computer is ready to guess the player's animal:
//
// answer
//