7. http://osama-oransa.blogspot.com/ March, 2012
Animations
• The animation of any character is based on drawing this
shape many times with different shapes.
• So a cycle of clean and re-draw the shape with time
slicing is the basic of animations.
9. http://osama-oransa.blogspot.com/ March, 2012
Sprite Class
• Create object and specify the size of the single frame
(width x height)
• Define draw function that draw the specified frame.
• You can either change the frame according to the object
actions or auto-change it.
• This depends on your game object behavior.
– drawImage(Image Object, source X, source Y, source Width, sou
rce Height, destination X (X position), destination Y (Y position),
Destination width, Destination height)
10. http://osama-oransa.blogspot.com/ March, 2012
Interactions
• 2 Types: Dynamics and Collisions.
• Graphics interact with each others through collision
detection, so once you detect the user character has
collision with enemy or wall or a box,…etc.. we can do
the subsequent needed reaction.
• Collision detections varies from:
– Boundaries calculations
– Color detections
11. http://osama-oransa.blogspot.com/ March, 2012
Collision Detection
• Calculating the boundaries of each character using its
axis and width/height
• Advanced collision detection take into consideration the
filled parts only.
• Example:
– No Collision
– Collision
13. http://osama-oransa.blogspot.com/ March, 2012
Controls
• Controls varies from Keyboard, Mouse, Joystick, Touch
,…etc.
• The most important is to be able to detect controls and
respond to them.
• Also controls have lifetime and could be changed with
different game screens.
• Some controls are valid only under certain conditions
– Pick something only if exist
– Jump only if the space allow that.
14. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Controls mainly focus on the following:
– Control/Change Direction
– Control/Change Speed
– Control/Change Action
• Sometimes user object is continuously moving so you
are only directing the movement, sometimes it is idle and
wait your direction and speed etc.
• Controls are mainly affected by boundaries.
15. http://osama-oransa.blogspot.com/ March, 2012
Boundaries
• Each game scene this is known as the world , this world
must have a boundaries where the user object can move
only inside this.
• The boundaries could be physical like the walls or virtual
like end of your world.
16. http://osama-oransa.blogspot.com/ March, 2012
Entry Points
• Usually games have start point either from menu or a
button to start the game from the beginning.
• But most of the games have multiple entry points like
load saved game, where the user can go to this saved
scene directly.
• The needs here is to design the game code to enable
starting the game smoothly from different points.
• Your entry point need to have some abstraction to
enable this smoothly.
17. http://osama-oransa.blogspot.com/ March, 2012
Physics
• Physics engines are very important in game
development to simulate the animations and interaction
between the object.
• Make things simulate what happen in the real world.
• Example:
– http://labs.skookum.com/demos/barcampclt_physics
• Example of JS Physics engine: Box2DJS
– Box2DJS is a JavaScript port of Box2D Physics Engine.
– URL : http://box2d-js.sourceforge.net/
18. http://osama-oransa.blogspot.com/ March, 2012
AI
• Most of interactive games need some level of AI to
control the enemies or play on behalf of the opponent.
• It varies from simple if/switch cases to complex AI
engine rules.
• It could be predictive or non-predictive.
• The more ability to predict future movements the better
gaming quality you will have.
21. http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Game Components
• HTML 5 Canvas
• Drawing Functions
• Gradient Colors
• Pattern Fill
• Drawing Text
• 2D Context
• HTML 5 Web Storage
• HTML 5 Audio/Video
22. http://osama-oransa.blogspot.com/ March, 2012
HTML 5
• HTML 5 improves interoperability and reduces
development costs by making precise rules on how to
handle all HTML elements, and how to recover from
errors.
• Some of the new features in HTML 5 are functions for
embedding audio, video, graphics, client-side data
storage, and interactive documents.
• To test browser support:
– http://www.html5test.com/
23. http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Canvas
• Uses JavaScript to draw graphics on a web page.
• A canvas is a rectangular area, and you control every
pixel of it.
• The canvas element has several methods for drawing
paths, boxes, circles, characters, and adding images.
<canvas id="myCanvas" width="200" height="100">
</canvas>
26. http://osama-oransa.blogspot.com/ March, 2012
Drawing Functions
• Use JS to draw on it:
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle=“red";
cxt.fillRect(0,0,150,75);
</script>
28. http://osama-oransa.blogspot.com/ March, 2012
Gradient Colors
var grd=cxt.createLinearGradient(0,0,175,50);
grd.addColorStop(0,"#FF0000");
grd.addColorStop(1,"#00FF00");
cxt.fillStyle=grd;
cxt.fillRect(0,0,175,50);
var img=new Image()
img.src="img_flwr.png"
cxt.drawImage(img,0,0);
29. http://osama-oransa.blogspot.com/ March, 2012
Pattern Fill
• Instead of repeat drawing we can apply a pattern using
an image, so you can get the same results with a little
efforts:
var pattern = context.createPattern(backgroundImg,
"repeat");
context.rect(0, 25, screenWidth, canvas.height);
context.fillStyle = pattern;
context.fill();
• Possible Parameter Values:
repeat, repeat-x, repeat-y, no-repeat.
31. http://osama-oransa.blogspot.com/ March, 2012
2D Context
• Best practice to work with context is to push current 2D
context status into stack , modify its properties, finish
your work then pop the old status back from the stack.
context.save();
var pattern = context.createPattern(woodImg, "repeat");
context.rect(0, 350, 600, 100);
context.fillStyle = pattern;
context.fill();
context.restore();
context.rect(50, 150, 600, 100);
32. http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Web Storage
• Two new methods for storing data on the client:
1. localStorage: stores data with no time limit.
2. sessionStorage: stores data for one session.
• Earlier, this was done with cookies.
– Cookies are not suitable for large amounts of data,
because they are passed on by EVERY request to the
server, making it very slow and in-effective.
• In HTML5, the data is NOT passed on by every server
request, but used ONLY when asked for.
33. http://osama-oransa.blogspot.com/ March, 2012
The localStorage Method
• It is possible to store large amounts of data without
affecting the website's performance.
• A website can only access data stored by itself.
• HTML5 uses JavaScript to store and access the data.
• Stores the data with no time limit.
• The data will be available the next day, week, or year.
35. http://osama-oransa.blogspot.com/ March, 2012
The sessionStorage Method
• Stores the data for one session.
• The data is deleted when the user closes the browser
window.
<script type="text/javascript">
sessionStorage.lastname=“Oransa";
document.write(sessionStorage.lastname);
</script>
<script type="text/javascript">
if (sessionStorage.pagecount){
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount);
</script>
36. http://osama-oransa.blogspot.com/ March, 2012
Example
• Methods:
– localStorage.setItem('level', level);
– level = parseInt(localStorage.getItem('level',0));
• We used 0 here as default value if no value already
stored.
• The getter will return null if the value not exist and no
default value and this is very useful.
• Also you can remove the save item by calling:
– removeItem(‘level’);
37. http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Audio
• You can create audio files for your game to reflect
user interactions.
• Using JS code:
boom = new Audio("boom.wav");
boom.play();
• Using HTML 5 tag:
<audio src="Phonics Song 2.wav" controls="controls"
autoplay="autoplay">
Your browser don't support the video element.
</audio>
38. http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Video
• Today, most videos are shown through a plugin (like
flash).
• HTML5 specifies a standard way to include video, with
the video element.
<video src=“myMovie.ogg" controls="controls">
Your browser don’t support the video element.
</video>
• Insert content between the <video> and </video> tags
for browsers that do not support the video element.
45. http://osama-oransa.blogspot.com/ March, 2012
Define Resources
//Create game images
ballonImg= new Image();
ballonRightImg= new Image();
boomImg=new Image();
backgroundImg = new Image();
pinLeftImg = new Image();
pinRightImg = new Image();
pinTopImg = new Image();
pinButtomImg = new Image();
loadImages();
//Create and load game sounds
boom = new Audio(“audio/boom.wav");
46. http://osama-oransa.blogspot.com/ March, 2012
Load Images
//load all images for game
function loadImages() {
ballonImg.src = "images/balloon.png";
ballonRightImg.src = "images/balloon2.png";
backgroundImg.src = "images/back.png";
pinLeftImg.src = "images/pin2.png";
pinRightImg.src = "images/pin.png";
pinTopImg.src = "images/pin-red.png";
pinButtomImg.src = "images/pin-red2.png";
boomImg.src = "images/boom.png";
}
47. http://osama-oransa.blogspot.com/ March, 2012
Game Status
• We have 3 different Game Status:
– 0=Playing
– 1=Died (Exploded)
– 2=Game Over
• In each status the game will behave differently:
– 0=Draw the user object
– 1=Draw the explosion (+boom sound) and wait restart
of the current level.
– 2=Draw “Game Over” and wait restart of the game.
50. http://osama-oransa.blogspot.com/ March, 2012
Keyboard Control
function doKeyDown(event){
switch (event.keyCode) {
case 38: /* Up arrow was pressed */
verticalSpeed=-speed;
break;
case 40: /* Down arrow was pressed */
verticalSpeed=speed;
break;
case 37: /* Left arrow was pressed */
horizontalSpeed=-speed;
break;
case 39: /* Right arrow was pressed */
horizontalSpeed=speed;
break;
}
}
51. http://osama-oransa.blogspot.com/ March, 2012
Touch Control
• Touch events
– Three basic touch events are outlined in the spec and implemented
widely across mobile devices:
– touchstart: a finger is placed on a DOM element.
– touchmove: a finger is dragged along a DOM element.
– touchend: a finger is removed from a DOM element.
• Each touch event includes three lists of touches:
– touches: a list of all fingers currently on the screen.
– targetTouches: a list of fingers on the current DOM element.
– changedTouches: a list of fingers involved in the current event. For
example, in a touchend event, this will be the finger that was removed.
• URL:
– https://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
52. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• These lists consist of objects that contain touch
information: identifier: a number that uniquely identifies
the current finger in the touch session.
• target: the DOM element that was the target of the
action.
• client/page/screen coordinates: where on the screen
the action happened.
• radius coordinates and rotationAngle: describe the
ellipse that approximates finger shape.
53. http://osama-oransa.blogspot.com/ March, 2012
Example
• This snippet lets you drag a DOM element around using
single-finger touch:
var obj = document.getElementById('id');
obj.addEventListener('touchmove', function(event) {
// If there's exactly one finger inside this element
if (event.targetTouches.length == 1) {
var touch = event.targetTouches[0];
// Place element where the finger is
obj.style.left = touch.pageX + 'px'; obj.style.top = touch.pageY + 'px';
}
}, false);
54. http://osama-oransa.blogspot.com/ March, 2012
Gamepad Control
• Gamepad specification defines a low-level interface that
represents gamepad devices.
• 3 Interfaces defined:
– Gamepad, Navigator and GamepadEvent
• URL:
– https://dvcs.w3.org/hg/gamepad/raw-
file/default/gamepad.html
55. http://osama-oransa.blogspot.com/ March, 2012
Initialize the Game
function init(){
context = document.getElementById('canvas').getContext('2d');
screenWidth = document.getElementById('canvas').width;
screenHeight = document.getElementById('canvas').height;
document.getElementById('canvas').onmousemove=mouseMove;
window.addEventListener('keydown',doKeyDown,true);
//load level 0
state=0;
level=0;
lives=15;
loadLevelData();
}
56. http://osama-oransa.blogspot.com/ March, 2012
Game Data
levelsDetails= new Array()
levelsStartPoint= new Array();
levelsPinLeftDetails= new Array();
levelsPinRightDetails= new Array();
levelsPinTopDetails= new Array();
levelsPinButtomDetails= new Array();
////////////// level 0
levelsDetails[0]= new Array(
10,180,340,80,10,95,120,90,10,38,40,65,50,38,320,40,300,20,50,20,230,78,40,105,315,78,40,80,270,120,60,38 );
levelsStartPoint[0]= new Array( 250,200 );
levelsPinLeftDetails[0]= new Array( 5,165,5,190,5,215 );
levelsPinRightDetails[0]= new Array( 100,150,100,125,340,40,322,220,322,190 );
levelsPinTopDetails[0]= new Array( 50,95,70,95,90,95,225,78,245,78 );
levelsPinButtomDetails[0]= new Array( 150,228,170,228 );
///////////// Level 1
levelsDetails[1]= new Array( 290,20,60,280,40,20,60,210,90,140,220,90);
levelsStartPoint[1]= new Array( 300,240 );
levelsPinLeftDetails[1]= new Array( 35,165,35,190 );
levelsPinRightDetails[1]= new Array( 320,140,320,115,320,90 );
levelsPinTopDetails[1]= new Array( 130,140,150,140,170,140,190,140,210,140 );
levelsPinButtomDetails[1]= new Array( 250,198 );
59. http://osama-oransa.blogspot.com/ March, 2012
Draw Levels
function drawLevel(){
context.clearRect(0, 0, screenWidth, screenHeight);
var pattern = context.createPattern(backgroundImg, "repeat");
context.rect(0, 25, screenWidth, canvas.height);
context.fillStyle = pattern;
context.fill();
//draw level details
for (var l = 0; l < details.length; l=l+4) {
context.fillRect(details[l],details[l+1],details[l+2],details[l+3]);
}
if(pinRightDetails[0]!=-1){
for (var l = 0; l < pinRightDetails.length; l=l+2) {
context.drawImage(pinRightImg, pinRightDetails[l],pinRightDetails[l+1]);
}
}
60. http://osama-oransa.blogspot.com/ March, 2012
Cont.
if(pinLeftDetails[0]!=-1){
for (var l = 0; l < pinLeftDetails.length; l=l+2) {
context.drawImage(pinLeftImg,
pinLeftDetails[l],pinLeftDetails[l+1]);
}
}
if(pinButtomDetails[0]!=-1){
for (var l = 0; l < pinButtomDetails.length; l=l+2) {
context.drawImage(pinButtomImg,
pinButtomDetails[l],pinButtomDetails[l+1]);
}
}
context.fillText("Ballon Game", 20, 5);
currentLevel=context.getImageData(0, 0, screenWidth, screenHeight);
}
61. http://osama-oransa.blogspot.com/ March, 2012
Game Loop
• It do the following 2 tasks:
– Draw the background again.
– Draw the new animations.
• In our game we will only move the user object , if there
are other objects that need to be moved , then we must
handle them here.
function gameLoop(){
if(state==0){
context.putImageData(currentLevel, 0, 0);
moveUser();
}
}
63. http://osama-oransa.blogspot.com/ March, 2012
Game Flow
init()
loadLevelData()
drawLevel()
Click start
Level Image
Draw Level Image
Draw Movement
Game Loop
Load resources
Define variables
Define controls
Load Game
64. http://osama-oransa.blogspot.com/ March, 2012
MoveUser Method
function moveUser(){
collision=false;
//Move the user in the current direction
……… Logic of movements…..
//detect collision!
if(collision==true){
//Draw the boom
context.drawImage(boomImg, x, y);
lives--;
boom.play();
state=1;
gameRunning=false;
clearInterval(gameloopId);
if(lives==0){
gameOver();
}
}else{
//Draw the user
if(horizontalSpeed>0) context.drawImage(ballonImg, x, y);
else context.drawImage(ballonRightImg, x, y);
if(y<10) {
if(level<10) level++;
else level=0;
xx=x;
loadLevelData();
}
}
drawGameStatistics();
}
Logic of Movement
& Collision detection
Draw the collision
Or the balloon.
Detect Game Over
Detect Next Level
Draw Game statistics
67. http://osama-oransa.blogspot.com/ March, 2012
User Movements
if(horizontalSpeed>0){
if(x<screenWidth-30){
imagedata = context.getImageData(x+35, y, 1, 35)
data=imagedata.data
var point1=data[0]+data[1]+data[2];
var point2=data[68]+data[69]+data[70];
var point3=data[136]+data[137]+data[138];
if(point1!=255 && point2!=255 && point3!=255 && point1!=765 && point2!=765
&& point3!=765) {
x+= horizontalSpeed;
if(point1!=0 || point2!=0 || point3!=0) {
collision=true;
}
}
}
}else{
…. Same logic but in opposite direction …
}
68. http://osama-oransa.blogspot.com/ March, 2012
Cont.
if(verticalSpeed>0){
if(y<screenHeight){
imagedata = context.getImageData(x, y+44, 35, 1)
data=imagedata.data
//add check for the bricks
var point1=data[0]+data[1]+data[2];
var point2=data[136]+data[137]+data[138];
if(point1!=255 && point2!=255 && point1!=765 && point2!=765) {
y+= verticalSpeed;
if(point1!=0 || point2!=0) {
collision=true;
}
}
}
}else{
….. Same logic but in opposite direction…..
}
69. http://osama-oransa.blogspot.com/ March, 2012
Logging
• In Java Script coding is some how difficult in
troubleshooting issues.
• There are different ways to do that:
– Use FireBug (FF plugin)
– User Web Console and log messages using
• console.log("here x=“+x);
– Use alert(‘the message here’);
– Use JS code: (either replace or append) :
document.getElementById('log').innerHTML="Log="+point
1+" "+point2+" "+point3;
71. http://osama-oransa.blogspot.com/ March, 2012
Save Game
function saveGame(){
localStorage.setItem('level', level);
localStorage.setItem('lives', lives);
localStorage.setItem('xx', xx);
alert("Game Saved!");
}
72. http://osama-oransa.blogspot.com/ March, 2012
Load Game
function loadGame(){
gameRunning=false;
//check if a game is already saved
if(localStorage.getItem('level')==null){
alert("No Game Saved");
return;
}
state=1;
level = parseInt(localStorage.getItem('level',0));
lives = Number(localStorage.getItem('lives',15));
xx = parseInt(localStorage.getItem('xx',150));
loadLevelData();
toggleGameplay();
}
73. http://osama-oransa.blogspot.com/ March, 2012
We’re done!
• So we have made the following so far:
– HTML : just canvas and few buttons.
– DATA file : to draw different level
– CODE : to handle the drawing, animations , controls
,sound effects and game logic.
78. http://osama-oransa.blogspot.com/ March, 2012
Advanced Game Development Topics
1. Using Physics Engine
– Save Balls Game
– World Creation
– Objects Creation
– Physics & Renders
– World Step
– Joints
– Impulses & Forces
2. Using AI Engine
– Tic Tac Toe Game
– Game Components
– AI Engine/Rules
79. http://osama-oransa.blogspot.com/ March, 2012
1) Using Physics Engine
• Box2D is an open source 2D physics engine with a
strong community, numerous ports, and has been tested
and deployed in many games (such as Rolando and
Angry Birds).
• HTML5 games are an exciting new platform, and with
modern JavaScript engines and hardware accelerated
graphics, browsers are now capable of running more
demanding gaming experiences complete with physics
emulations.
82. http://osama-oransa.blogspot.com/ March, 2012
Writing HTML
• Add the usual canvas
<canvas id="mainCanvas" width="480" height="400px">
• Import JS files in the same order described in the APIs or
exist in our demo.
• You may remove the un-used features from these imports but
you still need to keep the order.
<script ……
<script src='js/box2d/collision/shapes/b2Shape.js'></script>
<script src='js/box2d/collision/shapes/b2ShapeDef.js'></script>
<script src='js/box2d/collision/shapes/b2BoxDef.js'></script>
<script …..
84. http://osama-oransa.blogspot.com/ March, 2012
World Creation
• Create world by dimensions : min & max
• Create world gravity.
worldAABB = new b2AABB();
worldAABB.minVertex.Set(-50, -50);
worldAABB.maxVertex.Set(700, 500);
gravity = new b2Vec2(0, 300);
doSleep = true; //false will be slower
world = new b2World(worldAABB, gravity, doSleep);
85. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Every object in Box2d has the following parts :
– Fixture:
• Defines properties like friction , restitution , density
– Shape (2d geometrical shape):
• Can be circle or polygon (set of vertices).
– Body:
• Defines the point where the object is and what is
its type – dynamic , static or kinetic
86. http://osama-oransa.blogspot.com/ March, 2012
Objects Creation
• Create ground by creating box/object definition and body
definition:
var groundSd = new b2BoxDef();
groundSd.extents.Set(600, 50); //dimension
groundSd.restitution = 0.0;
var groundBd = new b2BodyDef();
groundBd.AddShape(groundSd);
groundBd.position.Set(300, 400); // center
return world.CreateBody(groundBd);
87. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Create User Cursor:
cursorSd = new b2BoxDef();
cursorSd.extents.Set(30, 0);
cursorSd.restitution = 0.5;
cursorBd = new b2BodyDef();
cursorBd.AddShape(cursorSd);
cursorBd.position.Set(user_x+30, 200);
return world.CreateBody(cursorBd);
88. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Create Balls:
function createNewCircle(x, y){
var circleSd = new b2CircleDef();
circleSd.density = 1.0;
circleSd.radius = 13;
circleSd.restitution = 0.6;
circleSd.friction = 0.1;
var circleBd = new b2BodyDef();
circleBd.AddShape(circleSd);
circleBd.position.Set(x, y);
return world.CreateBody(circleBd);
}
89. http://osama-oransa.blogspot.com/ March, 2012
Physics & Renders
• The render is totally different than physics object..
• The physics control the behavior while render control
how we need to shape this.
• Example:
function drawCursor(){
context.drawImage(blockImg , user_x, 200,60, 20);
}
92. http://osama-oransa.blogspot.com/ March, 2012
Game Loop
function step(){
random=Math.random();
if(sc_total>0 && random>0.43 && random<0.47){
var circle = createNewCircle(random*400, random*200);
bodies.push(circle);
sc_total--;
}
world.Step(1.0/60, 1);
drawWorld();
drawGameStatistics();
if(sc_total>0) {
loopId=setTimeout('step()', 10);
}else{
gameOver();
}
}
93. http://osama-oransa.blogspot.com/ March, 2012
World Step
• The world.Step method takes 3 parameters – timestep ,
velocity iterations , position iterations
• The timestep indicates , how much time the world should
move ahead by , say 1 second or 0.1 second.
//fps = 60 , time steps
var fps = 60;
var timeStep = 1.0/fps;
world.Step(timeStep , 8 , 3);
95. http://osama-oransa.blogspot.com/ March, 2012
Joints
• Bind two bodies.
• Box2D features six different joint types:
– Distance, Gear, Mouse, Prismatic, Pulley and Revolute joint.
• For example, let's look at the definition of a Revolute
joint:
var joint = new b2RevoluteJointDef();
joint .body1=circle1;
joint .body2=circle2;
joint.collideConnected =true;
world.CreateJoint(joint);
96. http://osama-oransa.blogspot.com/ March, 2012
Impulses
• Box2D allows you to add force and impulses to bodies.
• Adding an impulse is like hitting a body with a hard bat.
Adding force over time is like pushing on a body.
• Both force and impulse require a vector, specifically a
b2Vec2, for direction and magnitude.
• The following code is an easy way to create an impulse:
var degrees=70;
var power=100;
body.ApplyImpulse(new b2Vec2(Math.cos(degrees * (Math.PI / 180)) *
power, Math.sin(degrees * (Math.PI / 180)) * power),
body.GetWorldCenter());
97. http://osama-oransa.blogspot.com/ March, 2012
Animate Object
//animate the fan
context.drawImage(fanImg,fanframe*64,0,64,64,60,300,64,
64);
fanCounter++;
if(fanCounter==10){
fanframe++;
fanCounter=0;
if(fanframe>=3) { fanframe=0;}
}
99. http://osama-oransa.blogspot.com/ March, 2012
Fan Effects
• It poll the balls by applying “Force”.
– ApplyImpulse : immediately change momentum.
• Think being hit by a bat.
– ApplyForce : change momentum over time.
• Think pushing something.
• So far balls move towards the pins.
if(circle.m_position.x>70 && circle.m_position.y>=320){
circle.ApplyForce(new b2Vec2(1000,1000),new
b2Vec2(100,100));
}
106. http://osama-oransa.blogspot.com/ March, 2012
Game Control
case 32: /* Space bar is pressed */
case 13: /* Enter is pressed */
if(state==0 && playerTurn==true){
var n=x-70;var s=y-75;
n=n/70;s=s/55;
if(box[n][s]==emptyValue) {
box[n][s]=lossValue;
playerTurn=false;
counter++;
gameLoop();
}
}
break;
emptyValue =0
lossValue =1
winValue =2
108. http://osama-oransa.blogspot.com/ March, 2012
Our AI Engine
• 2 Levels : Easy (0) and Hard (1)
• Some if conditions to decide the best movement of the
processor.
function play (){
//try to win the game
if(tryToWin()) return;
//try to prevent him from win
if(tryToPreventLoss()) return;
//try to play in the center
if(tryToCenteralize()) return;
}
109. http://osama-oransa.blogspot.com/ March, 2012
Using Frameworks
• Example of ready frameworks to use:
– Impact :
• Impact is a JavaScript Game Engine that allows you to
develop stunning HTML5 Games for desktop and
mobile browsers.
• http://impactjs.com/
– EaselJS:
• A javascript library for working with
the html5 canvas element
• http://easeljs.com/
110. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Advantages:
– Easy , documentation, do not write from scratch.
– Tutorials, samples, out of box functionality.
• Disadvantages:
– Difficult to troubleshoot abnormal behavior.
– Tight coupling with the framework.
111. http://osama-oransa.blogspot.com/ March, 2012
Summary
1. Using Physics Engine
– Save Balls Game
– World Creation
– Objects Creation
– Physics & Renders
– World Step
– Joints
– Impulses & Forces
2. Using AI Engine
– Tic Tac Toe Game
– Game Components
– AI Engine/Rules
115. http://osama-oransa.blogspot.com/ March, 2012
Platform Specific
• Example for Android:
• Create WebView in main.xml instead of TextView.
• Create WebView in your main class.
• Load your page:
webView.loadUrl(file:///android_asset/www/index.html);
• Put your html in the folder:
– /assets/www/index.html
– Put your images, CS and JS in corresponding
folders relative to this parent folder.
• In this video you can see detailed steps:
– http://www.youtube.com/watch?v=uVqp1zcMfbE
116. http://osama-oransa.blogspot.com/ March, 2012
Generic
• MoSync
– The MoSync SDK is licensed under GPL2. That
means you are free to use it in anyway you want if
you give away whatever you create with it for free.
– Create new project HTML 5
– Add your HTML, JS, images and CSS.
– Define application icon.
– Package for the platform you want.
– Test on emulator and mobile.
117. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• PhoneGap
– Package your games into an iPhone or Android App,
ready to be distributed in the App Stores.
• appMobi
– Easily integrate and distribute your games into native
iPhone and Android Apps.
– You don't even need a Mac or XCode to get your
game into the iPhone App Store.
120. http://osama-oransa.blogspot.com/ March, 2012
3D Games using WebGL
• WebGL is a cross-platform, royalty-free web standard for
a low-level 3D graphics API based on OpenGL ES 2.0,
exposed through the HTML5 Canvas element.
• Close to OpenGL ES 2.0 specification.
• WebGL brings plugin-free 3D to the web, implemented
right into the browser.
• Major browser vendors Apple (Safari), Google (Chrome),
Mozilla (Firefox), and Opera (Opera) are members of the
WebGL Working Group.
• URL: http://www.khronos.org/webgl/
121. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Based on OpenGL ES 2.0
– Matches DirectX 9 in capabilities
• No GL extension or plugins.
• No proprietary plugins or APIs
• Cross-browser (not IE)
• Full hardware acceleration
• A lot of tutorials available online:
– http://learningwebgl.com/blog/
122. http://osama-oransa.blogspot.com/ March, 2012
Mouse Lock
• The Mouse Lock API provides for input methods of
applications based on the movement of the mouse, not
just the absolute position of a cursor.
• A popular example is that of first person movement
controls in three dimensional graphics applications such
as games.
– Mandatory for FPS, useful for action games
– http://chromestory.com/2011/10/developer-news-mouse-
lock-api/
123. http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Movement of the mouse is interpreted for rotation of the
view-port, there is no limit to how far movement can go,
and no mouse cursor is displayed.
function mouseClick(e) {
// Request that mouse be locked.
document.lockMouse(x);
// x is the object to get the lock for (send the movement to
it.)
…
127. http://osama-oransa.blogspot.com/ March, 2012
Covered Topics
• Game Development Concepts
• HTML 5 Game Components
• Developing A Game Step by Step
• Advanced Game Development Topics
• Packaging The Game
• What's next?
128. http://osama-oransa.blogspot.com/ March, 2012
New Game Conference
The Conference for HTML5 Game Developers.
Brought by Bocoup and Google.
“The future of gaming is in your browser.”
Prepare your Game for 2012