I created a little game with JavaScript while i am learning it.
I would like to get a count clicker in it. So you can see how many times you have clicked on the canvas before you die. (so it resets right after the 'game over'.
Here is the JS code i have at the moment:
window.addEventListener("load", function () {
//constants
var GAME_WIDTH = 640;
var GAME_HEIGHT = 360;
//keep the game going
var gameLive = true;
//current level
var level = 1;
//enemies
var enemies = [{
x: 100, //x coordinate
y: 100, //y coordinate
speedY: 2, //speed in Y
w: 40, //width
h: 40 //heght
},
{
x: 200,
y: 0,
speedY: 2,
w: 40,
h: 40
},
{
x: 330,
y: 100,
speedY: 3,
w: 40,
h: 40
},
{
x: 450,
y: 100,
speedY: -3,
w: 40,
h: 40
}
];
//the player object
var player = {
x: 10,
y: 160,
speedX: 2.5,
isMoving: false, //keep track whether the player is moving or not
w: 40,
h: 40
};
//the goal object
var goal = {
x: 580,
y: 160,
w: 50,
h: 36
}
// var zonder waarde
var img = {};
var movePlayer = function () {
player.isMoving = true;
}
var stopPlayer = function () {
player.isMoving = false;
}
//grab the canvas and context
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
//event listeners to move player
canvas.addEventListener('mousedown', movePlayer);
canvas.addEventListener('mouseup', stopPlayer);
canvas.addEventListener('touchstart', movePlayer);
canvas.addEventListener('touchend', stopPlayer);
var load = function () {
img.player = new Image();
img.player.src = 'images/ping.png';
img.background = new Image();
img.background.src = 'images/sea.png';
img.enemy = new Image();
img.enemy.src = 'images/enemy.png';
img.goal = new Image();
img.goal.src = 'images/fish.png';
};
//update the logic
var update = function () {
//check if you've won the game
if (checkCollision(player, goal)) {
// leven +1
level++;
// level in console
console.log(level);
// get player back in position
player.x = 10;
player.y = 160;
//increase the speed of the enemies by 1
//increase the speed of the enemies by 1
enemies.forEach(function (enemies) {
if (enemies.speedY > 0) {
enemies.speedY++;
} else {
enemies.speedY--;
}
});
}
//update player
if (player.isMoving) {
player.x = player.x + player.speedX;
}
enemies.forEach(function (element, index) {
//check for collision with player
if (checkCollision(player, element)) {
//stop the game
gameLive = false;
alert('Game Over!');
//reload page
window.location = "";
};
//move enemy
element.y += element.speedY;
//check borders
if (element.y <= 10) {
element.y = 10;
//element.speedY = element.speedY * -1;
element.speedY *= -1;
} else if (element.y >= GAME_HEIGHT - 50) {
element.y = GAME_HEIGHT - 50;
element.speedY *= -1;
}
});
};
//show the game on the screen
var draw = function () {
//clear the canvas
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
//draw background
ctx.drawImage(img.background, 0, 0);
//draw player
ctx.drawImage(img.player, player.x, player.y);
//draw enemies
enemies.forEach(function (element, index) {
ctx.drawImage(img.enemy, element.x, element.y);
});
//draw goal
ctx.drawImage(img.goal, goal.x, goal.y);
//for seeing the level in canvas
//color points
ctx.fillStyle = "#339900";
//font points
ctx.font = "60px Michroma";
//point shower
ctx.fillText(level, 10, 55);
};
//gets executed multiple times per second
var step = function () {
update();
draw();
if (gameLive) {
window.requestAnimationFrame(step);
}
};
//check the collision between two rectangles
var checkCollision = function (rect1, rect2) {
var closeOnWidth = Math.abs(rect1.x - rect2.x) <= Math.max(rect1.w, rect2.w);
var closeOnHeight = Math.abs(rect1.y - rect2.y) <= Math.max(rect1.h, rect2.h);
return closeOnWidth && closeOnHeight;
}
//initial kick
load();
step();
});
I tried some things out of hand but i couldn't figure it out. Thanks a lot for your help! :)
Kind regards
Add a new variable to increment then within the movePlayer function increment this value. When the game is over you can reset the variable to 0.
For example, below the current level variable add var clickCount = 0;
Then within the movePlayer function add clickCount += 1;
As you are currently reloading the page once the game ends the variable will be reset.
This variable could be output in a simple DIV on the page and does not have to be part of the canvas.
It would be best if you had a working example with the images too. You could do this on https://codesandbox.io/ or https://codepen.io/
UPDATE
Add a DOM element <div id="clickCount">0</div> onto your page. Then replace the movePlayer with the below.
var movePlayer = function () {
clickCount += 1;
player.isMoving = true;
document.getElementById('clickCount').innerHTML = clickCount;
}
This will then update the DIV with the new count, you can then use CSS to position and style the DIV as you want.
Related
I was wondering how I could write in my html/js code a simple leaderboard with the score at the end of the game. I have a level, score and a clickcount score that I want to register.
I don't have any knowledge with databases and server and such, so I really want to keep it 'simple' because I also want to understand what I am typing.
window.addEventListener("load", function() {
//constants
var GAME_WIDTH = 640;
var GAME_HEIGHT = 360;
//keep the game going
var gameLive = true;
//current level
var level = 1;
//Count per click
var clickCount = 0;
//Score
var score = 0;
//enemies
var enemies = [{
x: 100, //x coordinate
y: 100, //y coordinate
speedY: 2, //speed in Y
w: 40, //width
h: 40 //heght
},
{
x: 200,
y: 0,
speedY: 2,
w: 40,
h: 40
},
{
x: 330,
y: 100,
speedY: 3,
w: 40,
h: 40
},
{
x: 450,
y: 100,
speedY: -3,
w: 40,
h: 40
}
];
//the player object
var player = {
x: 10,
y: 160,
speedX: 2.5,
isMoving: false, //keep track whether the player is moving or not
w: 40,
h: 40
};
//the goal object
var goal = {
x: 580,
y: 160,
w: 50,
h: 36
}
// var zonder waarde
var img = {};
var movePlayer = function() {
clickCount += 1;
player.isMoving = true;
document.getElementById('clickCount').innerHTML = clickCount;
}
var stopPlayer = function() {
player.isMoving = false;
}
//grab the canvas and context
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
//event listeners to move player
canvas.addEventListener('mousedown', movePlayer);
canvas.addEventListener('mouseup', stopPlayer);
canvas.addEventListener('touchstart', movePlayer);
canvas.addEventListener('touchend', stopPlayer);
//img load
var load = function() {
img.player = new Image();
img.player.src = 'images/ping.png';
img.background = new Image();
img.background.src = 'images/sea.png';
img.enemy = new Image();
img.enemy.src = 'images/enemy.png';
img.goal = new Image();
img.goal.src = 'images/fish.png';
};
//update the logic
var update = function() {
//check if you've won the game
if (checkCollision(player, goal)) {
// level +1
level++;
// level in console
console.log(level);
// get player back in position
player.x = 10;
player.y = 160;
//increase the speed of the enemies by 1
//increase the speed of the enemies by 1
enemies.forEach(function(enemies) {
if (enemies.speedY > 0) {
enemies.speedY++;
} else {
enemies.speedY--;
}
});
}
//update player
if (player.isMoving) {
player.x = player.x + player.speedX;
score += 1;
}
enemies.forEach(function(element, index) {
//check for collision with player
if (checkCollision(player, element)) {
//stop the game
gameLive = false;
// alert for the level/ points/game over/ and click count
alert('Game Over!' + "\n" + "\n" + "Level: " + level + "\n" + "Score: " + score + '\n' + "Click count:" + " " + clickCount);
//reload page
window.location = "";
};
//move enemy
element.y += element.speedY;
//check borders
if (element.y <= 10) {
element.y = 10;
//element.speedY = element.speedY * -1;
element.speedY *= -1;
} else if (element.y >= GAME_HEIGHT - 50) {
element.y = GAME_HEIGHT - 50;
element.speedY *= -1;
}
});
};
//show the game on the screen
var draw = function() {
//clear the canvas
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
//draw background
ctx.drawImage(img.background, 0, 0);
//draw player
ctx.drawImage(img.player, player.x, player.y);
//draw enemies
enemies.forEach(function(element, index) {
ctx.drawImage(img.enemy, element.x, element.y);
});
//draw goal
ctx.drawImage(img.goal, goal.x, goal.y);
//for seeing the level in canvas
//color points
ctx.fillStyle = "#339900";
//font points
ctx.font = "60px Michroma";
//level shower
ctx.fillText(level, 10, 55);
//point shower
ctx.font = "15px Michroma";
ctx.fillText(score, 585, 30);
};
//gets executed multiple times per second
var step = function() {
update();
draw();
if (gameLive) {
window.requestAnimationFrame(step);
}
};
//check the collision between two rectangles
var checkCollision = function(rect1, rect2) {
var closeOnWidth = Math.abs(rect1.x - rect2.x) <= Math.max(rect1.w, rect2.w);
var closeOnHeight = Math.abs(rect1.y - rect2.y) <= Math.max(rect1.h, rect2.h);
return closeOnWidth && closeOnHeight;
}
//initial kick
load();
step();
});
<div id="centerCanvas">
<canvas id="mycanvas" width="640" height="360"></canvas>
</div>
<div id="clickCount"><span>0</span></div>
A fast database setup that integrates with your script can be Google's Firebase database.
Add Firebase to your Javascript Project
Installation & Setup of Database in Javascript
How to Structure Your Databse
After running through the Firebase web portal to set up your account and project, as an example, you can use the following in your JS file to write a record to the database:
var config = {
apiKey: "yourApiKey",
authDomain: "yourProjectId.firebaseapp.com",
databaseURL: "https://yourDatabaseName.firebaseio.com"
};
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
function writeUserData(userName, clickCount, score) {
firebase.database().ref('highscores/' + name).set({
userName: userName,
clickCount: clickCount,
score: score
});
}
I am new to canvas and developing a game where a car moves straight and now I want to rotate the image of the car only to rotate anti clockwise when the left key is pressed and clockwise when right key is pressed.
Currently I am trying with
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "images/car.png";
if (37 in keysDown) { // Player holding left
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width,canvas.height);
ctx.rotate(90*Math.PI/180);
ctx.drawImage(heroImage,hero.x,hero.y);
}
But this rotates the whole screen .I only want the heroImage to be rotated and not the screen.Any help is appreciated.
My source code: working pen
To get key input and rotate paths and what not on the canvas.
/** SimpleUpdate.js begin **/
// short cut vars
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
ctx.font = "18px arial";
var cw = w / 2; // center
var ch = h / 2;
var focused = false;
var rotated = false;
var angle = 0;
// Handle all key input
const keys = { // key input object
ArrowLeft : false, // only add key names you want to listen to
ArrowRight : false,
keyEvent (event) {
if (keys[event.code] !== undefined) { // are we interested in this key
keys[event.code] = event.type === "keydown";
rotated = true; // to turn off help
}
}
}
// add key listeners
document.addEventListener("keydown", keys.keyEvent)
document.addEventListener("keyup", keys.keyEvent)
// check if focus click
canvas.addEventListener("click",()=>focused = true);
// main update function
function update (timer) {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.clearRect(0,0,w,h);
// draw outside box
ctx.fillStyle = "red"
ctx.fillRect(50, 50, w - 100, h - 100);
// rotate if input
angle += keys.ArrowLeft ? -0.1 : 0;
angle += keys.ArrowRight ? 0.1 : 0;
// set orgin to center of canvas
ctx.setTransform(1, 0, 0, 1, cw, ch);
// rotate
ctx.rotate(angle);
// draw rotated box
ctx.fillStyle = "Black"
ctx.fillRect(-50, -50, 100, 100);
// set transform to center
ctx.setTransform(1, 0, 0, 1, cw, ch);
// rotate
ctx.rotate(angle);
// move to corner
ctx.translate(50,50);
// rotate once more, Doubles the rotation
ctx.rotate(angle);
ctx.fillStyle = "yellow"
ctx.fillRect(-20, -20,40, 40);
ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default
// draw center box
ctx.fillStyle = "white"
ctx.fillRect(cw - 25, ch - 25, 50, 50);
if(!focused){
ctx.lineWidth = 3;
ctx.strokeText("Click on canvas to get focus.",10,20);
ctx.fillText("Click on canvas to get focus.",10,20);
}else if(!rotated){
ctx.lineWidth = 3;
ctx.strokeText("Left right arrow to rotate.",10,20);
ctx.fillText("Left right arrow to rotate.",10,20);
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
/** SimpleUpdate.js end **/
<canvas id = canvas></canvas>
Looking at you pen bellow is a function that will help.
The following function will draw a scaled and rotated sprite on the canvas
// draws a image as sprite at x,y scaled and rotated around its center
// image, the image to draw
// x,y position of the center of the image
// scale the scale, 1 no scale, < 1 smaller, > 1 larger
// angle in radians
function drawSprite(image, x, y, scale = 1,angle = 0){
ctx.setTransform(scale, 0, 0, scale, x, y); // set scale and center of sprite
ctx.rotate(angle);
ctx.drawImage(image,- image.width / 2, - image.height / 2);
ctx.setTransform(1,0,0,1,0,0); // restore default transform
// if you call this function many times
// and dont do any other rendering between
// move the restore default line
// outside this function and after all the
// sprites are drawn.
}
OK more for you.
Your code is all over the place and the only way to work out what was happening was to rewrite it from the ground up.
The following does what I think you want your pen to do. Not I squash the width to fit the snippet window.
Code from OP pen and modified to give what I think the OP wants.
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1024;
canvas.height = 1024;
document.body.appendChild(canvas);
var monstersCaught = 0;
var lastFrameTime;
var frameTime = 0; // in seconds used to control hero speed
// The main game loop
function main (time) {
if(lastFrameTime !== undefined){
frameTime = (time - lastFrameTime) / 1000; // in seconds
}
lastFrameTime = time
updateObjects();
render();
requestAnimationFrame(main);
};
// this is called when all the images have loaded
function start(){
monstersCaught = 0;
resetObjs();
requestAnimationFrame(main);
}
function displayStatus(message){
ctx.setTransform(1,0,0,1,0,0); // set default transform
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "black";
ctx.font = "24px Helvetica";
ctx.textAlign = "center";
ctx.textBaseline = "center";
ctx.fillText(message,canvas.width / 2 ,canvas.height / 2);
}
// reset objects
function resetObjs () {
monsters.array.forEach(monster => monster.reset());
heros.array.forEach(hero => hero.reset());
}
// Update game objects
function updateObjects (modifier) {
monsters.array.forEach(monster => monster.update());
heros.array.forEach(hero => hero.update());
}
function drawObjects (modifier) {
monsters.array.forEach(monster => monster.draw());
heros.array.forEach(hero => hero.draw());
}
// Draw everything
function render () {
ctx.setTransform(1,0,0,1,0,0); // set default transform
ctx.drawImage(images.background, 0, 0);
drawObjects();
// Score
ctx.setTransform(1,0,0,1,0,0); // set default transform
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Points: " + monstersCaught, 32, 32);
}
// hold all the images in one object.
const images = { // double underscore __ is to prevent adding images that replace these functions
__status : {
count : 0,
ready : false,
error : false,
},
__onready : null,
__createImage(name,src){
var image = new Image();
image.src = src;
images.__status.count += 1;
image.onerror = function(){
images.__status.error = true;
displayStatus("Error loading image : '"+ name + "'");
}
image.onload = function(){
images.__status.count -= 1;
if(images.__status.count === 0){
images.__status.ready = true;
images.__onready();
}
if(!images.__status.error){
displayStatus("Images remaing : "+ images.__status.count);
}
}
images[name] = image;
return image;
}
}
// Handle all key input
const keys = { // key input object
ArrowLeft : false, // only add key names you want to listen to
ArrowRight : false,
ArrowDown : false,
ArrowUp : false,
keyEvent (event) {
if (keys[event.code] !== undefined) { // are we interested in this key
keys[event.code] = event.type === "keydown";
event.preventDefault();
}
}
}
// default setting for objects
const objectDefault = {
x : 0, y : 0,
dir : 0, // the image rotation
isTouching(obj){ // returns true if object is touching box x,y,w,h
return !(this.x > obj.x +obj.w || this.y > obj.y +obj.h || this.x + this.w < obj.x || this.y + this.h < obj.y);
},
draw(){
ctx.setTransform(1,0,0,1,this.x + this.w / 2, this.y + this.h / 2);
ctx.rotate(this.dir);
ctx.drawImage(this.image, - this.image.width / 2, - this.image.height / 2);
},
reset(){},
update(){},
}
// default setting for monster object
const monsterDefault = {
w : 32, // width
h : 32, // height
reset(){
this.x = this.w + (Math.random() * (canvas.width - this.w * 2));
this.y = this.h + (Math.random() * (canvas.height - this.h * 2));
},
}
// default settings for hero
const heroDefault = {
w : 32, // width
h : 32, // height
speed : 256,
spawnPos : 1.5,
reset(){
this.x = canvas.width / this.spawnPos;
this.y = canvas.height / this.spawnPos;
},
update(){
if (keys.ArrowUp) { // Player holding up
this.y -= this.speed * frameTime;
this.dir = Math.PI * 0; // set direction
}
if (keys.ArrowDown) { // Player holding down
this.y += this.speed * frameTime;
this.dir = Math.PI * 1; // set direction
}
if (keys.ArrowLeft) { // Player holding left
this.x -= this.speed * frameTime;
this.dir = Math.PI * 1.5; // set direction
}
if (keys.ArrowRight) { // Player holding right
this.x += this.speed * frameTime;
this.dir = Math.PI * 0.5; // set direction
}
if(Math.sign(this.speed) === -1){ // filp directio of second car
this.dir += Math.PI; // set direction
}
monsters.array.forEach(monster => {
if(monster.isTouching(this)){
monster.reset();
monstersCaught += 1;
}
});
if (this.x >= canvas.width || this.y >= canvas.height || this. y < 0 || this.x < 0) {
this.reset();
}
}
}
// objects to hold monsters and heros
const monsters = { // dont call a monster "array"
array : [], // copy of monsters as array
};
const heros = { // dont call a monster "array"
array : [], // copy of heros as array
};
// add monster
function createMonster(name, settings = {}){
monsters[name] = {...objectDefault, ...monsterDefault, ...settings, name};
monsters[name].reset();
monsters.array.push(monsters[name]);
return monsters[name];
}
// add hero to heros object
function createHero(name, settings){
heros[name] = {...objectDefault, ...heroDefault, ...settings, name};
heros[name].reset();
heros.array.push(heros[name]);
return heros[name];
}
// set function to call when all images have loaded
images.__onready = start;
// load all the images
images.__createImage("background", "http://res.cloudinary.com/dfhppjli0/image/upload/v1491958481/road_lrjihy.jpg");
images.__createImage("hero", "http://res.cloudinary.com/dfhppjli0/image/upload/c_scale,w_32/v1491958999/car_p1k2hw.png");
images.__createImage("monster", "http://res.cloudinary.com/dfhppjli0/image/upload/v1491959220/m_n1rbem.png");
// create all objects
createHero("hero", {image : images.hero, spawnPos : 1.5});
createHero("hero3", {image : images.hero, spawnPos : 2, speed : -256});
createMonster("monster", {image : images.monster});
createMonster("monster3", {image : images.monster});
createMonster("monster9", {image : images.monster});
createMonster("monster12", {image : images.monster});
// add key listeners
document.addEventListener("keydown", keys.keyEvent);
document.addEventListener("keyup", keys.keyEvent);
canvas {
width : 100%;
height : 100%;
}
i am new in canvas scripting. i am try to build some condition in canvas, which the condition will showing text after the condition fulfilled. Here the conditions that i made.
if( fictionMeter > 26 && fictionMeter < 37 ) {
ctx.fillStyle = "#e86f14";
ctx.font = "25px Bangers";
ctx.fillText(
"Alert Condition 1",
mx + 55,
my - 25
);
ctx.font = "14px Bangers";
ctx.fillText(
"add some extra condition",
mx - 55,
my - 8
);
}
if( fictionMeter > 37 ) {
ctx.fillStyle = "#d5292b";
ctx.font = "25px Bangers";
ctx.fillText(
"DANGER CONDITION ONE",
mx + 45,
my - 25
);
ctx.font = "14px Bangers";
ctx.fillText(
"DANGER extra condition one",
mx - 10,
my - 8
);
}
ctx.restore();
}
My question is how to add blinking text animation on it?,which the text animation will appear for a second and than hide until the other condition fulfilled.
The easier way to keep track of objects with their own animation properties is to create objects representing them. This way you can drive an object using current time and independently.
For example (see comments):
var ctx = c.getContext("2d"), bg = 0, db = 0.01;
// BlinkText objects which will hold appearance and timings
function BlinkText(txt, x, y, interval) {
this.text = txt;
this.x = x;
this.y = y;
this.interval = interval;
this.font = "bold 20px sans-serif";
this.color = "#f00";
this.active = false;
this.time = 0;
this.toggle = true;
}
// If several instances is to be defined, use prototypal approach
BlinkText.prototype = {
start: function(time) {
this.time = time; // store start time to calc. delta
this.active = true; // enable drawing in render()
this.toggle = true; // reset toggle flag so first check is "on"
},
stop: function() {
this.active = false; // disable drawing in render()
},
render: function(ctx) { // render if active
if (this.active) {
if (this.toggle) { // are we on nor off?
ctx.font = this.font;
ctx.fillStyle = this.color;
ctx.fillText(this.text, this.x, this.y); // render text if on
}
// calc time interval and toggle every other time
var time = performance.now();
if (time - this.time >= this.interval) { // passed interval?
this.time = time; // update start time
this.toggle = !this.toggle; // toggle state
}
}
}
};
// create a couple of instances
var txt1 = new BlinkText("Hello there..", 50, 50, 500);
var txt2 = new BlinkText("This is blinking too", 100, 90, 900);
var txt3 = new BlinkText("All independant, but controlable...", 10, 120, 300);
txt2.color = "#00f"; // set some custom properties
txt3.font = "16px sans-serif";
txt3.color = "#090";
(function loop() {
// draw other stuff
ctx.fillStyle = "hsl(0,0%, " + (bg * 40) + "%)";
ctx.fillRect(0, 0, c.width, c.height);
txt1.render(ctx); // call render() regardless of state
txt2.render(ctx);
txt3.render(ctx);
bg += db;
if (bg <0 || bg > 1) db = -db;
requestAnimationFrame(loop)
})();
bstart.onclick = function() {
txt1.start(performance.now()); // init start with current time
txt2.start(performance.now());
txt3.start(performance.now());
};
bstop.onclick = function() {
txt1.stop();
txt2.stop();
txt3.stop();
};
<canvas id=c></canvas><br>
<button id=bstart>Start</button> <button id=bstop>Stop</button>
How change the speed of each shape?
I tried to play with pct but I guess this is wrong way:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// shape stuff
var shapes = [];
var points;
// shape#1
points = pointsToSingleArray([{
x: 20,
y: 20
}, {
x: 50,
y: 100
}, {
x: 75,
y: 20
}, {
x: 100,
y: 100
}]);
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red"
});
// shape#2
points = pointsToSingleArray([{
x: 0,
y: 0
}, {
x: 180,
y: 0
}, {
x: 180,
y: 180
}, {
x: 0,
y: 180
}, {
x: 0,
y: 0
}, {
x: 100,
y: 80
}]);
shapes.push({
width: 20,
height: 20,
waypoints: points,
color: "blue"
});
// animation stuff
var index = 0;
var fps = 60;
// start animating
animate();
function pointsToSingleArray(points) {
// array to hold all points on this polyline
var allPoints = [];
// analyze all lines formed by this points array
for (var a = 1; a < points.length; a++) { // loop through each array in points[]
// vars for interpolating steps along a line
var dx = points[a].x - points[a - 1].x;
var dy = points[a].y - points[a - 1].y;
var startX = points[a - 1].x;
var startY = points[a - 1].y;
// calc 100 steps along this particular line segment
for (var i = 1; i <= 100; i++) {
var pct = Math.min(1, i * .01);
var nextX = startX + dx * pct;
var nextY = startY + dy * pct;
allPoints.push({
x: nextX,
y: nextY
});
}
}
return (allPoints);
}
function animate() {
setTimeout(function () {
// this flag becomes true if we made any moves
// If true, we later request another animation frame
var weMoved = false;
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all shapes
for (var i = 0; i < shapes.length; i++) {
// get reference to next shape
var shape = shapes[i];
// check if we still have waypoint steps for this shape
if (index < shape.waypoints.length) {
// we're not done, so set the weMoved flag
weMoved = true;
// draw this shape at its next XY
drawShape(shape, index);
} else {
// we're done animating this shape
// draw it in its final position
drawShape(shape, shape.waypoints.length - 1);
}
}
// goto next index XY in the waypoints array
// Note: incrementing by 2 doubles animation speed
index += 2;
// if weMoved this frame, request another animation loop
if (weMoved) {
requestAnimFrame(animate)
};
}, 1000 / fps);
}
function drawShape(shape, waypointIndex) {
var x = shape.waypoints[waypointIndex].x;
var y = shape.waypoints[waypointIndex].y;
ctx.fillStyle = shape.color;
ctx.fillRect(x, y, shape.width, shape.height);
}
Maybe somebody know examples with changing speed, or how to make the code better.
http://jsfiddle.net/4DxLL/ - changing speed
var index = [0, 0];
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red",
speed: 10,
});
index[i] += shape.speed;
I'm trying to make a simple (or so I thought) memory game. Unfortunately it does not update state of cards when user clicks on them. I'm running out of ideas, probably because it's my first javascript game. I suppose there is a problem with game loop. Could anyone at least point me in the right direction and help me understand what needs to be changed/rewritten?
//HTML5 Memory Game implementation
//main variables
var cards = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var exposed = [makeArray("false",16)];
var first_card = 0;
var second_card = 0;
var moves = 0;
var WIDTH = 800;
var HEIGHT = 100;
var state = 0;
var mouseX = 0;
var mouseY = 0;
//creating canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.getElementById("game").appendChild(canvas);
//filling empty array with number,character,object
function makeArray(value, length) {
var newArray = [];
var i = 0;
while (i<length) {
newArray[i] = value;
i++;
}
return newArray;
}
//shuffling algorithm
function shuffle(array) {
var copy = [];
var n = array.length;
var i;
while (n) {
i = Math.floor(Math.random() * n--);
copy.push(array.splice(i, 1)[0]);
}
return copy;
}
//where user clicks
function getClickPosition(event) {
var X = event.pageX - canvas.offsetLeft;
var Y = event.pageY - canvas.offsetTop;
return mouse = [X, Y];
}
//read click position
function readPos(event) {
mousePos = getClickPosition(event);
mouseX = mousePos[0];
mouseY = mousePos[1];
}
//initializing
function init() {
state = 0;
moves = 0;
exposed = [makeArray("false",16)];
cards = shuffle(cards);
}
//drawing cards
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i in cards) {
if (exposed[i] === true) {
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "50px Courier New";
ctx.fillText(cards[i], (i*50+12), 65);
} else {
ctx.strokeStyle = "rgb(250, 0, 0)";
ctx.fillStyle = "rgb(0, 0, 250)";
ctx.fillRect(i*50, 0, 50, 100);
ctx.strokeRect(i*50, 0, 50, 100);
}
}
};
//update cards
function update() {
if (exposed[parseInt(mouseX / 50)] === false) {
if (state == 0) {
state = 1;
first_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
} else if (state == 1) {
state = 2;
second_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
} else {
if (cards[first_card] != cards[second_card]) {
exposed[first_card] = false;
exposed[second_card] = false;
}
state = 1;
first_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
}
}
}
addEventListener('click', readPos, false);
setInterval(function() {
update();
draw();
}, 16);
I would check your addEventListener method: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
I also recommend you look into using jQuery.
After copy and pasting your code I found a couple of things:
You didn't add an event listener to anything, you should add it to something so I added it to document.
You initialize the exposed array with values "false" and later check if they are false. These are not the same, the string "false" isn't the Boolean false.
You initializes the exposed array as a multi dimensional array [[false,false,false ...]] this should be a single dimension array because later you check exposed[1] (1 depending on the mouse x position.
No need to call draw and update every 16 milliseconds, you can call it after someone clicked.
Wrapped the whole thing up in a function so there are no global variables created.
Here is the code after changing these obvious errors. There might be room for optimization but for now I've gotten the problems out.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id="game"></div>
<script type="text/javascript">
(function(){
//HTML5 Memory Game implementation
//main variables
var cards = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
var exposed = makeArray(false, 16);
var first_card = 0;
var second_card = 0;
var moves = 0;
var WIDTH = 800;
var HEIGHT = 100;
var state = 0;
var mouseX = 0;
var mouseY = 0;
//creating canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.getElementById("game").appendChild(canvas);
//filling empty array with number,character,object
function makeArray(value, length) {
var newArray = [];
var i = 0;
while (i < length) {
newArray.push(value);
i++;
}
return newArray;
}
//shuffling algorithm
function shuffle(array) {
var copy = [];
var n = array.length;
var i;
while (n) {
i = Math.floor(Math.random() * n--);
copy.push(array.splice(i, 1)[0]);
}
return copy;
}
//where user clicks
function getClickPosition(event) {
var X = event.pageX - canvas.offsetLeft;
var Y = event.pageY - canvas.offsetTop;
return mouse = [X, Y];
}
//read click position
function readPos(event) {
mousePos = getClickPosition(event);
mouseX = mousePos[0];
mouseY = mousePos[1];
update();
draw();
}
//initializing
function init() {
state = 0;
moves = 0;
exposed = makeArray(false, 16);
cards = shuffle(cards);
}
//drawing cards
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i in cards) {
if (exposed[i] === true) {
ctx.fillStyle = "rgb(150, 150, 150)";
ctx.font = "50px Courier New";
ctx.fillText(cards[i], (i * 50 + 12), 65);
} else {
ctx.strokeStyle = "rgb(250, 0, 0)";
ctx.fillStyle = "rgb(0, 0, 250)";
ctx.fillRect(i * 50, 0, 50, 100);
ctx.strokeRect(i * 50, 0, 50, 100);
}
}
};
//update cards
function update() {
if (exposed[parseInt(mouseX / 50)] === false) {
if (state == 0) {
state = 1;
first_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
} else if (state == 1) {
state = 2;
second_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
} else {
if (cards[first_card] != cards[second_card]) {
exposed[first_card] = false;
exposed[second_card] = false;
}
state = 1;
first_card = parseInt(mouseX / 50);
exposed[parseInt(mouseX / 50)] = true;
}
}
}
document.body.addEventListener('click', readPos, false);
init();
draw();
})();
</script>
</body>
</html>
Your overall logic was good.
The point that was 'bad' was the way you handle the event :
the event handler should store some valuable information that
the update will later process and clear.
Here you mix your update with event handling, which cannot work
especially since the event will not fire on every update.
So i did a little fiddle to show you, the main change is
the click event handler, which update the var last_clicked_card :
http://jsfiddle.net/wpymH/
//read click position
function readPos(event) {
last_clicked_card = -1;
mousePos = getClickPosition(event);
mouseX = mousePos[0];
mouseY = mousePos[1];
// on canvas ?
if ((mouseY>100)||(mouseX<0)||(mouseX>WIDTH)) return;
// now yes : which card clicked ?
last_clicked_card = Math.floor(mouseX/50);
}
and then update is the processing of this information :
//update cards
function update() {
// return if no new card clicked
if (last_clicked_card == -1) return;
// read and clear last card clicked
var newCard = last_clicked_card;
last_clicked_card=-1;
// flip, store it as first card and return
// if there was no card flipped
if (state==0) { exposed[newCard] = true;
first_card = newCard;
state = 1 ;
return; }
// just unflip card if card was flipped
if ((state = 1) && exposed[newCard]) {
exposed[newCard]=false ;
state=0;
return;
}
// we have a second card now
second_card = newCard;
exposed[second_card] = true;
draw();
// ... i don't know what you want to do ...
if (cards[first_card] == cards[second_card]) {
alert('win'); }
else {
alert('loose'); }
exposed[first_card]=false;
exposed[second_card]=false;
state=0;
}