This snake style game is opened in a popup when you click a button on a page, then you are given a start screen and instructions, you click start to begin the game, and when you lose it displays your score and some text, if you close the popup and reopen it, it still shows the score rather than the start screen.
How do I make it reset when the popup is closed?
jQuery(document).ready(function($) {
$("#canvas").addClass("displayNone");
$("#lose").addClass("displayNone");
$("#post").removeClass("displayNone");
$("#controls").removeClass("displayNone");
$('#play').on('click', function() {
$('#playdiv').addClass('show-game');
})
var canvas = $("#canvas")[0];;
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var cw = 10;
var d;
var food;
var score;
var snake_array;
$("#score").addClass("displayNone");
$("#start").click(function() {
$("#start").addClass("displayNone");
$("#lose").addClass("displayNone");
$("#post").addClass("displayNone");
$("#canvas").removeClass("displayNone");
init();
})
var keys = [];
window.addEventListener("keydown",
function(e) {
keys[e.keyCode] = true;
switch (e.keyCode) {
case 37:
case 39:
case 38:
case 40:
case 32:
e.preventDefault();
break;
default:
break;
}
},
false);
window.addEventListener('keyup',
function(e) {
keys[e.keyCode] = false;
},
false);
// was here
function init() {
d = "right";
create_snake();
create_food();
score = 0;
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 90);
}
// init();
function create_snake() {
var length = 5;
snake_array = [];
for (var i = length - 1; i >= 0; i--) {
snake_array.push({
x: i,
y: 0
});
}
}
function create_food() {
food = {
x: Math.round(Math.random() * (w - cw) / cw),
y: Math.round(Math.random() * (h - cw) / cw),
};
}
function paint() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if (d == "right") nx++;
else if (d == "left") nx--;
else if (d == "up") ny--;
else if (d == "down") ny++;
if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || check_collision(nx, ny, snake_array)) {
document.querySelector('#score').innerText = 'Your score: ' + score;
$("#score").removeClass("displayNone");
$("#lose").removeClass("displayNone");
$("#start").removeClass("displayNone");
$("#canvas").addClass("displayNone");
//init();
return;
}
if (nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};
score++;
create_food();
} else {
var tail = snake_array.pop();
tail.x = nx;
tail.y = ny;
}
snake_array.unshift(tail);
for (var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
paint_cell(c.x, c.y);
}
paint_cell(food.x, food.y);
var score_text = "Score: " + score;
ctx.fillText(score_text, 5, h - 5);
}
function paint_cell(x, y) {
ctx.fillStyle = "pink";
ctx.fillRect(x * cw, y * cw, cw, cw);
ctx.strokeStyle = "red";
ctx.strokeRect(x * cw, y * cw, cw, cw);
}
function check_collision(x, y, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].x == x && array[i].y == y) return true;
}
return false;
}
$(document).keydown(function(e) {
var key = e.which;
if (key == "37" && d != "right") d = "left";
else if (key == "38" && d != "down") d = "up";
else if (key == "39" && d != "left") d = "right";
else if (key == "40" && d != "up") d = "down";
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> unknown HTML please post it here</div>
Seems like you never clean setInterval on exit. Please try to clearInterval. Attach to the window, not local valriable.
const window.timerId = setInterval(init, 9000)
// On init
if (window.game_loop != "undefined") clearInterval(game_loop);
window.game_loop = setInterval(paint, 90);
Related
I've been trying to figure out how I can add a play again button to refresh the page after a player has lost. This is a classic snake game. I followed a tutorial on it and but they never said anything about a Play Again button. Any help would be appreciated. Nothing too complicated though please, I'm still learning.
const ctx = canvas.getContext("2d");
class SnakePart {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let speed = 7;
let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;
let headX = 10;
let headY = 10;
const snakeParts = [];
let tailLength = 2;
let appleX = 5;
let appleY = 5;
let inputsXVelocity = 0;
let inputsYVelocity = 0;
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
const gulpSound = new Audio("gulp.mp3");
//game loop
function drawGame() {
xVelocity = inputsXVelocity;
yVelocity = inputsYVelocity;
changeSnakePosition();
let result = isGameOver();
if (result) {
return;
}
clearScreen();
checkAppleCollision();
drawApple();
drawSnake();
drawScore();
if (score > 5) {
speed = 9;
}
if (score > 10) {
speed = 11;
}
setTimeout(drawGame, 1000 / speed);
}
function isGameOver() {
let gameOver = false;
if (yVelocity === 0 && xVelocity === 0) {
return false;
}
//walls
if (headX < 0) {
gameOver = true;
} else if (headX === tileCount) {
gameOver = true;
} else if (headY < 0) {
gameOver = true;
} else if (headY === tileCount) {
gameOver = true;
}
for (let i = 0; i < snakeParts.length; i++) {
let part = snakeParts[i];
if (part.x === headX && part.y === headY) {
gameOver = true;
break;
}
}
if (gameOver) {
ctx.fillStyle = "white";
ctx.font = "50px Verdana";
if (gameOver) {
ctx.fillStyle = "white";
ctx.font = "50px Verdana";
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", " magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
}
ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
}
return gameOver;
}
function drawScore() {
ctx.fillStyle = "white";
ctx.font = "10px Verdana";
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 = "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 an item at the end of the list next to the head
while (snakeParts.length > tailLength) {
snakeParts.shift(); // remove the furthet item from the snake parts if have more than our tail size.
}
ctx.fillStyle = "orange";
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize);
}
function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}
function drawApple() {
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}
function checkAppleCollision() {
if (appleX === headX && appleY == headY) {
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
tailLength++;
score++;
gulpSound.play();
}
}
document.body.addEventListener("keydown", keyDown);
function keyDown(event) {
//up
if (event.keyCode == 38 || event.keyCode == 87) {
//87 is w
if (inputsYVelocity == 1) return;
inputsYVelocity = -1;
inputsXVelocity = 0;
}
//down
if (event.keyCode == 40 || event.keyCode == 83) {
// 83 is s
if (inputsYVelocity == -1) return;
inputsYVelocity = 1;
inputsXVelocity = 0;
}
//left
if (event.keyCode == 37 || event.keyCode == 65) {
// 65 is a
if (inputsXVelocity == 1) return;
inputsYVelocity = 0;
inputsXVelocity = -1;
}
//right
if (event.keyCode == 39 || event.keyCode == 68) {
//68 is d
if (inputsXVelocity == -1) return;
inputsYVelocity = 0;
inputsXVelocity = 1;
}
}
drawGame();```
The easiest way to refresh the page would be just:
window.location.reload(false)
Source:
https://www.freecodecamp.org/news/location-reload-method-how-to-reload-a-page-in-javascript/
I would suggest that simply reloading the page is not a great way to implement a play again feature but I appreciate the creativity of it.
I was making a snake game. I have a basic game but I wanted to move the snake more smoothly and specially I wanted to turn the direction of the snake more smoothly.
The problem until now is that I have been removing the tail of the snake and adding it to the head for the movement part.
Moving the snake smoothly is rather easy by reducing the interval for calling the draw function and incrementing the x and y values by small amounts but what I am having problem is with turning the snake smoothly,it is exactly where I am lost/confused as to how to do it like done here (only the turning of snake part and not the changing of head when snake gets blocked)
can anyone help out please? here is my code:
let cvs = "";
let ctx = "";
let size = [];
var direction = 'b';
var speed = 200;
//moving lines on arrow click
window.addEventListener("keydown", moveSomething, false);
function moveSomething(e) {
switch (e.keyCode) {
case 37:
//left
if (direction != 'r') {
direction = 'l';
}
break;
case 38:
//up
if (direction != 'b') {
direction = 't';
}
break;
case 39:
//right
if (direction != 'l') {
direction = 'r';
}
break;
case 40:
//bottom
if (direction != 't') {
direction = 'b';
}
break;
}
}
let food = {
x: Math.floor(Math.random() * 220),
y: Math.floor(Math.random() * 400),
s: 20,
draw: function() {
//this if block rounds off the x and y values
if ((this.x % 20) != 0 || (this.y % 20) != 0) {
if ((this.x % 20) != 0) {
let e = this.x % 20;
e = 20 - e;
this.x = this.x + e;
}
if ((this.y % 20) != 0) {
let e = this.y % 20;
e = 20 - e;
this.y = this.y + e;
}
};
ctx.fillStyle = "red";
ctx.fillRect(this.x, this.y, this.s, this.s);
},
newfood: function() {
this.x = Math.floor(Math.random() * 220);
this.y = Math.floor(Math.random() * 400);
this.draw();
}
}
const snake = {
s: 20,
draw: function(x, y) {
ctx.fillStyle = "green";
ctx.fillRect(this.s * x, this.s * y, this.s, this.s);
ctx.strokeStyle = "black";
ctx.strokeRect(this.s * x, this.s * y, this.s, this.s);
},
snakeInit: function() {
for (let i = 8; i >= 4; i--) {
size.push({
x: i,
y: 6
})
}
},
callDraw: function() {
for (let i = 0; i < size.length; i++) {
this.draw(size[i].x, size[i].y);
}
},
move: function() {
var snakeX = size[0].x;
var snakeY = size[0].y;
if (direction == 'r') {
snakeX++;
} else if (direction == 'l') {
snakeX--;
} else if (direction == 't') {
snakeY--;
} else if (direction == 'b') {
snakeY++;
}
//console.log("Inside move1", speed);
if (snakeX == -1 || snakeX == cvs.width / this.s || snakeY == -1 || snakeY == Math.floor(cvs.height / this.s) || this.checkSelfCollision(snakeX, snakeY, size)) {
ctx.clearRect(0, 0, cvs.width, cvs.height);
gameloop = clearInterval(gameloop);
return;
} else {
ctx.clearRect(0, 0, cvs.width, cvs.height);
food.draw();
}
if (snakeX * 20 == food.x && snakeY * 20 == food.y) {
var tail = {
x: snakeX,
y: snakeY
};
food.eaten();
speed += 200;
food.newfood();
} else {
var tail = size.pop();
tail.x = snakeX;
tail.y = snakeY;
}
size.unshift(tail);
for (let i = 0; i < size.length; i++) {
this.draw(size[i].x, size[i].y);
}
},
checkSelfCollision: function(x, y, arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].x == x && arr[i].y == y) {
return true;
}
}
return false;
}
}
function loop() {
const cvsL = document.getElementById("snakes");
const ctxL = cvsL.getContext('2d');
cvs = cvsL;
ctx = ctxL;
snake.snakeInit();
snake.callDraw();
food.draw();
gameloop = setInterval(function() {
snake.move();
}, speed);
}
<body onload="loop();">
<canvas id="snakes" width=240px height=420px style="border: 1px solid black;display: block;"></canvas>
</body>
I would like to add a leaderboard to this game so you can enter your name at the end and scores are recorded.
Failing that just displaying the users score at the end rather than it just reverting to the "start game" button automatically would suffice.
Id also like to add touch capability for mobiles/tablets.
Ive copied the code below along with a jsfiddle.
https://jsfiddle.net/goktxe84/
<button id="start">Start Game</button>
<canvas id="canvas" width="300" height="300"></canvas>
display:none;
}
button{
height:20px;
width:100px;
margin: -20px -50px;
position:relative;
top:50%;
left:50%;
}
$(document).ready(function() {
$("#canvas").addClass("displayNone");
$("#start").click(function(){
$("#start").addClass("displayNone");
$("#canvas").removeClass("displayNone");
})
var keys = [];
window.addEventListener("keydown",
function(e){
keys[e.keyCode] = true;
switch(e.keyCode){
case 37: case 39: case 38: case 40:
case 32: e.preventDefault(); break;
default: break;
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.keyCode] = false;
},
false);
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var cw = 10;
var d;
var food;
var score;
var snake_array;
function init() {
d = "right";
create_snake();
create_food();
score = 0;
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 90);
}
init();
function create_snake() {
var length = 5;
snake_array = [];
for (var i = length - 1; i >= 0; i--) {
snake_array.push({
x: i,
y: 0
});
}
}
function create_food() {
food = {
x: Math.round(Math.random() * (w - cw) / cw),
y: Math.round(Math.random() * (h - cw) / cw),
};
}
function paint() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if (d == "right") nx++;
else if (d == "left") nx--;
else if (d == "up") ny--;
else if (d == "down") ny++;
if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || check_collision(nx, ny, snake_array)) {
$("#start").removeClass("displayNone");
$("#canvas").addClass("displayNone");
init();
return;
}
if (nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};
score++;
create_food();
}
else {
var tail = snake_array.pop();
tail.x = nx;
tail.y = ny;
}
snake_array.unshift(tail);
for (var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
paint_cell(c.x, c.y);
}
paint_cell(food.x, food.y);
var score_text = "Score: " + score;
ctx.fillText(score_text, 5, h - 5);
}
function paint_cell(x, y) {
ctx.fillStyle = "pink";
ctx.fillRect(x * cw, y * cw, cw, cw);
ctx.strokeStyle = "red";
ctx.strokeRect(x * cw, y * cw, cw, cw);
}
function check_collision(x, y, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].x == x && array[i].y == y) return true;
}
return false;
}
$(document).keydown(function(e) {
var key = e.which;
if (key == "37" && d != "right") d = "left";
else if (key == "38" && d != "down") d = "up";
else if (key == "39" && d != "left") d = "right";
else if (key == "40" && d != "up") d = "down";
})
})
for show latest result add html element, where you can show it
<button id="start">Start Game</button>
<canvas id="canvas" width="300" height="300"></canvas>
<span id="score"></span>
and change text on this element, when you lose (line 79)
...
if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || check_collision(nx, ny, snake_array)) {
document.querySelector('#score').innerText = 'Your latest score = ' + score;
$("#start").removeClass("displayNone");
...
I recently made this game and wanted to ask how to improve it. I made an alert box inside the javascript for when the game ends. It works but it's not beautiful. so I wanted to ask how can I change the Color and the message on the top of the alert box? right now a webpage message has been written.
And I wanted to add that it could be played from the phone something like the arrow buttons. I found something for java but nothing for javascript and wanted to know if its possible and how do I doit?
here is the code:
<html>
<head>
<meta charset='utf-8'/>
<link rel="stylesheet" href="css/style.css">
<h1> <p align="left"><font color="rebeccapurple"> Snake developed by agente00mcm </font></p> </h1>
</head>
<body>
<div class= 'game'>
<div id = 'home'>
<canvas id='mycanvas' width='800' height='800'>
</canvas>
</div>
<p>Press start to start the game!</p>
<button id='btn'>START</button>
</div>
<script>
var mycanvas = document.getElementById('mycanvas');
var ctx = mycanvas.getContext('2d');
var snakeSize = 10;
var w = 800;
var h = 800;
var score = 0;
var snake;
var snakeSize = 10;
var food;
var drawModule = (function () {
var bodySnake = function(x, y) {
ctx.fillStyle = 'green';
ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
}
var pizza = function(x, y) {
ctx.fillStyle = 'yellow';
ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
ctx.fillStyle = 'red';
ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2);
}
var scoreText = function() {
var score_text = "Score: " + score;
ctx.fillStyle = 'blue';
ctx.fillText(score_text, 145, h-5);
}
var drawSnake = function() {
var length = 4;
snake = [];
for (var i = length-1; i>=0; i--) {
snake.push({x:i, y:0});
}
}
var paint = function(){
ctx.fillStyle = 'lightgray';
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = 'black';
ctx.strokeRect(0, 0, w, h);
btn.setAttribute('disabled', true);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
if (direction == 'right') {
snakeX++; }
else if (direction == 'left') {
snakeX--; }
else if (direction == 'up') {
snakeY--;
} else if(direction == 'down') {
snakeY++; }
if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) {
//restart game
alert("Game Over \nYour Score: "+score);
document.location.reload();
btn.removeAttribute('disabled', true);
ctx.clearRect(0,0,w,h);
gameloop = clearInterval(gameloop);
return;
}
if(snakeX == food.x && snakeY == food.y) {
var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail
score ++;
createFood(); //Create new food
} else {
var tail = snake.pop(); //pops out the last cell
tail.x = snakeX;
tail.y = snakeY;
}
//The snake can now eat the food.
snake.unshift(tail); //puts back the tail as the first cell
for(var i = 0; i < snake.length; i++) {
bodySnake(snake[i].x, snake[i].y);
}
pizza(food.x, food.y);
scoreText();
}
var createFood = function() {
food = {
x: Math.floor((Math.random() * 30) + 1),
y: Math.floor((Math.random() * 30) + 1)
}
for (var i=0; i>snake.length; i++) {
var snakeX = snake[i].x;
var snakeY = snake[i].y;
if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) {
food.x = Math.floor((Math.random() * 30) + 1);
food.y = Math.floor((Math.random() * 30) + 1);
}
}
}
var checkCollision = function(x, y, array) {
for(var i = 0; i < array.length; i++) {
if(array[i].x === x && array[i].y === y)
return true;
}
return false;
}
var init = function(){
direction = 'down';
drawSnake();
createFood();
gameloop = setInterval(paint, 80);
}
return {
init : init
};
}());
(function (window, document, drawModule, undefined) {
var btn = document.getElementById('btn');
btn.addEventListener("click", function(){ drawModule.init();});
document.onkeydown = function(event) {
keyCode = window.event.keyCode;
keyCode = event.keyCode;
switch(keyCode) {
case 37:
if (direction != 'right') {
direction = 'left';
}
console.log('left');
break;
case 39:
if (direction != 'left') {
direction = 'right';
console.log('right');
}
break;
case 38:
if (direction != 'down') {
direction = 'up';
console.log('up');
}
break;
case 40:
if (direction != 'up') {
direction = 'down';
console.log('down');
}
break;
}
}
})(window, document, drawModule);
</script>
</body>
</html>
and besides the Problem I wanted to ask how do you guys find it and if it Needs any improvement beside the alert box style.
thanks for your support!
The alert box is a system object and cannot be styled with css. You need to create an element in your page that replicates the behavior of the alert if you want to style it. You can find plenty of libraries that do this such as:
SweetAlert
jQueryUi dialog
AlertifyJs
Have fun developing games :)
So, I have a little "move around and stuff" engine, which is very primative at the moment.
Every so often (timer based) another pixel (5x5) will appear on the screen - if you intersect with that pixel, I would like to fire an event. (To be fair, that pixel (5x5) needs to be a hella-lot bigger :/ ).
So, here is my JSFiddle (for you fiddlers):
http://jsfiddle.net/neuroflux/q9APG/
And here is my javascript for the canvas:
var canvas, ctx;
var pixX = 0; //positions
var pixY = 0;
var endX = 0;
var endY = 0;
var youX = 5; //sizes
var youY = 5;
var dis = 1; //timings
var p = 0;
window.onload = function() {
init();
}
function init() {
canvas = document.getElementById('main');
ctx = canvas.getContext('2d');
setInterval(loop,40);
var pixTimer = Math.floor((Math.random() * 1000) * 10) + 1;
setInterval(addPixel, pixTimer);
document.addEventListener('keydown',function(e) {
runMove(e);
});
}
function addPixel() {
pX = Math.floor(Math.random() * 800) + 1;
pY = Math.floor(Math.random() * 600) + 1;
p++;
}
function loop() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(pixX,pixY,youX,youY);
ctx.fillText(pixX + ':' + pixY, 5, 500);
if (p > 0) {
for (var a = 0; a <= p; a++) {
ctx.fillRect(pX,pY,5,5);
}
}
}
function runMove(e) {
var canvas = document.getElementById('main');
ky = e.keyCode;
switch(ky) {
case 37:
endX = endX - dis;
if (pixX == endX) {
} else {
if (pixX >= 0 && pixX < canvas.width) {
moveleft = setInterval(ml,10);
function ml() { pixX--; }
} else {
pixX = 0;
}
}
return false;
case 38:
endY = endY - dis;
if (pixY == endY) {
} else {
if (pixY >= 0 && pixY < canvas.height) {
moveup = setInterval(mu,10);
function mu() { pixY--; }
}
}
return false;
case 39:
endX = endX + dis;
if (pixX == endX) {
} else {
if (pixX >= 0 && pixX < canvas.width) {
moveright = setInterval(mr,10);
function mr() { pixX++; }
}
}
return false;
case 40:
endY = endY + dis;
if (pixY == endY) {
} else {
if (pixY >= 0 && pixY < canvas.height) {
movedown = setInterval(md,10);
function md() { pixY++; }
}
}
return false;
case 80:
growing = setInterval(grow,100);
clearInterval(shrinking);
function grow() {
youX = youX + dis;
youY = youY + dis;
}
return false;
case 73:
clearInterval(shrinking);
clearInterval(growing);
return false;
case 79:
shrinking = setInterval(shrink,100);
clearInterval(growing);
function shrink() {
youX = youX - dis;
youY = youY - dis;
}
return false;
default:
return false;
}
}
I have already tried this, but got issues :( (nothing would fire):
JSFiddle: http://jsfiddle.net/neuroflux/uF5kj/
Canvas Code:
var canvas, ctx;
var pixX = 0; //positions
var pixY = 0;
var endX = 0;
var endY = 0;
var youX = 5; //sizes
var youY = 5;
var dis = 1; //timings
var p = 0;
var pixel = new Array();
window.onload = function() {
init();
}
function init() {
canvas = document.getElementById('main');
ctx = canvas.getContext('2d');
setInterval(loop,40);
var pixTimer = Math.floor((Math.random() * 1000) * 10) + 1;
setInterval(addPixel, pixTimer);
document.addEventListener('keydown',function(e) {
runMove(e);
});
}
function addPixel() {
pX = Math.floor(Math.random() * 800) + 1;
pY = Math.floor(Math.random() * 600) + 1;
p++;
}
function loop() {
ctx.clearRect(0,0,canvas.width,canvas.height);
var bgImg = new Image();
bgImg.src = 'bg.png';
ctx.drawImage(bgImg,0,0,800,600);
ctx.fillRect(pixX,pixY,youX,youY);
ctx.fillText(pixX + ':' + pixY, 5, 500);
if (p > 0) {
for (var a = 0; a <= p; a++) {
pixel[a] = ctx.fillRect(pX,pY,5,5);
}
}
}
function checkIntersections() {
for (var x = 0; x < pixel.length; x++) {
if (pixX == pixel[x].x) { alert(0) }
}
}
function runMove(e) {
var canvas = document.getElementById('main');
ky = e.keyCode;
switch(ky) {
case 37:
endX = endX - dis;
if (pixX == endX) {
} else {
if (pixX >= 0 && pixX < canvas.width) {
moveleft = setInterval(ml,10);
function ml() { pixX--; }
} else {
pixX = 0;
}
}
return false;
case 38:
endY = endY - dis;
if (pixY == endY) {
} else {
if (pixY >= 0 && pixY < canvas.height) {
moveup = setInterval(mu,10);
function mu() { pixY--; }
}
}
checkIntersections();
return false;
case 39:
endX = endX + dis;
if (pixX == endX) {
} else {
if (pixX >= 0 && pixX < canvas.width) {
moveright = setInterval(mr,10);
function mr() { pixX++; }
}
}
checkIntersections();
return false;
case 40:
endY = endY + dis;
if (pixY == endY) {
} else {
if (pixY >= 0 && pixY < canvas.height) {
movedown = setInterval(md,10);
function md() { pixY++; }
}
}
checkIntersections();
return false;
case 80:
growing = setInterval(grow,100);
clearInterval(shrinking);
function grow() {
youX = youX + dis;
youY = youY + dis;
}
checkIntersections();
return false;
case 73:
clearInterval(shrinking);
clearInterval(growing);
return false;
case 79:
shrinking = setInterval(shrink,100);
clearInterval(growing);
function shrink() {
youX = youX - dis;
youY = youY - dis;
}
return false;
default:
return false;
}
}
Wait, so all you want is a function to see if two rectangles intersect?
Here's a bulletproof function for you:
// returns true if there is any overlap
// params: x,y,w,h of two rectangles
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;
}
You'd be better off with circles, since the distance can more easily be calculated (fixed radius). Say you set radius to 10, then if distance < 20 they are inside each other, i.e. there is collison.
// Pythagoras theorem to calculate distance between 2 points
function does_collide(x1, y1, x2, y2) {
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) < 20;
}
Each time, calculate distance between user / object:
if(does_collide(pixX, pixY, pX, pY)) {
ctx.fillText('collison!#', 0, 10);
collison = true;
} else {
collison = false;
}
At any time, the collison variable can be used for checking whether there is collison.
You can draw a circle using:
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.fill();
http://jsfiddle.net/q9APG/4/