Animating multiple divs in a loop using plain javascript - javascript

I'm having three blue squares on my webpage. Each square is 50px by 50px in size. I wish to slowly increase the size of each squares to 80px by 80px one after the other.
Instead of the expected result above, only the last square size got changed.
Please how can I get the code below to work.
<!DOCTYPE html>
<html>
<head>
<title>zoom box</title>
<script>
function zoom() {
var box;
const height = 50;
var boxes = document.getElementsByClassName('box');
var id;
for (i = 0; i < boxes.length; i++) {
box = boxes[i];
h = height;
frame();
}
function frame() {
h++;
if (h >= 80) {
return;
}
box.style.height = h + 'px';
box.style.width = h + 'px';
setTimeout(frame, 100);
}
}
</script>
<head>
<body width="100%" height="100%" onload="zoom()">
<div style="width: 20em; height: 20em; margin:auto; border-style:solid;display:flex; justify-content: space-between;">
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
</div>
</body>
</html>

function zoom() {
var box;
const height = 50;
var boxes = document.getElementsByClassName('box');
var array = [];
var id;
for (var i = 0; i < boxes.length; i++) {
box = boxes[i];
console.log(box)
h = height;
if(i == 0){
array[i] = true;
}else{
array[i] = false;
}
frame(box,i,height);
}
function frame(box,i,h) {
if (h >= 80) {
for(var j = 0; j < array.length ; j++){
if(j != i && array[j] == false){
array[j] = true;
break;
}
}
array[i] = true;
return box;
}
console.log(i + " " + array[i]);
if(array[i]){
h++;
box.style.height = h + 'px';
box.style.width = h + 'px';
}
setTimeout(function(){
frame(box,i,h);
}, 100);
}
}

Related

How to add a game menu

I am trying to add a generic game menu with "start" to initiate the game. How do I go about doing this? Here is the code:
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
var lastLoopRun = 0;
var score = 0;
var iterations = 0;
var controller = new Object();
var enemies = new Array();
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
}
function intersects(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 480) {
sprite.x = 480 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 480) {
sprite.y = 480 - sprite.h;
}
}
function setPosition(sprite) {
var e = document.getElementById(sprite.element);
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
function handleControls() {
if (controller.up) {
hero.y -= HERO_MOVEMENT;
}
if (controller.down) {
hero.y += HERO_MOVEMENT;
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.space) {
var laser = getFireableLaser();
if (laser) {
laser.x = hero.x + 9;
laser.y = hero.y - laser.h;
}
}
ensureBounds(hero);
}
function getFireableLaser() {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (lasers[i].y <= -120) {
result = lasers[i];
}
}
return result;
}
function getIntersectingLaser(enemy) {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (intersects(lasers[i], enemy)) {
result = lasers[i];
break;
}
}
return result;
}
function checkCollisions() {
for (var i = 0; i < enemies.length; i++) {
var laser = getIntersectingLaser(enemies[i]);
if (laser) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
laser.y = -laser.h;
score += 100;
} else if (intersects(hero, enemies[i])) {
gameOver();
} else if (enemies[i].y + enemies[i].h >= 500) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
}
}
}
function gameOver() {
var element = document.getElementById(hero.element);
element.style.visibility = 'hidden';
element = document.getElementById('gameover');
element.style.visibility = 'visible';
}
function showSprites() {
setPosition(hero);
for (var i = 0; i < lasers.length; i++) {
setPosition(lasers[i]);
}
for (var i = 0; i < enemies.length; i++) {
setPosition(enemies[i]);
}
var scoreElement = document.getElementById('score');
scoreElement.innerHTML = 'SCORE: ' + score;
}
function updatePositions() {
for (var i = 0; i < enemies.length; i++) {
enemies[i].y += 4;
enemies[i].x += getRandom(7) - 3;
ensureBounds(enemies[i], true);
}
for (var i = 0; i < lasers.length; i++) {
lasers[i].y -= 12;
}
}
function addEnemy() {
var interval = 50;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 20;
} else if (iterations > 500) {
interval = 35;
}
if (getRandom(interval) == 0) {
var elementName = 'enemy' + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 35, 35);
var element = document.createElement('div');
element.id = enemy.element;
element.className = 'enemy';
document.children[0].appendChild(element);
enemies[enemies.length] = enemy;
}
}
function getRandom(maxSize) {
return parseInt(Math.random() * maxSize);
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
checkCollisions();
addEnemy();
showSprites();
lastLoopRun = new Date().getTime();
iterations++;
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
var hero = createSprite('hero', 250, 460, 20, 20);
var lasers = new Array();
for (var i = 0; i < 3; i++) {
lasers[i] = createSprite('laser' + i, 0, -120, 2, 50);
}
loop();
#hero {
/* background: #ff0000; */
background-image: url("man-of-space.png");
width: 40px;
height: 40px;
position: absolute;
}
#background {
background-image: url("space.png");
/* background: #000000; */
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
.laser {
background: #00ff00;
width: 2px;
height: 50px;
position: absolute;
}
.enemy {
background-image: url("spaceship.png");
background-size: 40px 40px;
width: 40px;
height: 40px;
position: absolute;
}
#score {
color: #ffffff;
font-size: 18pt;
position: absolute;
left: 20px;
top: 20px;
}
#gameover {
color: #ff0000;
font-size: 20px;
position: absolute;
left: 160px;
top: 200px;
visibility: hidden;
}
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
You could wrap your game UI in a <div id="game" style="display: none;"> element so it will be hidden when the page is loaded. Then wrap your start menu in a <div id="startMenu"> element with a <button id="startButton">Start</button> that will be used to hide the start menu and show the game UI.
In your JS code you could wrap your game in a function so it can be started when you call it.
HTML:
<div id="startMenu">
<button id="startButton">Start</button>
</div>
<div id="game" style="display: none;">
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
</div>
JS:
function startGame() {
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
[...Your game code...]
loop();
}
document.getElementById('startButton').onclick = function() {
document.getElementById('startMenu').style.display = "none";
document.getElementById('game').style.display = "";
startGame();
};
Now you have a start menu (<div id="startMenu">) that you can customize however you like, and a game UI (<div id="game">) that will be shown only after the start button is pressed.
Add more HTML would be my suggestion. Maybe make a div that has all the start screen elements you need in it. When the start function happens, set that div's innerHTML to "".
Example:
document.getElementById('yourDivIdHere').innerHTML = '';

how to make progress Bar with numbers

i have a progress bar which has to finish at 100%, and this moment the number shows this progress, the problem is this number is 1.5(it has to show 0.1, 0,2 and so on till number - 1.5) and I don't know how bind the progress bar with this number
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = width + "%";
}
}
});
Do width/100 and use toFixed() to determine the number of decimals.
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = ((width / 100).toFixed(1)) + "%";
}
}
});
#load {
position: fixed;
height: 100%;
display: flex;
align-items: center;
background-color: #000;
color: #fff;
font-size: 50px;
justify-content: flex-end;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load" />
This is more a math problem than a scripting one...
You have to tell the script that 1.5 is 100%.
I only added one line to your script in order to change the inner HTML displayed.
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1);
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 200); // Setted a longer delay...
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1); // Only one decimal.
}
}
});
#load{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load"></div>

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

How to keep an image outside of a div?

I am creating a maze, and I want the image following the mouse not able to go through the divs to get to the maze. For now, I have set up only one div, so I can get the idea of what I need to do. How can I achieve this?
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}
#drop{
width:100px;
height:100px;
background:aqua;
position: absolute;
left:200px;
top: 300px;
z-index:99
}
.maze {
width: 150px;
margin-left: 500px;
height:150px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div id="drop">
</div>
<div class="maze">
</div>
Jsfiddle: https://jsfiddle.net/3x7cgLdr/27/
I made a fiddle. The collision works. Now it's missing to count the collision sides to avoid the cursor pass the maze.
var isMoving = false;
var cursor = {
lx: 0,
ly: 0,
x: 0,
y: 0,
width: document.getElementById("image").width,
height: document.getElementById("image").height,
hitting: false,
sides: []
},
cursorElement;
var divs,
divs_L,
div_i,
divBd;
var cur_bottom,
div_bottom,
cur_right,
div_right;
var b_collision,
t_collision,
l_collision,
r_collision;
function onCursorMove(e) {
cursor.lx = cursor.x;
cursor.ly = cursor.y;
cursor.x = e.clientX;
cursor.y = e.clientY;
divs = document.getElementsByClassName("hitme");
divs_L = divs.length;
for (div_i = 0; div_i < divs_L; div_i++) {
divBd = divs[div_i].getBoundingClientRect();
if (cursor.x < divBd.left + divBd.width && cursor.x + cursor.width > divBd.left && cursor.y < divBd.top + divBd.height && cursor.y + cursor.height > divBd.top) {
hitting = true;
cur_bottom = cursor.y + cursor.height;
div_bottom = divBd.top + divBd.height;
cur_right = cursor.x + cursor.width;
div_right = divBd.left + divBd.width;
b_collision = div_bottom - cursor.y;
t_collision = cur_bottom - divBd.y;
l_collision = cur_right - divBd.x;
r_collision = div_right - cursor.x;
if (t_collision < b_collision && t_collision < l_collision && t_collision < r_collision) {
//Top collision
cursor.y = divBd.top - cursor.height;
} else if (b_collision < t_collision && b_collision < l_collision && b_collision < r_collision) {
cursor.y = divBd.bottom;
//bottom collision
}
if (l_collision < r_collision && l_collision < t_collision && l_collision < b_collision) {
//Left collision
cursor.x = divBd.left - cursor.width;
} else if (r_collision < l_collision && r_collision < t_collision && r_collision < b_collision) {
//Right collision
cursor.x = divBd.right;
}
break
}
}
cursorElement = document.getElementById("image");
cursorElement.style.left = cursor.x + "px";
cursorElement.style.top = cursor.y + "px";
}
window.onmousemove = onCursorMove;

How can i implement a simple menu for my game made with HTML?

i'm making a simple game with HTML only, more or less it works... My question is if i can make a simple menu /with "click to start" or something similar/ with an image at the background and 1 button to start the game. And if i can make it in the same archive.
Thanks.
<canvas id="ctx" width="1024" height="800" style="border:3px solid #000000;"></canvas>
<script>
var Height = 800;
var Width = 1024;
var timeElapset = Date.now();
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Consolas';
var frameCount = 0;
var score = 0;
var player = {
x:50,
spdX:30,
y:40,
spdY:30,
name:'P',
hp:10,
width:20,
height:20,
color:'green',
};
var enemyList = {};
getDistance = function (Obj1,Obj2){
var vx = Obj1.x - Obj2.x;
var vy = Obj1.y - Obj2.y;
return Math.sqrt((vx*vx)+(vy*vy));
}
checkCollision = function (Obj1,Obj2){
var rect1 = {
x: Obj1.x - Obj1.width/2,
y: Obj1.y - Obj1.height/2,
height: Obj1.height,
width: Obj1.width,
}
var rect2 = {
x: Obj2.x - Obj2.width/2,
y: Obj2.y - Obj2.height/2,
height: Obj2.height,
width: Obj2.width,
}
return testCollisionRectRect(rect1,rect2); //true o false
}
Enemy = function (id,x,y,spdX,spdY,width,height){
var enemy = {
x:x,
spdX:spdX,
y:y,
spdY:spdY,
name:'E',
id:id,
width:width,
height:height,
color:'black',
};
enemyList[id] = enemy;
}
document.onmousemove = function(mouse){
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;
if(mouseX < player.width/2)
mouseX = player.width/2;
if(mouseX > Width-player.width/2)
mouseX = Width - player.width/2;
if(mouseY < player.height/2)
mouseY = player.height/2;
if(mouseY > Height - player.height/2)
mouseY = Height - player.height/2;
player.x = mouseX;
player.y = mouseY;
}
updateEntity = function (Z){
updatePosition(Z);
drawPlayer(Z);
}
updatePosition = function(Z){
Z.x += Z.spdX;
Z.y += Z.spdY;
if(Z.x < 0 || Z.x > Width){
Z.spdX = -Z.spdX;
}
if(Z.y < 0 || Z.y > Height){
Z.spdY = -Z.spdY;
}
}
testCollisionRectRect = function(rect1,rect2){
return rect1.x <= rect2.x+rect2.width &&
rect2.x <= rect1.x+rect1.width &&
rect1.y <= rect2.y + rect2.height &&
rect2.y <= rect1.y + rect1.height;
}
drawPlayer = function(Z){
ctx.save();
ctx.fillStyle = Z.color;
ctx.fillRect(Z.x-Z.width/2,Z.y-Z.height/2,Z.width,Z.height);
ctx.restore();
}
update = function(){
ctx.clearRect(0,0,Width,Height);
frameCount++;
score++;
if(frameCount % 100 == 0)
randomGenerateEnemy();
for(var key in enemyList){
updateEntity(enemyList[key]);
var isColliding = checkCollision(player, enemyList[key]);
if(isColliding){
player.hp = player.hp -1;
}
}
if(player.hp <= 0){
var timeSurvived = Date.now() - timeElapset;
console.log("Has ganado Kappa, Tiempo vivo " + timeSurvived + " ms.");
ctx.fillText(" You Lose! ", Width/2, Height/2);
GameEngine();
}
drawPlayer(player);
ctx.fillText(player.hp + " Hp",20,30);
ctx.fillText('Puntuacion: ' + score/10,700,30);
}
GameEngine = function(){
player.hp = 13;
timeElapset = Date.now();
frameCount = 0;
score = 0;
enemyList = {};
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
}
randomGenerateEnemy = function(){
var x = Math.random()*Width;
var y = Math.random()*Height;
var height = 10 + Math.random()*70;
var width = 10 + Math.random()*70;
var id = Math.random();
var spdX = 5 + Math.random() * 5;
var spdY = 5 + Math.random() * 5;
Enemy(id,x,y,spdX,spdY,width,height);
}
GameEngine();
setInterval(update,30);
</script>
That's what i have.
The code also contains javascript.For proper gaming function .js file has to be called on your html page.Also use css to make it attractive.Consider this example
enter code here
<html>
<head>
<title>Your game title</title>
<script type="text/javascript" src="src/Common.js"></script>
<script type="text/javascript" src="src/Perlin.js"></script>
<script type="text/javascript" src="src/ChaikinCurve.js"></script>
<script type="text/javascript">
var app = null;
window.onload = function() {
utils.loadShaderXml("src/render/shaders.xml", null, function(shaders) {
if (shaders instanceof Exception) {
app = shaders;
} else {
try {
app = new App('canvas', shaders, null);
} catch (e) {
app = e;
}
}
});
document.onselectstart = function () {
return false;
};
};
function application() {
if (app == null) {
alert("Application is absent");
throw "no application";
} else if (app instanceof Exception) {
alert("An exception occured while creating the application:\n" + app.message);
throw app;
} else {
return app;
}
}
</script>
<style type="text/css">
body{
margin: 0px; padding: 0px; overflow: hidden;
background: #000;
}
#canvas-holder.active {
position: absolute;
padding: 0px;
left: 50%;
top: 50%;
}
#canvas-holder.inactive {
position: absolute;
top:50%;
width: 100%;
text-align: center;
}
#canvas {
padding: 0px;
width: 100%;
height: 100%;
color: #fff;
font-family: Allan, Arial;
font-size: 40px;
}
</style>
</head>
<body>
<div id="canvas-holder" class="inactive">
<div id="canvas">Your game` is loading...</div>
</div>
<div style="font-family: Lobster; visibility: hidden">one</div>
<div style="font-family: Allan; visibility: hidden">two</div>
<div style="font-family: Meddon; visibility: hidden">three</div>
<div style="font-family: Cuprum; visibility: hidden">four</div>
</body>
</html>

Categories