/* * trainer.js * * Computer Science 50, Fall 2011 * section9 * * Lets you train dolphins. */ /* * void * draw_ocean() * * Draws the ocean. */ function draw_ocean() { // start HTML string var html = ""; // store pictures of dolphins in the ocean in HTML string for (var i = 0; i < ocean_array.length; i++) { if (ocean_array[i] == null) html += ""; else html += "Dolphin"; } // continue HTML string html += ""; // store names of all dolphins in HTML string for (var dolphin in DOLPHINS) html += "" + dolphin + ""; // end HTML string html += ""; // print out HTML string document.getElementById("ocean_table").innerHTML = html; return; } /* * void * draw_pool() * * Draws the pool. */ function draw_pool() { // start HTML string var html = ""; // check if a dolphin is in the pool if (pool != null) { html += "

Now Training

"; html += "Name: " + pool.name + "
"; html += "Type: " + pool.type + "
"; html += "Genus: " + pool.genus + "
"; html += "Length: " + pool.length + " feet
"; html += "Weight: " + pool.weight + " pounds
"; } // print out HTML string document.getElementById("pool").innerHTML = html; return; } /* * void * load() * * Loads the web page. */ function load() { /* * put the dolphins into the ocean array * 1) create an empty array * 2) use a for-in loop * on the first iteration of the loop, here is what each variable will equal * dolphin == "Omar" * DOLPHINS[dolphin] == DOLPHINS["Omar"] == {name: "Omar", type:...} */ ocean_array = []; for (var dolphin in DOLPHINS) ocean_array.push(DOLPHINS[dolphin]); // no dolphins are in the pool to begin pool = null; // draw the ocean and the pool draw_ocean(); draw_pool(); return; } /* * void * train() * * Moves a dolphin from the ocean to the pool. */ function train() { // only one dolphin can be trained at a time if (pool != null) { alert("You're already training a dolphin!"); return; } // ask the trainer to pick a dolphin var name = prompt("Pick a dolphin to train:", ""); // remove chosen dolphin from the ocean and put in the pool for (var i = 0; i < ocean_array.length; i++) { if (name == ocean_array[i].name) { pool = ocean_array[i]; // why set the spot to null rather than write "ocean_array.splice(i, 1);"? ocean_array[i] = null; } } // if now training a dolphin if (pool != null) { // draw the ocean and the pool draw_ocean(); draw_pool(); } // if not now training else alert("Please enter an actual dolphin name."); return; } /* * void * set_free() * * Moves a dolphin from the pool to the ocean. */ function set_free() { // can't free a dolphin if not training one if (pool == null) { alert("You're not training a dolphin!"); return; } // remove the dolphin from the pool and put in the ocean for (var i = 0; i < ocean_array.length; i++) { if (ocean_array[i] == null) { ocean_array[i] = pool; pool = null; } } // draw the ocean and the pool draw_ocean(); draw_pool(); return; }