OK, so I'm new to JS, so am trying to make the basic 'breakout' game. What I'm trying to do is arrange the bricks into a triangle shape (or more accurately, forming a triangle out of the absence of bricks). But when I choose which items in the 2D array I want to equal 0 (no brick), it only allows me choose one. after that, the game simply won't load.
Weirdest thing is, it will only accept the first line in this part. No matter what I change, the second line onwards will cause the game to not load:
bricks[0][10]=0;
bricks[7][16]=0;
bricks[7][15]=0;
bricks[7][14]=0;
bricks[7][13]=0;
bricks[7][12]=0;
bricks[7][11]=0;
bricks[7][10]=0;
bricks[7][9]=0;
bricks[7][8]=0;
bricks[7][7]=0;
bricks[7][6]=0;
bricks[7][5]=0;
bricks[7][4]=0;
bricks[7][3]=0;
bricks[7][17]=0;
bricks[6][4]=0;
bricks[6][16]=0;
bricks[5][15]=0;
bricks[5][5]=0;
bricks[4][14]=0;
bricks[4][6]=0;
bricks[3][13]=0;
bricks[3][7]=0;
bricks[2][8]=0;
bricks[2][12]=0;
bricks[1][11]=0;
bricks[1][9]=0;
Also, i know the code is incomplete and flawed as it is. It's not finished and still need a lot of polishing up.
Here's my entire code
canvasApp();
function canvasApp(){
var canvas=document.getElementById("canvas")
if (!canvas || !canvas.getContext){
return;
}
var ctx = canvas.getContext("2d");
if (!ctx) {
return
}
//Application States
const GAME_STATE_TITLE = 0;
const GAME_STATE_NEW_LEVEL = 1;
const GAME_STATE_GAME_OVER = 2;
var currentGameState = 0;
var currentGameStateFunction = null;
var brickcount;
var bouncecount = 0;
//Initialise Start Screen State
var titleStarted = false;
var gameStarted = false;
var gameOver = false;
var keyPressList = [];
var keys = false //mouse or keys. false = mouse control, vice versa
var difficulty = 0;
// Declarations for the game
var dx = 6;
var dy = 6;
var x = 150;
var y = 100;
var r = 10;
var WIDTH = 500;
var HEIGHT = 400;
var ballx = 200;
var bally = 200;
var paddlex = WIDTH/1.2;
var paddleh = 10;
var paddlew = 75;
var paddledx = 30
var mouseX;
var bricks;
var NROWS;
var NCOLS;
var BRICKWIDTH;
var BRICKHEIGHT;
var PADDING;
var rowcolours = ["#FF1C0A", "#FFFD0A", "#00A308", "#0008DB", "#EB0093"];
var paddlecolour = "#FF00FF";
var ballcolour = "#00FFFF";
var backcolour = "#0000FF";
function initbricks() {
NROWS = 9
NCOLS = 21
brickcount = NROWS*NCOLS;
BRICKWIDTH = (WIDTH/NCOLS) - 1;
BRICKHEIGHT = 10;
PADDING = 1;
bricks = new Array(NROWS);
for (i=0; i < NROWS; i++) {
bricks[i] = new Array(NCOLS);
for (j=0; j < NCOLS; j++) {
bricks[i][j] = 1;
}
bricks[0][10]=0;
bricks[7][16]=0;
bricks[7][15]=0;
bricks[7][14]=0;
bricks[7][13]=0;
bricks[7][12]=0;
bricks[7][11]=0;
bricks[7][10]=0;
bricks[7][9]=0;
bricks[7][8]=0;
bricks[7][7]=0;
bricks[7][6]=0;
bricks[7][5]=0;
bricks[7][4]=0;
bricks[7][3]=0;
bricks[7][17]=0;
bricks[6][4]=0;
bricks[6][16]=0;
bricks[5][15]=0;
bricks[5][5]=0;
bricks[4][14]=0;
bricks[4][6]=0;
bricks[3][13]=0;
bricks[3][7]=0;
bricks[2][8]=0;
bricks[2][12]=0;
bricks[1][11]=0;
bricks[1][9]=0;
}
}
initbricks();
function switchGameState(newState) {
currentGameState = newState;
switch (currentGameState) {
case GAME_STATE_TITLE:
currentGameStateFunction = gameStateTitle;
break;
case GAME_STATE_NEW_LEVEL:
currentGameStateFunction = gameStatePlayLevel;
break;
case GAME_STATE_GAME_OVER:
currentGameStateFunction = gameStateGameOver;
break;
}
}
function gameStateTitle(){
if (titleStarted != true){
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
ctx.font = '20px _sans';
ctx.textBaseline = 'top';
ctx.fillText ("Breakout!", 200,150);
ctx.fillText ("Press Space to Play", 170,200);
if (keys == 0 ) {
ctx.fillText ("Mouse selected", 180,250);
ctx.fillText ("Press k to switch to keys", 140,300);
} else {
ctx.fillText ("Keys selected", 190,250);
ctx.fillText ("Press m to switch to mouse", 140,300);
}
titleStarted = true;
}else{
if (keyPressList[75] == true){
keys = 1;
titleStarted = false;
gameStateTitle(); // Redraw the title page
}
if (keyPressList[77] == true){
keys = 0;
titleStarted = false;
gameStateTitle();
}
if (keyPressList[32] == true){
switchGameState(GAME_STATE_NEW_LEVEL);
titleStarted = false;
}
}
}
function gameStatePlayLevel(){
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
// Update the game state and check for game over
function update() {
x+=dx
y+=dy
if (keys == 0) {
paddlex = mouseX;
}else{
if (keyPressList[37]==true){
paddlex-=paddledx;
}
if (keyPressList[39]==true){
paddlex+=paddledx;
}
}
//have we hit a brick?
rowheight = BRICKHEIGHT + PADDING;
colwidth = BRICKWIDTH + PADDING;
row = Math.floor(y/rowheight);
col = Math.floor(x/colwidth);
//if so, reverse the ball and mark the brick as broken
if (y < NROWS * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
brickcount--;
if (brickcount == 0) {
switchGameState(GAME_STATE_NEW_LEVEL);
difficulty+=1;
initbricks();
x=250;
y=200 + (difficulty*20);
brickcount=NROWS*NCOLS;
bouncecount=0;
}
}
if( x<0 || x>WIDTH) dx=-dx;
if( y<0 || y>HEIGHT) dy=-dy;
else if (y + dy > HEIGHT) {
if (x > paddlex && x < paddlex + paddlew) {
dx = 8 * ((x-(paddlex+paddlew/2))/paddlew);
dy = -dy;
bouncecount++;
}
else {
//game over, so stop the animation
switchGameState(GAME_STATE_GAME_OVER);
initbricks();
}
}
}
function render() {
ctx.save();
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
//draw bricks
for (i=0; i < NROWS; i++) {
ctx.fillStyle = rowcolours [i];
for (j=0; j < NCOLS; j++) {
if (bricks[i][j] == 1) {
rect((j * (BRICKWIDTH + PADDING)) + PADDING,
(i * (BRICKHEIGHT + PADDING)) + PADDING, BRICKWIDTH, BRICKHEIGHT);
}
}
}
circle(x, y, 10);
// init_paddle();
ctx.fillStyle = paddlecolour;
rect (paddlex, HEIGHT-paddleh, paddlew, paddleh);
ctx.restore();
show_result()
}
update();
render();
}
function gameStateGameOver(){
if (gameOver != true){
bouncecount=0;
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
ctx.font = '20px _sans';
ctx.textBaseline = 'top';
ctx.fillText ("Game over", 200,150);
ctx.fillText ("Press Space to Restart", 160,200);
ctx.fillText ("You completed " + difficulty + " levels", 160,240);
difficulty=0;
gameOver = true;
}else{
if (keyPressList[32] == true){
switchGameState(GAME_STATE_TITLE);
gameOver = false;
}
}
}
function runGame(){
currentGameStateFunction();
}
// Key handler
document.onkeydown = function(e){
e= e?e:window.event;
keyPressList[e.keyCode] = true;
}
document.onkeyup = function(e){
e= e?e:window.event;
keyPressList[e.keyCode] = false;
}
function onMouseMove(evt) {
// Event data passes to this function
mouseX = evt.clientX-canvas.offsetLeft - paddlew/2;
// Assign the relative position of the mouse in the canvas to mouseX
mouseY = evt.clientY-canvas.offsetTop;
//Do the same for mouseY
document.title="("+mouseX+","+mouseY+")";
//Put the mouse X and Y in the title for info
paddlex = mouseX;
// Position the paddle
}
canvas.addEventListener("mousemove",onMouseMove, false);
//Application start
switchGameState(GAME_STATE_TITLE);
const FRAME_RATE = 40;
var intervalTime = 1000/FRAME_RATE;
setInterval(runGame, intervalTime);
function show_result(){
ctx.fillText ("There are " + brickcount + " bricks", 160,200);
ctx.fillText ("Paddle bounces are " + bouncecount , 160,220);
}
}
With proper indenting, your code looks like this:
bricks = new Array(NROWS);
for (i=0; i < NROWS; i++) {
bricks[i] = new Array(NCOLS);
for (j=0; j < NCOLS; j++) {
bricks[i][j] = 1;
}
bricks[0][10]=0;
bricks[7][16]=0;
In other words, you're attempting to access bricks[7] in the very first iteration when only bricks[0] has been created. Properly close the first for loop with a } before running your list of overrides.
Related
I'm developing a snake game using canvas but am having trouble with displaying the player's score in the upper right corner. This should be handled in the drawScore function but the text doesn't appear. I'm not getting any errors in the console, nor can I find any problem with the code itself.
Any advice would be appreciated!
class SnakePart {
constructor(x,y) {
this.x = x;
this.y = y;
}
}
const body = document.body;
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
let speed = 7; // base speed variable of snake
const snakeParts = [];
let tailLength = 2;
let tileCount = 20;//number of tiles on screen
let headX = 10;//snake width
let headY = 10;//snake height
let tileSize = canvas.width / tileCount - 2;//size of tiles where apple spawns
let xv = 0;// x axis velocity
let yv = 0;//y axis velocity
let ax = 5;//apple position x axis
let ay = 5;//apple position y axis
let score = 0;
//draws game loop
function drawGame(){
//game loop
clearScreen();
changeSnakePosition();
checkAppleCollision();
drawApple();
drawSnake();
drawScore();
setTimeout(drawGame, 1000/speed);
}
function drawScore(){
ctx.fillStyle = 'white';
ctx.font = '12px Helvetica';
ctx.fillText = ("Score: " + score, canvas.width-50, 10);
}
function clearScreen(){
ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
function drawSnake(){
ctx.fillStyle = 'orange';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize,tileSize);
ctx.fillStyle = 'green'
for(let i = 0; i<snakeParts.length; i++){
let part = snakeParts[i];
ctx.fillRect(part.x *tileCount,part.y*tileCount,tileSize,tileSize)
}
snakeParts.push(new SnakePart(headX,headY)); //put a segment at the end of the snake next to the head
while(snakeParts.length > tailLength){
snakeParts.shift(); //remove the furthest item from the snake parts if we have more than our tailSize.
}
}
body.addEventListener('keydown', keyDown);
function keyDown(event){
switch(event.keyCode) {
case 37:
if(xv == 1)
return;
yv = 0;
xv = -1
break;
case 38:
if(yv == 1)
return;
yv= -1;
xv = 0;
break;
case 39:
if(xv == -1)
return;
yv = 0;
xv = 1
break;
case 40:
if(yv == -1)
return;
yv = 1;
xv = 0;
}
}
function changeSnakePosition(){
headX = headX + xv;
headY = headY + yv;
}
function drawApple(){
ctx.fillStyle = 'red';
ctx.fillRect(ax*tileCount,ay*tileCount,tileSize,tileSize)
}
function checkAppleCollision(){
if(ax === headX && ay == headY){
ax = Math.floor(Math.random()*tileCount);
ay = Math.floor(Math.random()*tileCount);
tailLength++;
score++;
speed++;
}
}
drawGame();
<canvas id="canvas"></canvas>
The problem is this line :
ctx.fillText = ("Score: " + score, canvas.width-50, 10);
Which should be :
ctx.fillText("Score: " + score, canvas.width-50, 10);
Here's a stripped down example :
const body = document.body;
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
let score = 0;
function drawGame() {
clearScreen();
drawScore();
}
function drawScore() {
ctx.fillStyle = 'white';
ctx.font = '12px Helvetica';
ctx.fillText("Score: " + score, canvas.width-50, 10);
}
function clearScreen() {
ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
drawGame();
<canvas id="canvas"></canvas>
I'm trying to get this particle explosion working. It's working but it looks like some frames does not get rendered. If I click many times to call several explosions it starts to uhm.. "lag/stutter". Is there something I have forgotten to do? It may look like the browser hangs when I click many times. Is it too much to have 2 for loops inside each other?
Attached my code so you can see.
Just try to click many times, and you will see the problem visually.
// Request animation frame
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
// Canvas
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
// Set full-screen
c.width = window.innerWidth;
c.height = window.innerHeight;
// Options
var background = '#333'; // Background color
var particlesPerExplosion = 20;
var particlesMinSpeed = 3;
var particlesMaxSpeed = 6;
var particlesMinSize = 1;
var particlesMaxSize = 3;
var explosions = [];
var fps = 60;
var now, delta;
var then = Date.now();
var interval = 1000 / fps;
// Optimization for mobile devices
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
fps = 29;
}
// Draw
function draw() {
// Loop
requestAnimationFrame(draw);
// Set NOW and DELTA
now = Date.now();
delta = now - then;
// New frame
if (delta > interval) {
// Update THEN
then = now - (delta % interval);
// Our animation
drawBackground();
drawExplosion();
}
}
// Draw explosion(s)
function drawExplosion() {
if (explosions.length == 0) {
return;
}
for (var i = 0; i < explosions.length; i++) {
var explosion = explosions[i];
var particles = explosion.particles;
if (particles.length == 0) {
explosions.splice(i, 1);
return;
}
for (var ii = 0; ii < particles.length; ii++) {
var particle = particles[ii];
// Check particle size
// If 0, remove
if (particle.size < 0) {
particles.splice(ii, 1);
return;
}
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, Math.PI * 2, 0, false);
ctx.closePath();
ctx.fillStyle = 'rgb(' + particle.r + ',' + particle.g + ',' + particle.b + ')';
ctx.fill();
// Update
particle.x += particle.xv;
particle.y += particle.yv;
particle.size -= .1;
}
}
}
// Draw the background
function drawBackground() {
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
}
// Clicked
function clicked(e) {
var xPos, yPos;
if (e.offsetX) {
xPos = e.offsetX;
yPos = e.offsetY;
} else if (e.layerX) {
xPos = e.layerX;
yPos = e.layerY;
}
explosions.push(new explosion(xPos, yPos));
}
// Explosion
function explosion(x, y) {
this.particles = [];
for (var i = 0; i < particlesPerExplosion; i++) {
this.particles.push(new particle(x, y));
}
}
// Particle
function particle(x, y) {
this.x = x;
this.y = y;
this.xv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.yv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.size = randInt(particlesMinSize, particlesMaxSize, true);
this.r = randInt(113, 222);
this.g = '00';
this.b = randInt(105, 255);
}
// Returns an random integer, positive or negative
// between the given value
function randInt(min, max, positive) {
if (positive == false) {
var num = Math.floor(Math.random() * max) - min;
num *= Math.floor(Math.random() * 2) == 1 ? 1 : -1;
} else {
var num = Math.floor(Math.random() * max) + min;
}
return num;
}
// On-click
$('canvas').on('click', function(e) {
clicked(e);
});
draw();
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>
You are returning from iterating over the particles if one is too small. This causes the other particles of that explosion to render only in the next frame.
I have a working version:
// Request animation frame
const requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
// Canvas
const c = document.getElementById('canvas');
const ctx = c.getContext('2d');
// Set full-screen
c.width = window.innerWidth;
c.height = window.innerHeight;
// Options
const background = '#333'; // Background color
const particlesPerExplosion = 20;
const particlesMinSpeed = 3;
const particlesMaxSpeed = 6;
const particlesMinSize = 1;
const particlesMaxSize = 3;
const explosions = [];
let fps = 60;
const interval = 1000 / fps;
let now, delta;
let then = Date.now();
// Optimization for mobile devices
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
fps = 29;
}
// Draw
function draw() {
// Loop
requestAnimationFrame(draw);
// Set NOW and DELTA
now = Date.now();
delta = now - then;
// New frame
if (delta > interval) {
// Update THEN
then = now - (delta % interval);
// Our animation
drawBackground();
drawExplosion();
}
}
// Draw explosion(s)
function drawExplosion() {
if (explosions.length === 0) {
return;
}
for (let i = 0; i < explosions.length; i++) {
const explosion = explosions[i];
const particles = explosion.particles;
if (particles.length === 0) {
explosions.splice(i, 1);
return;
}
const particlesAfterRemoval = particles.slice();
for (let ii = 0; ii < particles.length; ii++) {
const particle = particles[ii];
// Check particle size
// If 0, remove
if (particle.size <= 0) {
particlesAfterRemoval.splice(ii, 1);
continue;
}
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, Math.PI * 2, 0, false);
ctx.closePath();
ctx.fillStyle = 'rgb(' + particle.r + ',' + particle.g + ',' + particle.b + ')';
ctx.fill();
// Update
particle.x += particle.xv;
particle.y += particle.yv;
particle.size -= .1;
}
explosion.particles = particlesAfterRemoval;
}
}
// Draw the background
function drawBackground() {
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
}
// Clicked
function clicked(e) {
let xPos, yPos;
if (e.offsetX) {
xPos = e.offsetX;
yPos = e.offsetY;
} else if (e.layerX) {
xPos = e.layerX;
yPos = e.layerY;
}
explosions.push(
new explosion(xPos, yPos)
);
}
// Explosion
function explosion(x, y) {
this.particles = [];
for (let i = 0; i < particlesPerExplosion; i++) {
this.particles.push(
new particle(x, y)
);
}
}
// Particle
function particle(x, y) {
this.x = x;
this.y = y;
this.xv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.yv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.size = randInt(particlesMinSize, particlesMaxSize, true);
this.r = randInt(113, 222);
this.g = '00';
this.b = randInt(105, 255);
}
// Returns an random integer, positive or negative
// between the given value
function randInt(min, max, positive) {
let num;
if (positive === false) {
num = Math.floor(Math.random() * max) - min;
num *= Math.floor(Math.random() * 2) === 1 ? 1 : -1;
} else {
num = Math.floor(Math.random() * max) + min;
}
return num;
}
// On-click
$('canvas').on('click', function (e) {
clicked(e);
});
draw();
<!DOCTYPE html>
<html>
<head>
<style>* {margin:0;padding:0;overflow:hidden;}</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>
Loops, break and continue.
The problem was caused when you checked for empty particle arrays and when you found a particle to remove.
The bugs
The following two statements and blocks caused the problem
if (particles.length == 0) {
explosions.splice(i, 1);
return;
}
and
if (particles.size < 0) {
explosions.splice(ii, 1);
return;
}
The returns stopped the rendering of particles, so you would sometimes return before drawing a single particle was rendered just because the first explosion was empty or first particle was too small.
Continue and break
You can use the continue token in javascript to skip the rest of a for, while, do loop
for(i = 0; i < 100; i++){
if(test(i)){
// need to skip this iteration
continue;
}
// more code
// more code
// continue skips all the code upto the closing }
} << continues to here and if i < 100 the loop continues on.
Or you can completely break out of the loop with break
for(i = 0; i < 100; i++){
if(test(i)){
// need to exit the for loop
break;
}
// more code
// more code
// break skips all the code to the first line after the closing }
}
<< breaks to here and if i remains the value it was when break was encountered
The fix
if (particles.length == 0) {
explosions.splice(i, 1);
continue;
}
and
if (particles.size < 0) {
explosions.splice(ii, 1);
continue;
}
Your example with the fix
Your code with the fix. Befor I found it I started changing stuff.
Minor stuff.
requestAnimationFrame passes a time in milliseconds so to an accuracy of micro seconds.
You were setting then incorrectly and would have been losing frames. I changed the timing to use the argument time and then is just set to the time when a frame is drawn.
There are some other issues, nothing major and more of a coding style thing. You should capitalise objects created with new
function Particle(...
not
function particle(...
and your random is a overly complex
function randInt(min, max = min - (min = 0)) {
return Math.floor(Math.random() * (max - min) + min);
}
or
function randInt(min,max){
max = max === undefined ? min - (min = 0) : max;
return Math.floor(Math.random() * (max - min) + min);
}
randInt(100); // int 0 - 100
randInt(10,20); // int 10-20
randInt(-100); // int -100 to 0
randInt(-10,20); // int -10 to 20
this.xv = randInt(-particlesMinSpeed, particlesMaxSpeed);
this.yv = randInt(-particlesMinSpeed, particlesMaxSpeed);
this.size = randInt(particlesMinSize, particlesMaxSize);
And if you are using the same name in variables a good sign to create an object
var particlesPerExplosion = 20;
var particlesMinSpeed = 3;
var particlesMaxSpeed = 6;
var particlesMinSize = 1;
var particlesMaxSize = 3;
Could be
const settings = {
particles : {
speed : {min : 3, max : 6 },
size : {min : 1 : max : 3 },
explosionCount : 20,
},
background : "#000",
}
Anyways your code.
var c = canvas;
var ctx = c.getContext('2d');
// Set full-screen
c.width = innerWidth;
c.height = innerHeight;
// Options
var background = '#333'; // Background color
var particlesPerExplosion = 20;
var particlesMinSpeed = 3;
var particlesMaxSpeed = 6;
var particlesMinSize = 1;
var particlesMaxSize = 3;
var explosions = [];
var fps = 60;
var now, delta;
var then = 0; // Zero start time
var interval = 1000 / fps;
// Optimization for mobile devices
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
fps = 29;
}
// Draw
// as time is passed you need to start with requestAnimationFrame
requestAnimationFrame(draw);
function draw(time) { //requestAnimationFrame frame passes the time
requestAnimationFrame(draw);
delta = time - then;
if (delta > interval) {
then = time
drawBackground();
drawExplosion();
}
}
// Draw explosion(s)
function drawExplosion() {
if (explosions.length == 0) {
return;
}
for (var i = 0; i < explosions.length; i++) {
var explosion = explosions[i];
var particles = explosion.particles;
if (particles.length == 0) {
explosions.splice(i, 1);
//return;
continue;
}
for (var ii = 0; ii < particles.length; ii++) {
var particle = particles[ii];
// Check particle size
// If 0, remove
if (particle.size < 0) {
particles.splice(ii, 1);
// return;
continue;
}
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, Math.PI * 2, 0, false);
ctx.closePath();
ctx.fillStyle = 'rgb(' + particle.r + ',' + particle.g + ',' + particle.b + ')';
ctx.fill();
// Update
particle.x += particle.xv;
particle.y += particle.yv;
particle.size -= .1;
}
}
}
// Draw the background
function drawBackground() {
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
}
// Clicked
function clicked(e) {
var xPos, yPos;
if (e.offsetX) {
xPos = e.offsetX;
yPos = e.offsetY;
} else if (e.layerX) {
xPos = e.layerX;
yPos = e.layerY;
}
explosions.push(new explosion(xPos, yPos));
}
// Explosion
function explosion(x, y) {
this.particles = [];
for (var i = 0; i < particlesPerExplosion; i++) {
this.particles.push(new particle(x, y));
}
}
// Particle
function particle(x, y) {
this.x = x;
this.y = y;
this.xv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.yv = randInt(particlesMinSpeed, particlesMaxSpeed, false);
this.size = randInt(particlesMinSize, particlesMaxSize, true);
this.r = randInt(113, 222);
this.g = '00';
this.b = randInt(105, 255);
}
// Returns an random integer, positive or negative
// between the given value
function randInt(min, max, positive) {
if (positive == false) {
var num = Math.floor(Math.random() * max) - min;
num *= Math.floor(Math.random() * 2) == 1 ? 1 : -1;
} else {
var num = Math.floor(Math.random() * max) + min;
}
return num;
}
// On-click
$('canvas').on('click', function(e) {
clicked(e);
});
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>
I am creating an interactive game and am very new to programming. I was wondering how exactly to increment a variable and then put it into an alert box. I want to find the calculation of foodCaught and foodWasted and display it in an alert box at the end of my game. Also how do I make it so it is on a timer and at the end of this timer the alert box with foodCaught and foodWasted appears?
$(document).ready(function(){
var cnv = $("#myCanvas")[0];
var ctx = cnv.getContext("2d");
var catcherX = ctx.canvas.width/2;
var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position
var numFoods = 5;
var catcherSpeed = 30;
var foodCaught = 0;
var foodWasted = 0;
function Food(){ // the name of the constructor usually begins with a captial letter
this.radius = 30;
this.x = Math.floor(Math.random()*ctx.canvas.width);
this.y = 0 - this.radius;
this.speed = 1+ Math.floor(Math.random()*5);
var imageToUse = new Image();
this.width = 50; // default values
this.height = 50; // default values
var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image
if(randomNum == 0){
imageToUse.src = "corn.png";
this.width = 27; // width of corn.png
this.height = 100; // height of corn.png
} else if(randomNum == 1){
imageToUse.src = "straw.png"
this.width = 83; // width of straw.png
this.height = 100; // height of straw.png
}
this.moveFood = function(){
if(this.y > ctx.canvas.height){
this.x = Math.floor(Math.random()*ctx.canvas.width);
this.y = 0;
footWasted += 1;
}
this.y += this.speed; // add speed to location
}
this.drawFood = function() {
ctx.drawImage(imageToUse, this.x, this.y);
}
this.intersectFood = function(targetX, targetY, targetR) {
if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){
foodCaught += 1;
return true;
}
/*
var distanceX = this.x - targetX;
var distanceY = this.y - targetY;
var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
if(distance < targetR + this.radius){
return true;
}
*/
}
}
// create an Array of Foods
var FoodArray = new Array();
for(var i=0; i<numFoods; i++) {
FoodArray[i] = new Food();
}
// get mouse Postion
$(document).keydown(function(e){ // attach the event to the entire document
switch(e.keyCode){
case 37: // left
catcherX-= catcherSpeed;
break;
case 39: // right
catcherX+= catcherSpeed;
break;
}
});
var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds
var counter = 0;
function gameLoop(){
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
for(var i=0; i < FoodArray.length; i++) {
FoodArray[i].moveFood();
FoodArray[i].drawFood();
if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
FoodArray.splice(i,1);
console.log(i);
}
}
// draw catcher
ctx.beginPath();
ctx.fillStyle="#119933";
ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
Updated Answer
After your game has ended, do:
alert("foodCaught = " + foodCaught + "<br>foodWasted = " + foodWasted);
Just make sure that this alert is withing the scope of foodCaught and foodWasted variables.
EDIT:
Your game is actually never ending. The setInterval that you keeps calling gameLoop() every 10 milliseconds, ENDLESSLY!
To keep a track of foodCaught and foodWasted variables, add a console.log() statement at the end of gameLoop() function as shown in the code below:
function gameLoop(){
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
for(var i=0; i < FoodArray.length; i++) {
FoodArray[i].moveFood();
FoodArray[i].drawFood();
if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
FoodArray.splice(i,1);
//console.log(i);
}
}
// draw catcher
ctx.beginPath();
ctx.fillStyle="#119933";
ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
console.log("foodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted);
}
With this, you will get the values of foodCaught and foodWasted variables everytime the gameLoop function is called.
If you are unaware of how to use the console, checkout this post.
EDIT2:
I have an idea about ending this game. In the updated code below, I have set the game to run for 10 seconds (just as an example so you can change it quickly) using setTimeout(). You have change it to any duration that you want. In setTimeout(), I am also alerting the values that you need.
Here is the updated Javascript/jQuery code:
$(document).ready(function(){
var cnv = $("#myCanvas")[0];
var ctx = cnv.getContext("2d");
var catcherX = ctx.canvas.width/2;
var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position
var numFoods = 5;
var catcherSpeed = 30;
var foodCaught = 0;
var foodWasted = 0;
function Food(){ // the name of the constructor usually begins with a captial letter
this.radius = 30;
this.x = Math.floor(Math.random()*ctx.canvas.width);
this.y = 0 - this.radius;
this.speed = 1+ Math.floor(Math.random()*5);
var imageToUse = new Image();
this.width = 50; // default values
this.height = 50; // default values
var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image
if(randomNum == 0){
imageToUse.src = "corn.png";
this.width = 27; // width of corn.png
this.height = 100; // height of corn.png
} else if(randomNum == 1){
imageToUse.src = "straw.png"
this.width = 83; // width of straw.png
this.height = 100; // height of straw.png
}
this.moveFood = function(){
if(this.y > ctx.canvas.height){
this.x = Math.floor(Math.random()*ctx.canvas.width);
this.y = 0;
foodWasted += 1;
}
this.y += this.speed; // add speed to location
}
this.drawFood = function() {
ctx.drawImage(imageToUse, this.x, this.y);
}
this.intersectFood = function(targetX, targetY, targetR) {
if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){
foodCaught += 1;
return true;
}
/*
var distanceX = this.x - targetX;
var distanceY = this.y - targetY;
var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
if(distance < targetR + this.radius){
return true;
}
*/
}
}
function gameLoop(){
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
for(var i=0; i < FoodArray.length; i++) {
FoodArray[i].moveFood();
FoodArray[i].drawFood();
if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
FoodArray.splice(i,1);
}
}
// draw catcher
ctx.beginPath();
ctx.fillStyle="#119933";
ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
}
$(document).keydown(function(e){ // attach the event to the entire document
switch(e.keyCode){
case 37: // left
catcherX-= catcherSpeed;
break;
case 39: // right
catcherX+= catcherSpeed;
break;
}
});
// create an Array of Foods
var FoodArray = new Array();
for(var i=0; i<numFoods; i++) {
FoodArray[i] = new Food();
}
var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds
setTimeout(function(){
clearInterval(interval);
alert("Time UP!\n\nfoodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted);
}, 10000);
});
I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>
I have been reading/searching for an answer to detect collisions of sprites in two arrays. I am not understanding how to pass two arrays into the detection function and have it check all contents of each array against each other. Any input would be greatly appreciated.
<script type="text/javascript">
var FIRE = 0;
var NORTH = 38;
var SOUTH = 40;
var EAST = 39;
var WEST = 37;
var destX = 350;
var destY = 500;
var canvas = null;
var context = null;
var sprites = null;
var player = null;
var island = null;
var enemies = [];
var fires = [];
var gameLoopInterval = null;
var offScreenFire = null;
var isShooting = false;
var intersect = null;
var Fire = function() {
this.spriteX = 278;
this.spriteY = 110;
this.spriteWidth = 13;
this.spriteHeight = 16;
this.destX = player.destX + 25;
this.destY = player.destY;
this.speed = 5;
}
var Player = function(name) {
this.name = name;
this.spriteX = 5;
this.spriteY = 400;
this.spriteWidth = 64;
this.spriteHeight = 64;
this.destX = 350;
this.destY = 500;
this.speed = 5;
this.level = 1;
}
var Enemy = function() {
this.spriteX = 4;
this.spriteY = 4;
this.spriteWidth = 32;
this.spriteHeight = 32;
this.destX = Math.ceil(Math.random() * (800 - this.spriteWidth));
this.destY = this.spriteWidth;
this.speed = Math.ceil(Math.random() * 5);
}
var Island = function() {
this.spriteX = 168;
this.spriteY = 500;
this.spriteWidth = 64;
this.spriteHeight = 64;
this.destX = Math.ceil(Math.random() * (800 - this.spriteWidth));
this.destY = this.spriteWidth - 64;
this.speed = 2;
}
Fire.prototype.takeTurn = function() {
var intersect;
var projdestX = this.destX;
var projdestY = this.destY;
var projspriteWidth = this.spriteWidth;
var projspriteHeight = this.spriteHeight;
for (enemy in enemies) {
intersect = intersect || intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
if(intersect == true) { alert("colliding"); }
else{drawImage(this);}
// if (intersect != true){
// drawImage(this);
// }
// else {
// alert("boom");
// }
if(this.destY <= 0){
offScreenFire = fires.indexOf(this);
fires.splice(offScreenFire, 1);
}
else
this.destY -= this.speed;
}
Player.prototype.takeTurn = function() {
drawImage(this);
}
Enemy.prototype.takeTurn = function() {
drawImage(this);
if (this.destY < canvas.height)
this.destY += this.speed;
else
this.destY = -32;
}
Island.prototype.takeTurn = function() {
drawImage(this);
this.destY += this.speed;
}
function fireAction() {
var fire = new Fire();
drawImage(fire);
fires.push(fire);
}
function drawImage(sprite) {
context.drawImage(sprites, sprite.spriteX, sprite.spriteY, sprite.spriteWidth, sprite.spriteHeight, sprite.destX, sprite.destY, sprite.spriteWidth, sprite.spriteHeight );
}
function gameLoop () {
context.clearRect(0, 0, canvas.width, canvas.height);
island.takeTurn();
player.takeTurn();
//console.log(fires); //debug
for (fire in fires) {
fires[fire].takeTurn();
}
for (enemy in enemies) {
enemies[enemy].takeTurn();
}
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2)
return false;
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2)
return false;
}
return true;
}
window.onload = function() {
//alert('here');
canvas = document.getElementById('gameWorld');
context = canvas.getContext("2d");
sprites = new Image();
player = new Player('Brad');
island = new Island();
sprites.onload = function() {
drawImage(player);
for (i = 0; i < 3; i++) {
var enemy = new Enemy();
drawImage(enemy);
enemies.push(enemy);
}
}
sprites.src = "Sprites/1945.png";
gameLoopInterval = setInterval('gameLoop()', 100)
}
window.onkeypress = function(e){
var evt = window.event ? event : e;
//alert(evt.keyCode);
switch(evt.keyCode) {
case NORTH:
if (player.destY > 0)
player.destY -= player.speed;
else
player.destY == player.destY;
break;
case SOUTH:
if (player.destY < canvas.height - player.spriteWidth)
player.destY += player.speed;
else
player.destY == player.destY;
break;
case EAST:
if (player.destX < canvas.width - player.spriteWidth)
player.destX += player.speed;
else
player.destX == player.destY;
break;
case WEST:
if (player.destX > 0)
player.destX -= player.speed;
else
player.destX == player.destX;
break;
case FIRE:
fireAction();
break;
}
}
</script>
Your problems seems to be in:
for (enemy in enemies) {
intersect = intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
intersect will always have the last value saved. (Meaning you are really only checking if it intersects with the last enemy.)
A quick solution would be to change the inner line to:
intersect = intersect || intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
This will make intersect stay as true if the fire doesn't intersect with the next enemy.
Edit:
Your second problem is in the same for(). In javascript, when you do a for in, the first variable does not have a reference to the instance, but rather is only the key.
Your final for should look like:
for (enemy in enemies) {
intersect = intersect || intersects(enemies[enemy].destX, enemies[enemy].destY, enemies[enemy].spriteWidth, enemies[enemy].spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
You also seem to not be spawning any enemies. In my fiddle of your code (http://jsfiddle.net/path411/umjnQ/) I added the following snippet into your gameLoop():
if(enemies.length < 1) {
enemies.push(new Enemy());
}
This simply creates a new enemy if you don't already have one. (You will probably want to change later).