Function works only sometimes. How could this be? - javascript

In my snake game I am trying to catch the y-coordinate of a rectangle (food).
Now check out this function:
function eat() {
console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (y == food_position_y) {
throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
Pretty simple, huh?
Now the weird thing about this story is: y is not always equal food_position_y!
You may want to check the full script:
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 2;
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width);
food_position_y = Math.floor(Math.random() * canvas.height);
function eat() {
console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (y == food_position_y) {
throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, 10, 10);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
}
break;
}
});
})();
What do I mean by "y is not always equal food_position_y"?
Please go ahead and make yourself an impression of it. Try to run this script a multiple times.
For now, don't worry about x. Just try to catch the food and you will notice, that sometimes you will get an "error" (which is good!) and the game stops but sometimes when the snake is even on the same height as the food, you won't get this fancy error and the game goes on.
Question: Why?

As 4castle explained,
The amount it is moving is dictated by speed. Speed is set to 2. If the y coordinate for the "snake" is an odd number, then it will be incremented by two each time and will never reach the same y-coordinate for the "food" (if food is even). A way to see this is to switch the speed to 1. This of course will make your snake move at half speed, so after you visually see your program working - switch back to speed = 2 and tweak the food's y-coordinate variable to be an odd number as well.

Look closely at the console output, because it shows the culprit:
food_x:31 x:34 / food_y:97 y:98
food_x:31 x:34 / food_y:97 y:96
Your snake is just never on the same exact position as the food. The eat() function is called every time. However, your condition isn't always true.
The solution to this problem would be to just check if y somewhat equal (within tolerance of speed) to food_position_y:
if (Math.abs(y - food_position_y) <= Math.abs(speed)) {
throw;
}

Related

Player Speeding Up In JavaScript Game [duplicate]

This question already has an answer here:
setInterval time increases on every click
(1 answer)
Closed 1 year ago.
Every single time I move with the right or left arrows keys or A or D, the player speeds up. I don't want this to happen. I want the player to move at the same speed whenever you press the move key. I have no idea why this is happening. Here is my code:
class Player {
constructor(x, y, color, width, height, health, strength, type, speed) {
this.x = x;
this.y = y;
this.color = color;
this.width = width;
this.height = height;
this.health = health;
this.strength = strength;
this.type = type;
this.speed = speed;
}
draw() {
c.beginPath();
c.rect(this.x, this.y, this.width, this.height);
c.fillStyle = this.color;
c.fill();
c.stroke();
}
moveLeft(){
this.x -= this.speed;
}
moveRight(){
this.x += this.speed;
}
moveUp(){
this.y += this.speed;
}
}
var x = canvas.width / 2;
var y = canvas.height / 2;
var left = false;
var up = false;
var right = false;
var left2 = false;
var up2 = false;
var right2 = false;
var pressing;
var player = new Player(x, y, 'red', 30, 30, 100, 30, 'basic', 2);
player.draw();
document.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37:
left = true;
setInterval(function pressing(){
if(left2===false && left === true){
player.moveLeft();
}
},10)
break;
case 65:
left2 = true;
setInterval(function pressing(){
if(left===false && left2 === true){
player.moveLeft();
}
},10)
break;
case 39:
right = true;
setInterval(function pressing(){
if(right2===false && right === true){
player.moveRight();
}
},10)
break;
case 68:
right2 = true;
setInterval(function pressing(){
if(right===false && right2 === true){
player.moveRight();
}
},10)
break;
}
});
document.addEventListener("keyup", event => {
clearInterval(pressing);
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 65) {
left2 = false;
}
if (event.keyCode === 39) {
right = false;
}
if (event.keyCode === 68) {
right2 = false;
}
});
I followed many tutorials but couldn't find a different easy way to move my player. Does anyone have another strategy for moving or know why this isn't working?
On every keypress you are currently creating a new interval that is never stopped. So what you are actually doing is to create duplicate intervals each time the key is pressed. As a first, rough fix you could try to store the return value of setInterval in a variable outside of the scope of the key event handler and check whether you have earlier intervals running. If so, clear them up before going ahead.
As clearInterval does not throw any error when fed un-intervalish values, you don't even have to check before clearing:
let myInterval = null
document.addEventListener('keydown', (e) => {
// Clean up any earlier mess.
clearInterval(myInterval)
// Create new mess.
myInterval = setInterval(() => { /* do something */ }, 10)
})
I think that you already have the answer...
You are creating multiple intervals that are never stopped.
But I would not use the interval in the key events, instead use just one outside to draw at certain frequency, then use a more mathematical approach to move and set the speed of the player on those events, we don't need different functions to move left or right, all we need is the correct speed value, positive increases (moves right), negative decreases (moves left) ... here is the code:
class Player {
constructor(pos, speed) {
this.pos = pos
this.speed = speed
}
draw() {
this.pos.x += this.speed.x
this.pos.y += this.speed.y
c.clearRect(0, 0, canvas.width, canvas.height)
c.beginPath()
c.rect(this.pos.x, this.pos.y, 20, 20)
c.fill()
}
}
let canvas = document.getElementById("game")
let c = canvas.getContext("2d")
var player = new Player({ x: 60, y: 50 }, { x: 0, y: 0 })
setInterval(() => player.draw(), 50)
document.addEventListener("keydown", function (e) {
switch (e.keyCode) {
case 37:
case 65:
player.speed.x = -1
break
case 39:
case 68:
player.speed.x = 1
break
}
})
document.addEventListener("keyup", function (e) {
switch (e.keyCode) {
case 37:
case 65:
case 39:
case 68:
player.speed.x = 0
break
}
})
<canvas id="game"></canvas>
I did simplify a lot of your code to keep this example small...
If you are really serious about building a JS game you should look at some of the game engines:
https://github.com/collections/javascript-game-engines
Those are some of the most popular open source ones

Let the snake catch his food

I am trying to create a simple snake game. For now I am trying to catch the food but the position of the snake is never the same as the position of food.
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 2;
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width);
food_position_y = Math.floor(Math.random() * canvas.height);
function eat() {
console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (y == food_position_y && x == food_position_x) {
throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, 10, 10);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
}
break;
}
});
})();
canvas { background-color: #000022 }
<canvas id="canvas" width="400" height="400"></canvas>
console.log() will return all positions.
jsfiddle
Am I calculating something wrong? Maybe I have to change the variables food_position_x and food_position_y. If not, I have no idea why the positions are never the same.
Your game area is supposed to be a grid of cells with widths and heights of 10. That's why you do this: Math.floor(x/10)*10 when drawing the snake.
To make the eat function work you just need to draw the food in the same way:
food_position_x = Math.floor(Math.random() * canvas.width / 10) * 10;
food_position_y = Math.floor(Math.random() * canvas.height / 10) * 10;
and add the same thing to the if condition of the eat function:
if (Math.floor(y/10)*10 == food_position_y && Math.floor(x/10)* 10 == food_position_x)
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 2;
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width / 10) * 10;
food_position_y = Math.floor(Math.random() * canvas.height / 10) * 10;
function eat() {
//console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (Math.floor(y/10)*10 == food_position_y && Math.floor(x/10)* 10 == food_position_x) {
throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
if (x > canvas.width) x = 0;
if (y > canvas.height) y = 0;
if (y < 0) y = canvas.height;
if (x < 0) x = canvas.width;
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, 10, 10);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
}
break;
}
});
})();
canvas { background-color: #000022 }
<canvas id="canvas" width="400" height="400"></canvas>
Your game looks like it's on big chunky grid, but it really isn't, that's only in the graphics. The state variables, which are what matter, are little fiddly small numbers.
Instead of drawing the snake like this:
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, 10, 10);
Try drawing it like this:
ctx.rect( x, y, 1, 1 );
And you'll see the real state of the game. This is what you're really playing: https://jsfiddle.net/xeyrmsLc/11/ - and that's why it's hard to get the food.
The main problem is that there are so many possibilities for x and food_position_x, and precise control is difficult, that it's very difficult to land exactly on an X that matches in combination with a Y that matches. You have to move back and forth a lot around the same area to get an exact match for X or an exact match for Y (from which you can then proceed to go in some orthogonal direction to land on the food).
But your code does work at a base level. You might consider reducing the speed and making the visual square location exactly match the internal numbers (less visual granularity which doesn't match the underlying state).

Snake moves horizontally

I am trying to create a simple snake game.
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 2;
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width / 10) * 10,
food_position_y = Math.floor(Math.random() * canvas.height / 10) * 10,
size_x = 10;
function eat() {
console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (Math.floor(y / 10) * 10 == food_position_y && Math.floor(x / 10) *10 == food_position_x) {
size_x += 2;
//throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, size_x, 10);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
}
break;
}
});
})();
canvas { background-color: #000022 }
<canvas id="canvas" width="400" height="400"></canvas>
jsfiddle
The problem
Every time when I catch the food, the snake becomes longer but when you press the down or up key, it moves horizontally.
Maybe a solution
This is what I believe the solution could be:
The snake should be an array! Every time when the key is pressed, define the position of HEAD of snake and move the snake step by step, because it is an array. So the body follows the head. But in this case, I have no idea how to make an array from it.
Maybe there are other solutions. Any helps would be appreciated!
You need to maintain an array of the points currently occupied by the snake body, and add new point (unshift) to the array as the snake approaches and remove point from the back of the array (pop). The following code is a starter, you need to make it your own :).
(function () {
const COLORS={ SNAKE:'#ff7bf5', FOOD:'blue' };
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var snake=[], score=0;
var x, y, food_position_x, food_position_y, x_move, y_move;
var frameCount=0, framesRequiredToMove=10;
//the less the framesToMove the faster the sname moves
function draw(){
if(++frameCount==framesRequiredToMove){
frameCount=0;
move();
}
requestAnimationFrame(draw);
}
function init(){
snake = [{x:3,y:0},{x:2,y:0},{x:1,y:0},{x:0,y:0}];
snake.forEach((p)=>{plot(p.x,p.y,COLORS.SNAKE)})
x=snake[0].x;y=snake[0].y;
score=0;x_move=1;y_move=0;
scoreboard.innerText=score;
newfood();
setTimeout(draw,1000);
}
function plot(x,y,color){
ctx.beginPath();
ctx.rect(x * 10, y * 10, 10, 10);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function move(){
snakepx.innerText = x;
snakepy.innerText = y;
x = x + x_move;
y = y + y_move;
// Advance The Snake
plot(x,y,COLORS.SNAKE);
snake.unshift({x:x,y:y});
// Check food encounter
if(x==food_position_x && y==food_position_y){
scoreboard.innerText=++score;
newfood();
}
else{
var last=snake.pop();
ctx.clearRect(last.x * 10, last.y * 10, 10, 10);
}
}
function newfood(){
food_position_x=Math.floor(Math.random() * canvas.width / 10);
food_position_y=Math.floor(Math.random() * canvas.height / 10);
plot(food_position_x,food_position_y,COLORS.FOOD);
foodpx.innerText = food_position_x;
foodpy.innerText = food_position_y;
}
init();
// Key Pressing
document.addEventListener('keydown', function (event) {
event.preventDefault();
switch (event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = 1;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = 1;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -1;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -1;
y_move = 0;
}
break;
}
});
})();
canvas {
background-color: #000022;
float: left;
}
<canvas id="canvas" width="400" height="180"></canvas>
<div style="margin-left: 410px">
Snake: (<span id="snakepx"></span>, <span id="snakepy"></span>)<br>
Food: (<span id="foodpx"></span>, <span id="foodpy"></span>)<br>
Score: <span id="scoreboard"></span>
</div>
Well as I had some free time to spare I created my own JS snake to demonstrate you how it can be done. Most important parts are in this.snakeBody where array of body is stored and this.moveForward() where you can see how body is updated.
https://jsfiddle.net/nooorz24/p8xtdv3h/13/
moveForward: function() {
var next = this.getNextfieldValue();
if (next == "frame" || next == "body") {
console.log("You lose!")
this.isAlive = false;
} else {
var newHead = this.getNextfieldCoords();
this.draw.snake(newHead.x, newHead.y);
this.body.unshift(newHead);
if (next == "food") {
this.generateFood();
this.snakeSize++;
} else {
var last = this.body.pop();
this.draw.empty(last.x, last.y);
}
}
},
I tried to make it as readable as I could, but note that this is unfinished example and would need need loads of improvements to be a playable game
I think that you have hit on the answer with an array. In the past, I have found that Snake works best with an array, tracking each block of the snake and checking for any two blocks being in the same position. For movement, however, you must directly control the head, and have the body follow based on the position of the array space one ahead of it. The snake head would be the first item in the array. I am not sure what you mean about not understanding the implementation of the array, but the coordinates for each block would be an item in the array.
Have a length variable and make that the x or y size based on direction, like this:
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 2,
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width / 10) * 10,
food_position_y = Math.floor(Math.random() * canvas.height / 10) * 10,
size_x = 10,
size_y = 10,
snake_length = 10;
function eat() {
console.log('food_x:' + food_position_x + ' x:' + x + ' / food_y:' + food_position_y + ' y:' + y);
if (Math.floor(y / 10) * 10 == food_position_y && Math.floor(x / 10) *10 == food_position_x) {
snake_length += 2;
//throw new Error("MATCH!"); // This is not an error. Just trying to stop the script
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, size_x, size_y);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
size_x = 10;
size_y = snake_length;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
size_x = snake_length;
size_y = 10;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
size_x = 10;
size_y = snake_length;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
size_x = snake_length;
size_y = 10;
}
break;
}
});
})();
canvas { background-color: #000022 }
<canvas id="canvas" width="400" height="400"></canvas>
I make the game using C++ soi can advice make a new object for every snake tile and on move set it to parent position
function Tile(x, y)
{
this.x = x;
this.y = y;
}
To debug your down or up problem, I would add some console.log('message') calls in your code for debugging.
Specifically, add some console messages in the switch statement so that you know the correct event and branch is firing. For Example:
switch(event.keyCode) {
case 40:
console.log('down');
...
case 39:
console.log('right');
...
}
Then add more and more debugging log messages until you find your problem.
You can view the console messages in the F12 developer tools in your browser of choice while running your game.
Also make sure you are not calling ctx.translate(...) on the canvas context to flip the canvas, this would change the direction of the x and/or y axis.

Easeljs coordinates

I'm making a game in javascript using EaselJS. I've run into problems with collision detection.
I'm using this for hit detection (as I'm checking if shapes hit, not just points) https://github.com/olsn/Collision-Detection-for-EaselJS
Which seems to work great, but for some reason the coordinates of different shapes always seem 'off'. I had the exact same problem without olsns collision detection. I think this is because they are in different coordinate spaces but I've no idea how to get uniform coordinates. Ideally I want everything using the same coordinate system, there is only keyboard interaction so mouse coordinates do not really matter.
I've messed around with localtoglobal, globaltolocal and localtolocal but nothing seems to work as needed.
I feel like I'm missing something important in how easelJS handles coordinates.
Here's some (relevant) code:
window.stage = new createjs.Stage("CanvasGeo");
function drawShip() {
// Initializes ship graphics
shipG = new createjs.Shape();
shipG.graphics.beginFill("DeepSkyBlue").drawCircle(x, y, circlesize);
stage.addChild(shipG);
}
function drawShape() {
shapeG = new createjs.Shape();
if (type == "Rect") {
shapeG.graphics.beginFill(colour).drawRect(x, y, shapesize, shapesize);
} else if (type == "Triangle") {
shapeG.graphics.beginFill(colour).drawPolyStar(x, y, shapesize, 3, 0.5, getRandomInt(1, 359));
} else if (type == "Star") {
shapeG.graphics.beginFill(colour).drawPolyStar(x, y, shapesize, 5, 0.7, getRandomInt(1, 359));
}
stage.addChild(shapeG);
}
function findSpawnPoint() {
var direction = getRandomInt(1, 5);
switch (direction) {
// TOP
case 1:
console.log("Spawn shape on top");
x = getRandomInt((shapesize * 2), canvasWidth - (shapesize * 2));
y = -1 * shapesize;
xVel = getRandomSpeed();
yVel = Math.abs(getRandomSpeed());
break;
// LEFT
case 2:
console.log("Spawn shape on left");
x = -1 * shapesize;
y = getRandomInt((shapesize * 2), canvasHeight - (shapesize * 2));
xVel = Math.abs(getRandomSpeed());
yVel = getRandomSpeed();
break;
// RIGHT
case 3:
console.log("Spawn shape on right");
x = shapesize + canvasWidth;
y = getRandomInt((shapesize * 2), canvasHeight - (shapesize * 2));
xVel = -1 * Math.abs(getRandomSpeed());
yVel = getRandomSpeed();
break;
// BOTTOM
case 4:
console.log("Spawn shape on bottom");
x = getRandomInt((shapesize * 2), canvasWidth - (shapesize * 2));
y = shapesize + canvasHeight;
xVel = getRandomSpeed();
yVel = -1 * Math.abs(getRandomSpeed());
break;
}
}
this.hitCheck = function(ship) {
if (!null == ndgmr.checkRectCollision(shapeG, ship)) {
this.hitAction();
}
}
Thanks for any help :)

Changing my Jquery project to plain javascript

I created a breakout game for a school project using jquery and a helpful online tutorial.
The working fiddle is here: http://jsfiddle.net/Kinetic915/kURvf/
EDIT revised fiddle: http://jsfiddle.net/Kinetic915/nVctR/
I have changed most to javascript but am having problems changing the jquery code that renders the ball to javascript.
I have Marked and left spaces in the areas where there are problems.
Thank you very much for any help given!!
//***********************************************************************************
// START CODE
//***********************************************************************************
// VARIABLES and other initializing functions are here
function start() {
//******************************************************************************
//JQUERY
// HERE IS THE MAIN PROBLEM!!!!!!
// HERE IS THE MAIN PROBLEM!!!!!!
Cir = $('#canvas')[0].getContext("2d");
//JQUERY
//changing to Cir = canvas.getContext("2d"); causes the code to FAIL.
return setInterval(drawCIRCLE, 10);
}
function windowsize() {
//success with javascript
WIDTH.width = window.innerWidth;
HEIGHT.height = window.innerHeight;
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
//Previous JQUERY:
// WIDTH = $("#canvas")[0].width = $(window).width();
// HEIGHT = $("#canvas")[0].height = $(window).height();
}
windowsize();
var x = WIDTH / 2 - 30; //divide by 2 start in middle of window
var y = HEIGHT / 2;
//THIS DRAWS THE CIRCLE
function circle() {
//Cir.clearRect(0, 0, WIDTH, HEIGHT);
Cir.beginPath();
Cir.arc(x, y, 10, 0, Math.PI * 2, true);
Cir.closePath();
Cir.fill();
}
// Initialization of the Block array, rendering of the gutter area and coordinate box
were here
//*********************************************************
// HERE IS THE CODE THAT RENDERS THE BALL MOVEMENT ETC.
//draw a circle
function drawCIRCLE() {
clear();
circle();
drawPADDLE(); //calls draw paddle function
drawGUTTER(); // calls draw gutter function
drawCOORBOX(); // calls draw coordinate box function
drawBRICKS(); //calls the function to draw the boxes
//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 < numrows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
}
if (x + dx > WIDTH || x + dx < 0) dx = -dx;
if (y + dy < 0) dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) || y + dy > HEIGHT) {
if (x > paddlex && x < paddlex + paddlew)
//switch! once first is true, then second goes
dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) && y + dy > HEIGHT) {
clearInterval(intervalId);
}
}
x += dx;
y += dy;
if (rightpress) paddlex += 5;
else if (leftpress) paddlex -= 5;
}
function clear() {
Cir.clearRect(0, 0, WIDTH, HEIGHT);
//Is this jquery? I suspect this part of the code making the circle rendering fail.
}
start();
init_paddle();
initbricks();
Ages ago I wrote a similar code in pure JavaScript here
this code uses pure javascript and no library.The code is well commented(I think :))
I generally attached events like this
document.onkeydown = function(e)
{
e = e || window.event;
switch (e.keyCode) { // which key was pressed?
case 32: // release ball.
if(!game.ball.isFree)
{
game.ball.isFree = true;
game.ball.directionX = game.ball.directionY = 1;
game.ball.x = game.ball.offsetLeft;
game.ball.y = game.screen.offsetHeight - game.ball.offsetTop;
}
break;
case 37: // left, rotate player left
game.bar.direction = -1;
break;
case 39: // right, rotate player right
game.bar.direction = 1;
break;
}
}
document.onkeyup = function(e)
{
e = e || window.event;
switch (e.keyCode)
{
case 37:
case 39:
game.bar.direction = 0;
break;
}
}
},
Ofcourse you have many other places which might need porting so a helpful break down of questions would be easier to answer :)
Hope this helps

Categories