Game Development Reference
In-Depth Information
/widgets
The only widget used in this game is the EnergyBar widget. The whole point of wid-
gets is to simplify the management of different user interface elements. The way in
which each widget decides how to display the elements they represent is their own
business and any client code using them should only be concerned about the inter-
face through which it can communicate with the widget.
What the EnergyBar widget does is display a horizontal bar across the top of the
page representing how much energy the player has left. Each time the player is hit
by an enemy ship, its energy levels drop by some amount. When that energy meter
goes to zero, the player dies, and the game is over.
One way this energy bar could have been rendered was through the canvas API,
where the widget was rendered directly on the game canvas. While this is a very
acceptable solution as well as a very common one, I decided to just use a plain
old DOM element instead. This way the styling can be changed much more easily
through CSS and nothing else would need to be changed within the code. In other
words, while someone worked on the actual code, a second person could work on
styling the widget and all they'd need to access would be the stylesheet associated
with it.
var Packt = Packt || {};
Packt.Widgets = Packt.Widgets || {};
Packt.Widgets.EnergyBar = function(cssClass) {
var energy = 100;
// Create the DOM element to represent this
widget on screen
var container = document.createElement("div");
container.classList.add(cssClass);
var bar = document.createElement("div");
bar.style.width = energy + "%";
container.appendChild(bar);
// Return the DOM element so it can be
Search WWH ::




Custom Search