الأربعاء، 13 يناير 2016

HTML5 Game Development


                       HTML5                Game
_________
                        Development             ______________________________________
__________________________________________________
Project 1: Building a CSS Quest Game 
In this project, we are going to build a card quest game using HTML elements and CSS styling.
We will also learn how to separate JavaScript logic into modules for clarity. We will build the
game from scratch with a basic HTML layout and then represent the composition of the pattern
in logic and CSS.
Mission briefing
We are going to create a matching game. This game presents a combination of patterns to
the player, and some of these patterns overlap each other. Players analyze the patterns and
then select them in the correct sequence so that the composition matches the provided one.
You may visit the URL http://makzan.net/html5-games/color-quest/ to play the
example game in order to have a better understanding of what we will build throughout
this project.

Why is it awesome  
A simple matching game like this is a perfect way to get you warmed up with the HTML5
games' development rhythm. What we will learn in this project is the foundation to build
more complicated games later in this book.
This game uses what we are familiar with: HTML element interaction and styling in CSS.
What's new, is JavaScript logic. This project will show us how to convert the game rule into
code. We will also learn how to separate logic into different parts with different responsibilities.


We'll perform the following tasks in this project:
  Creating the HTML structure
 f Managing the game scenes
 Representing the quest pattern composition
  Placing the patterns on the deck
ff Selecting the pattern
  Comparing players and compositions of the quest
  Showing different quests
  Counting down the game


Mission checklist
In this game, we are going to stick to plain JavaScript without using a library. This will help us
get started with a basic foundation in JavaScript.
Note that writing JavaScript for games is a little bit different from writing it for a web page.
Game logic requires well-structured code to ensure the logic is easy to read and maintained.
The following essays provide an in-depth discussion on writing JavaScript in the right way:
ff JavaScript best practices:
http://www.thinkful.com/learn/javascript-best-practices-1/
ff JavaScript the right way: http://www.jstherightway.org
Creating the HTML structure
In this task, we are going to kick-start the project by creating the file structure, ensuring that
the essential files are ready.
Prepare for lift off
We need several things to get started. First, we will create an empty project directory.
Then, we will create an index.html file, a folder where we will put the CSS styling files,
and a folder to put the JavaScript logic files in.


During the missions, we need several graphics files, including the background and buttons;
you can find the graphics from the sample code. Put all the images into a directory named
images. The created file structure is shown in the following screenshot:
Engage thrusters
Use the following steps to create the basic game structure:
1. We will enter the following HTML code in the index.html file. It is a basic HTML
structure that includes the CSS file in the head and the script tag at the bottom:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Color Quest</title>
<link rel="stylesheet" href="game.css">
</head>
<body>
<!-- game content here -->
<script src='js/game.js'></script>
</body>
</html>
2. Right after the opening of the <body> tag and before our <script> tag, we add
the following HTML code for the game page. The content is divided into four parts:
header, game section, the how-to-play section, and footer. The game section is
where all the game logic happens. The #element-template is the template of
game elements that will be used for cloning later:
<header>
<div class="row">
<h1>Color Quest</h1>
</div>
</header>
Project 1
11
<section id="game">
</section>
<section class='how-to-play'>
<div class="row">
<h2>How to Play?</h2>
<p>Composite your card to match the given
pattern.</p>
</div>
</section>
<footer>
<div class="row">
<p>This game is an example for the HTML5 Games
Hotshot book. Free for personal and commerical
use.</p>
</div>
</footer>
<div id='element-template'>
</div>
3. Add the following JavaScript to the game.js file. It acts as the entry point of the
game logic:
(function(){
// Entry Point
var init = function() {
};
init(); // start the game
})(); // self-executing function.
Downloading the example code
You can download the example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the files e-mailed directly to you.
Building a CSS Quest Game
12
Objective complete – mini debriefing
We have created a very basic structure of the game. The following sections explain what we
have done.
HTML structure
The header, section, and footer arrangement follows a simple HTML5 content structure.
We will put the game elements inside this structure, attached to the game. The following
screenshot shows the HTML structure:
Modularizing the logic
We separate the JavaScript logic into modules, and each separated file encapsulates one
module. This allows us to tackle each part individually. The first JavaScript file we have is
the game.js file. It is in charge of controlling the game flow. There are other different
parts in this game, and for these parts, we are going to create different files with the
purpose of using them for future tasks.
Project 1
13
Variable scope in JavaScript
In JavaScript, we want to have as few global variables as possible. Variables are global when
they are attached to the highest scope of the runtime environment. In a web browser, this
refers to a variable that is attached to a window scope. A variable that is created with the
var keyword lives inside the scope of the function that encloses it.
This is why we put all the logic inside a self-executing anonymous function. This ensures that
by default, we will not pollute the global scope with our game logic variables. The following
code block shows how to create each module with one global game variable and one local
game variable inside a self-executing-anonymous function:
(function(){
var game = this.colorQuestGame = this.colorQuestGame || {};
})();
We will intentionally create one global variable named colorQuestGame to act as the
namespace. In the later sections, we will put different logic modules into different files
under the same global object.
The this.colorQuestGame || {}; declaration means that, by default, it will use the
existing colorQuestGame variable if it was already declared previously. Otherwise, it will
be a new empty object. We will put this line of declaration into every file.
This scoping feature is also useful when we need to encapsulate logic into private functions.
For example, the following code shows how we can create private functions that are only
accessible inside a specific scope to help extract the code:
Composition.createFromSequence = function(sequence) {
// helper functions
var privateHelperA = function() {}
var privateHelperB = function() {}
// end helper functions
// use your private helper functions here.
}
Inside any method, we can declare local scoped functions to help extract the logic and to
make the code more readable.
Classified intel
For performance, we usually place scripts at the end of Document Object Model (DOM)
and just before the closing of the </body> tag. This is because script loading may block the
loading of DOM and cause the webpage to load slower. For more details, please have a look
at the Yahoo performance rule, Put Scripts at the Bottom, at http://developer.yahoo.
com/performance/rules.html#js_bottom.
Building a CSS Quest Game
14
Managing the game scene
In this task, we create four scenes and display different scenes based on the game flow.
Prepare for lift off
The following figure is our planning of the four scenes and the flow, showing on how they
should link together:
summary scene gameover scene
start scene game scene
Project 1
15
The following figure shows three scenes of what we will create in this task:
Engage thrusters
We code the management part of the scene via the following steps:
1. The scenes are DOM elements, so we will have the following HTML elements
defined inside the tag with the game ID:
<div id="game-scene" class="scene out">
<a href="#" id="gameover-btn">Game Over</a>
<a href="#" id="finish-btn">Finish</a>
</div>
<div id="start-scene" class="scene">
<a href="#" id="start-btn" class="button">
Start Game</a>
</div>
<div id="summary-scene" class="scene out">
<a href="#" id="next-level-button"
class="button">Next</a>
</div>
<div id="gameover-scene" class="scene out">
<a href="#" id="back-to-menu-button"
class="button">Back to menu</a>
</div>
2. Now, we need to import our newly created scenes.js file into the HTML file,
before the game.js file:
<script src='js/scenes.js'></script>
<script src='js/game.js'></script>
</body>
Building a CSS Quest Game
16
3. In the scene.js file, we add the following code to define the scene's object and
its instances:
(function(){
var game = this.colorQuestGame = this.colorQuestGame ||
{};
// put common scene logic into 'scene' object.
var scene = {
node: document.querySelector('.scene'),
show: function() {
this.node.classList.remove('out');
this.node.classList.add('in');
},
hide: function() {
this.node.classList.remove('in');
this.node.classList.add('out');
}
};
// scene instances code to go here.
)();
4. Then, we create an instance of the game scene. Put the following code right after
the scene object code. The following code creates two temporary links to finish
the level and complete the game:
var gameScene = game.gameScene = Object.create(scene);
gameScene.node = document.getElementById('game-scene');
gameScene.handleInput = function() {
document.getElementById('finish-btn').onclick = function(){
game.flow.finishLevel();
};
document.getElementById('gameover-btn').onclick = function(){
game.flow.gameOver();
};
};
5. The start scene instance comes after the game scene code. The following code
handles the clicking of the start button that links to the game scene:
var startScene = game.startScene = Object.create(scene);
startScene.node = document.getElementById('start-scene');
startScene.handleInput = function() {
document.getElementById('start-btn').onclick = function(){
game.flow.nextLevel();
};
};
Project 1
17
6. Then, we have the summary scene. The summary scene has a button that links to
the game scene again to show the next level:
var summaryScene = game.summaryScene =
Object.create(scene);
summaryScene.node = document.getElementById('summaryscene');
summaryScene.handleInput = function() {
document.getElementById('next-level-button')
.onclick = function() {
game.flow.nextLevel();
};
};
7. At last, we add the game over scene code to the scenes.js file. When the game is
over, we bring the player back to the menu scene after the back button is clicked:
var gameoverScene = game.gameoverScene = Object.create(scene);
gameoverScene.node = document.getElementById('gameover-scene');
gameoverScene.handleInput = function() {
var scene = this;
document.getElementById('back-to-menu-button').onclick =
function() {
game.flow.startOver();
};
};
8. Now, we will define a game flow in the game.js file that will help us control how to
show and hide the scenes:
// Main Game Logic
game.flow = {
startOver: function() {
game.startScene.hide();
game.summaryScene.hide();
game.gameoverScene.hide();
game.gameScene.hide();
game.startScene.show();
},
gameWin: function() {
game.gameScene.hide();
game.summaryScene.show();
},
gameOver: function() {
game.startScene.show();
game.gameScene.hide();
game.gameoverScene.show();
},
Building a CSS Quest Game
18
nextLevel: function() {
game.startScene.hide();
game.summaryScene.hide();
game.gameScene.show();
},
finishLevel: function() {
game.gameScene.hide();
game.summaryScene.show();
},
}
9. The init function is the entry point of the game. Inside this function, we will
register the click input listeners:
var init = function() {
game.startScene.handleInput();
game.summaryScene.handleInput();
game.gameoverScene.handleInput();
game.gameScene.handleInput();
}
10. At last, we need some styling for the scenes to make them work. Put the following
CSS rules at the end of the game.css file:
#game {
width: 480px;
height: 600px;
margin: 0 auto;
border: 1px solid #333;
text-align: center;
position: relative;
overflow: hidden;
}
.scene {
background: white;
width: 100%;
height: 100%;
position: absolute;
transition: all .4s ease-out;
}
.scene.out {top: -150%;}
.scene.in {top: 0;}
.button {
width: 145px;
Project 1
19
height: 39px;
display: block;
margin: auto;
text-indent: 120%;
white-space: nowrap;
overflow: hidden;
background-repeat: no-repeat;
}
.button:hover {
background-position: 0 -39px;
}
.button:active {
background-position: 0 0;
}
#start-scene {background: url(images/menu_bg.png);}
#start-btn {
background-image: url(images/start_btn.png);
margin-top: 270px;
}
#game-scene {background: url(images/game_bg.png);}
#game-scene.out {
opacity: 0;
top: 0;
transition-delay: .5s;
}
#summary-scene {background: url(images/summary_bg.png);}
next-level-button {
background-image: url(images/next_btn.png);
margin-top: 370px;
}
#summary-scene.in {
transition-delay: .5s;
}
#gameover-scene {
background: url(images/gameover_bg.png);
}
#back-to-menu-button {
background-image: url(images/restart_btn.png);
margin-top: 270px;
}






ليست هناك تعليقات:

إرسال تعليق