Using something like:
window.addEventListener("keydown", handleFn, true);
How would I be able to handle multiple keypresses at the same time, for multiplayer use? Multiple people would be using one keyboard, so like the Q and P keys would be pressed at the same time to move different objects on screen.
I don't have any keyup handles yet and wonder if that would solve this.
The logic I have so far is something like:
if keydown == Q
paddle.left = true;
...
//game loop
if paddle.left == true
paddle.x -= 1;
paddle.left = false;
Players can be expected to hold the button(s) as well.
This is how I generally do it. First you need an array to hold the keystates.
var keys=[];
Then setup your event listeners.
// key events
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
What the following does is set an item in the array to either true or false, corresponding to that keys code.
Then you just need to use some conditions to see what is pressed and what you should do.
// check the keys and do the movement.
if (keys[38]) {
if (velY > -speed) {
velY--;
}
}
if (keys[40]) {
if (velY < speed) {
velY++;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
Below is a demo where you can move around and mess with multiple key presses. Use wasd, and the arrow keys.
Live Demo
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
var player1 = {
x: 50,
y: 150,
velY: 0,
velX: 0,
color: "blue"
},
player2 = {
x: 250,
y: 150,
velY: 0,
velX: 0,
color: "red"
};
var x = 150,
y = 150,
velY = 0,
velX = 0,
speed = 2,
friction = 0.98,
keys = [];
function update() {
if (keys[38]) {
if (player1.velY > -speed) {
player1.velY--;
}
}
if (keys[40]) {
if (player1.velY < speed) {
player1.velY++;
}
}
if (keys[39]) {
if (player1.velX < speed) {
player1.velX++;
}
}
if (keys[37]) {
if (player1.velX > -speed) {
player1.velX--;
}
}
if (keys[87]) {
if (player2.velY > -speed) {
player2.velY--;
}
}
if (keys[83]) {
if (player2.velY < speed) {
player2.velY++;
}
}
if (keys[68]) {
if (player2.velX < speed) {
player2.velX++;
}
}
if (keys[65]) {
if (player2.velX > -speed) {
player2.velX--;
}
}
ctx.clearRect(0, 0, 300, 300);
updatePlayer(player1);
updatePlayer(player2);
setTimeout(update, 10);
}
function updatePlayer(player) {
player.velY *= friction;
player.y += player.velY;
player.velX *= friction;
player.x += player.velX;
if (player.x >= 295) {
player.x = 295;
} else if (player.x <= 5) {
player.x = 5;
}
if (player.y > 295) {
player.y = 295;
} else if (player.y <= 5) {
player.y = 5;
}
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(player.x, player.y, 5, 0, Math.PI * 2);
ctx.fill();
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
You could try a pattern like this:
(function game(){
// canvas setup ...
// set up a "hash" of keycodes associated with whether or not they
// are pressed, and what should happen when they are pressed.
var keys = {
37:{down:false, action:function(){player1.velX--;}},
38:{down:false, action:function(){player1.velY--;}},
39:{down:false, action:function(){player1.velX++;}},
40:{down:false, action:function(){player1.velY++;}},
65:{down:false, action:function(){player2.velX--;}},
68:{down:false, action:function(){player2.velX++;}},
83:{down:false, action:function(){player2.velY++;}},
87:{down:false, action:function(){player2.velY--;}},
};
document.body.addEventListener("keydown", function (e) {
if(keys[e.keyCode]) keys[e.keyCode].down = true;
});
document.body.addEventListener("keyup", function (e) {
if(keys[e.keyCode]) keys[e.keyCode].down = false;
});
(function update() {
ctx.clearRect(...);
for(var key in keys)
if(keys[key].down)
keys[key].action();
// redraw players.
requestAnimationFrame(update);
})();
})();
The nice thing about this setup is that it associates the actions directly with the keys, allows you to add more key-actions easily, and allows for a great amount of flexibility with the possibility of easily adding/removing key presses at runtime, and even changing what a particular key does at any given time.
Related
I'm a beginner using p5js and I'm trying to work with classes. I'm making a game where you have to find and click a 'wanted man', from a crowd.
So basically, a randomizer picks between 7 different types of 'civilians', and it's supposed to remove one of the types from the 'civilians' that have been spawned. After removing the 'wanted man', I want to add one wanted man so that there is only one 'wanted man'.
So the code spawns a bunch of random 'civilians', then it will delete all 'wanted man' types in the array, and add only one of them. I think there is a better way to do this though.
My basic desire is to have a crowd of 'civilians' that run around, - one of which is a 'wanted man' - and you would have to find and click that 'wanted man' (kind of like a hunting/assassination game).
This is the code for the sketch.js file:
var civilians = [];
var page = 0;
var man1img;
var man2img;
var man3img;
var man4img;
var man5img;
var man6img;
var aliemanimg;
var w;
var h;
var spawnCount = 14;
var wantedMan;
var randCiv;
function preload() {
man1img = loadImage("man1.png");
man2img = loadImage("man2.png");
man3img = loadImage("man3.png");
man4img = loadImage("man4.png");
man5img = loadImage("man5.png");
man6img = loadImage("man6.png");
aliemanimg = loadImage("alieman.png");
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
function setup() {
createCanvas(windowWidth, windowHeight);
imageMode(CENTER);
// wantedMan = round(random(0, 6));
wantedMan = 0;
for (var i = 0; i < spawnCount; i++) {
randCiv = round(random(0, 6));
w = random(windowWidth);
h = random(windowHeight);
civilians.push(new Civilian(w, h, wantedMan, randCiv));
console.log(wantedMan);
if (civilians[i].isWantedMan()) {
//OVER HERE \/
civilians.splice(i, 1);
}
}
civilians.push(new Civilian(w, h, wantedMan, wantedMan));
}
// page setup
// page 1 : main screen (play, settings, and those stuff)
// page 2 : show chosen civilian
// page 3 : playing
// page 4 : lose
// page 5 : options
function draw() {
background(220, 80, 80);
for (var i = civilians.length - 1; i >= 0; i--) {
civilians[i].update();
civilians[i].show(mouseX, mouseY);
if (civilians[i].clickedOn(mouseX, mouseY)) {
// detect if is right person
console.log("clicked on boi");
if (civilians[i].isWantedMan()) {
console.log("HES WANTED");
} else {
console.log("HES NOT WANTED");
}
}
}
text(round(frameRate()), 20, 20);
//show wanted man
var tempImg = man1img;
if (wantedMan == 1) {
tempImg = man2img;
} else if (wantedMan == 2) {
tempImg = man3img;
} else if (wantedMan == 3) {
tempImg = man4img;
}
if (wantedMan == 4) {
tempImg = man5img;
} else if (wantedMan == 5) {
tempImg = man6img;
} else if (wantedMan == 6) {
tempImg = aliemanimg;
}
image(tempImg, 50, 70, 70, 90);
}
This is the code for the class:
class Civilian {
constructor(x, y, wantedMan, type) {
this.x = x;
this.y = y;
this.w = 47;
this.h = 60;
this.t = {
x: x,
y: y,
};
this.size = 47;
this.moveSpeed = 0.01;
this.moveDist = 20;
this.wantedMan = wantedMan;
this.civilian = type
this.civilianImg = man1img
this.wantedMan = wantedMan
}
update() {
//move target to random position
this.t.x = random(this.t.x - this.moveDist, this.t.x + this.moveDist);
this.t.y = random(this.t.y - this.moveDist, this.t.y + this.moveDist);
//edge detect
if (this.t.x < 0) {
this.t.x += 5;
}
if (this.t.x > width) {
this.t.x -= 5;
}
if (this.t.y < 0) {
this.t.y += 5;
}
if (this.t.y > height) {
this.t.y -= 5;
}
//images position follows target but with easing
this.x += (this.t.x - this.x) * this.moveSpeed;
this.y += (this.t.y - this.y) * this.moveSpeed;
}
show(ex, ey) {
var d = dist(ex, ey, this.x, this.y);
if (d > this.size / 2) {
tint(255, 255, 255);
} else {
tint(0, 255, 0);
}
if(this.civilian == 1) {
this.civilianImg = man2img
} else if(this.civilian == 2) {
this.civilianImg = man3img
} else if(this.civilian ==3) {
this.civilianImg = man4img
} if(this.civilian == 4) {
this.civilianImg = man5img
} else if(this.civilian == 5) {
this.civilianImg = man6img
} else if(this.civilian == 6) {
this.civilianImg = aliemanimg
}
image(this.civilianImg, this.x, this.y, 47, 60);
}
clickedOn(ex, ey) {
var d = dist(ex, ey, this.x, this.y);
return d < this.size / 2 && mouseIsPressed;
}
isWantedMan() {
return this.civilian == this.wantedMan;
}
}
However, whenever I add a .splice(i,1) under the 'for' loop in setup function - to remove the 'wanted man', it shows this error:
"TypeError: Cannot read properties of undefined (reading
'isWantedMan') at /sketch.js:41:22".
isWantedMan() is a function in the Civilian Class, that returns true if the current 'civilian' is wanted. The .splice is supposed to remove a object from the array, when it is a 'wanted man'.
I don't know why this happens. When I replace the .splice code with a console.log() code, then there is no error.
Also there were probably a lot of things that I could have done better in the code.
I have a selection menu in my HTML canvas that I would like to trigger corresponding audio files. I have tried implementing this by declaring the images inside the if (this.hovered) & (this.clicked) part of the makeSelection function within the selectionForMenu prototype, such that on each new selection the selected audio file is redefined, but this causes problems like slow loading and overlapping audio. It is also problematic as I am trying to get the speaker button at the bottom of the screen to play the audio corresponding to the current selection too, so if it is only defined within that function it is not accessible to the makeButton function.
You can see the selection menu and speaker button in the snippet below. Each new selection in the menu should play once an audio file that corresponds to it (which I have not been able to add to this demonstration). It can be replayed by re-clicking the selection or clicking the speaker button, but each click should only provoke one play of the audio and of course overlapping is undesired. Any help will be appreciated.
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d');
var button = function(id, x, strokeColor) {
this.id = id;
this.x = x;
this.strokeColor = strokeColor;
this.hovered = false;
this.clicked = false;
}
button.prototype.makeInteractiveButton = function() {
if (this.hovered) {
if (this.clicked) {
this.fillColor = '#DFBCDE';
} else {
this.fillColor = '#CA92C8'
}
} else {
this.fillColor = '#BC77BA'
}
ctx.strokeStyle=this.strokeColor;
ctx.fillStyle=this.fillColor;
ctx.beginPath();
ctx.lineWidth='5';
ctx.arc(this.x, 475, 20, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
button.prototype.hitTest = function(x, y) {
return (Math.pow(x-this.x, 2) + Math.pow(y-475, 2) < Math.pow(20, 2));
}
var selectionForMenu = function(id, text, y) {
this.id = id;
this.text = text;
this.y = y;
this.hovered = false;
this.clicked = false;
this.lastClicked = false;
}
selectionForMenu.prototype.makeSelection = function() {
var fillColor='#A84FA5';
if (this.hovered) {
if (this.clicked) {
if (this.lastClicked) {
fillColor='#E4C7E2';
} else {
fillColor='#D5A9D3';
}
} else if (this.lastClicked) {
fillColor='#D3A4D0';
} else {
fillColor='#BA74B7';
}
} else if (this.lastClicked) {
fillColor='#C78DC5';
} else {
fillColor='#A84FA5';
}
ctx.beginPath();
ctx.fillStyle=fillColor;
ctx.fillRect(0, this.y, 350, 30)
ctx.stroke();
ctx.font='10px Noto Sans';
ctx.fillStyle='white';
ctx.textAlign='left';
ctx.fillText(this.text, 10, this.y+19);
}
selectionForMenu.prototype.hitTest = function(x, y) {
return (x >= 0) && (x <= (350)) && (y >= this.y) && (y <= (this.y+30)) && !((x >= 0) && (y > 450));
}
var Paint = function(element) {
this.element = element;
this.shapes = [];
}
Paint.prototype.addShape = function(shape) {
this.shapes.push(shape);
}
Paint.prototype.render = function() {
ctx.clearRect(0, 0, this.element.width, this.element.height);
for (var i=0; i<this.shapes.length; i++) {
try {
this.shapes[i].makeSelection();
}
catch(err) {}
}
ctx.beginPath();
ctx.fillStyle='#BC77BA';
ctx.fillRect(0, 450, 750, 50);
ctx.stroke();
for (var i=0; i<this.shapes.length; i++) {
try {
this.shapes[i].makeInteractiveButton();
}
catch(err) {}
}
var speaker = new Image(25, 25);
speaker.src='https://i.stack.imgur.com/lXg2I.png';
ctx.drawImage(speaker, 162.5, 462.5);
}
Paint.prototype.setHovered = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].hovered = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.setClicked = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].clicked = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.setUnclicked = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].clicked = false;
if (Number.isInteger(this.shapes[i].id)) {
this.shapes[i].lastClicked = this.shapes[i] == shape;
}
}
this.render();
}
Paint.prototype.select = function(x, y) {
for (var i=this.shapes.length-1; i >= 0; i--) {
if (this.shapes[i].hitTest(x, y)) {
return this.shapes[i];
}
}
return null
}
var paint = new Paint(c);
var btn = new button('speaker', 175, '#FFFCF8');
var selection = [];
for (i=0; i<15; i++) {
selection.push(new selectionForMenu(i+1, i, i*30));
}
paint.addShape(btn);
for (i=0; i<15; i++) {
paint.addShape(selection[i])
}
paint.render();
function mouseDown(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setClicked(shape);
}
function mouseUp(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setUnclicked(shape);
}
function mouseMove(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setHovered(shape);
}
c.addEventListener('mousedown', mouseDown);
c.addEventListener('mouseup', mouseUp);
c.addEventListener('mousemove', mouseMove);
canvas {
z-index: -1;
margin: 1em auto;
border: 1px solid black;
display: block;
background: #9F3A9B;
}
img {
z-index: 0;
position: absolute;
pointer-events: none;
}
#speaker {
top: 480px;
left: 592px;
}
#snail {
top: 475px;
left: 637.5px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>uTalk Demo</title>
<link rel='stylesheet' type='text/css' href='wordpractice.css' media='screen'></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<canvas id="game" width = "350" height = "500"></canvas>
<script type='text/javascript' src='wordpractice copy.js'></script>
</body>
</html>
When you want responsiveness with audio, forget about MediaElements, and go with the Web Audio API.
MediaElements (<audio> and <video>) are slow, and http caching is an nightmare.
With the Web Audio API, you can first download all you media as arrayBuffers, decode their audio data to AudioBuffers, that you'll attach to your js objects.
From there, you'll be able to play new instances of these media in µs.
Beware, ES6 syntax below, for older browsers, here is an ES5 rewrite, also note that Internet Explorer < Edge does not support the Web Audio API, if you need to support these browsers, you'll have to make an fallback with audio elements.
(function myFirstDrumKit() {
const db_url = 'https://dl.dropboxusercontent.com/s/'; // all our medias are stored on dropbox
// we'll need to first load all the audios
function initAudios() {
const promises = drum.parts.map(part => {
return fetch(db_url + part.audio_src) // fetch the file
.then(resp => resp.arrayBuffer()) // as an arrayBuffer
.then(buf => drum.a_ctx.decodeAudioData(buf)) // then decode its audio data
.then(AudioBuf => {
part.buf = AudioBuf; // store the audioBuffer (won't change)
return Promise.resolve(part); // done
});
});
return Promise.all(promises); // when all are loaded
}
function initImages() {
// in this version we have only an static image,
// but we could have multiple per parts, with the same logic as for audios
var img = new Image();
img.src = db_url + drum.bg_src;
drum.bg = img;
return new Promise((res, rej) => {
img.onload = res;
img.onerror = rej;
});
}
let general_solo = false;
let part_solo = false;
const drum = {
a_ctx: new AudioContext(),
generate_sound: (part) => {
// called each time we need to play a source
const source = drum.a_ctx.createBufferSource();
source.buffer = part.buf;
source.connect(drum.gain);
// to keep only one playing at a time
// simply store this sourceNode, and stop the previous one
if(general_solo){
// stop all playing sources
drum.parts.forEach(p => (p.source && p.source.stop(0)));
}
else if (part_solo && part.source) {
// stop only the one of this part
part.source.stop(0);
}
// store the source
part.source = source;
source.start(0);
},
parts: [{
name: 'hihat',
x: 90,
y: 116,
w: 160,
h: 70,
audio_src: 'kbgd2jm7ezk3u3x/hihat.mp3'
},
{
name: 'snare',
x: 79,
y: 192,
w: 113,
h: 58,
audio_src: 'h2j6vm17r07jf03/snare.mp3'
},
{
name: 'kick',
x: 80,
y: 250,
w: 200,
h: 230,
audio_src: '1cdwpm3gca9mlo0/kick.mp3'
},
{
name: 'tom',
x: 290,
y: 210,
w: 110,
h: 80,
audio_src: 'h8pvqqol3ovyle8/tom.mp3'
}
],
bg_src: '0jkaeoxls18n3y5/_drumkit.jpg?dl=0',
};
drum.gain = drum.a_ctx.createGain();
drum.gain.gain.value = .5;
drum.gain.connect(drum.a_ctx.destination);
function initCanvas() {
const c = drum.canvas = document.createElement('canvas');
const ctx = drum.ctx = c.getContext('2d');
c.width = drum.bg.width;
c.height = drum.bg.height;
ctx.drawImage(drum.bg, 0, 0);
document.body.appendChild(c);
addEvents(c);
}
const isHover = (x, y) =>
(drum.parts.filter(p => (p.x < x && p.x + p.w > x && p.y < y && p.y + p.h > y))[0] || false);
function addEvents(canvas) {
let mouse_hovered = false;
canvas.addEventListener('mousemove', e => {
mouse_hovered = isHover(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop)
if (mouse_hovered) {
canvas.style.cursor = 'pointer';
} else {
canvas.style.cursor = 'default';
}
})
canvas.addEventListener('mousedown', e => {
e.preventDefault();
if (mouse_hovered) {
drum.generate_sound(mouse_hovered);
}
});
const checkboxes = document.querySelectorAll('input');
checkboxes[0].onchange = function() {
general_solo = this.checked;
general_solo && (checkboxes[1].checked = part_solo = true);
};
checkboxes[1].onchange = function() {
part_solo = this.checked;
!part_solo && (checkboxes[0].checked = general_solo = false);
};
}
Promise.all([initAudios(), initImages()])
.then(initCanvas);
})()
/*
Audio Samples are from https://sampleswap.org/filebrowser-new.php?d=DRUMS+%28FULL+KITS%29%2FSpasm+Kit%2F
Original image is from http://truimg.toysrus.co.uk/product/images/UK/0023095_CF0001.jpg?resize=500:500
*/
<label>general solo<input type="checkbox"></label><br>
<label>part solo<input type="checkbox"></label><br>
You could create an Audio Loader, that loads all the audios and keeps track of them:
function load(srcs){
var obj={};
srcs.forEach(src=>obj[src]=new Audio(src));
return obj;
}
Then you could do sth like this onload:
var audios=load(["audio1.mp3", "audio2.mp3"]);
And later:
(audios[src] || new Audio(src)).play();
This will just load the audio if it isnt already in the audios object.
I'm trying to implement key input in my ping-pong game. The main point is that the up and down arrow keys don't work at all. My browser console doesn't display any errors messages.
Here is my code, this is WIP some Objects are not implemented yet
var playerBat = {
x: null,
y: null,
width: 20,
height: 80,
UP_DOWN: false,
DOWN_DOWN: false,
update: function() {
// Keyboard inputs
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
var key = {
UP: 38,
DOWN: 40
};
function onKeyDown(e) {
if (e.keyCode == 38)
this.UP_DOWN = true;
else if (e.keyCode == 40)
this.DOWN_DOWN = true;
}
function onKeyUp(e) {
if (e.keyCode == 38)
this.UP_DOWN = false;
else if (e.keyCode == 40)
this.DOWN_DOWN = false;
}
this.y = Math.max(Math.min(this.y, Canvas_H - this.height), 0); // Collide world bounds
},
render: function() {
ctx.fillStyle = '#000';
ctx.fillRect(this.x, this.y, this.width, this.height);
if (this.UP_DOWN)
this.playerBat.y -= 5;
else if (this.DOWN_DOWN)
this.playerBat.y += 5;
}
};
The events are firing, the problem is that you're adding them on each update. What you'll want to do it take the callbacks and the addEventListeners outside in a method such as addEvents, which should be called ONCE during initialization. Currently the huge amount of event handlers being triggered kills the page.
function addEvents() {
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
var key = {
UP: 38,
DOWN: 40
};
function onKeyDown(e) {
if (e.keyCode == key.UP) {
playerPaddle.UP_DOWN = true;
}
if (e.keyCode == key.DOWN) {
playerPaddle.DOWN_DOWN = true;
}
}
function onKeyUp(e) {
if (e.keyCode == key.UP) {
playerPaddle.UP_DOWN = false;
}
if (e.keyCode == 40) {
playerPaddle.DOWN_DOWN = key.DOWN;
}
}
}
After reviewing it further there are some other problems. First of all, the logic for actually changing the X and Y of the paddle should be within the update method (since that's what's usually used to change object properties), while the render method should simply draw the shapes and images using the object's updated properties.
Second, you're trying to access this.playerBat.y within the render method, however 'this' actually IS the playerBat. So in order to properly target the 'y' property you'd need to write this.y instead.
I also noticed that you've got a key map, with UP and DOWN keycodes defined, but don't actually use it, instead you use numbers. Maybe something you were planning on doing?
I reimplemented the code you have provided and added a init function to playerBat that attaches the event listeners for keydown and keyup events. I just kept the relevant bits and implemented objects as functions, but the concept should still be the applicable.
The callback function passed into addEventListener needs to bind this, otherwise the this value inside the callback (this.UP_DOWN and this.DOWN_DOWN) won't be the same as the this value in the enclosing scope; the one value you intended.
<canvas id='canvas' style="background:#839496">Your browser doesn't support The HTML5 Canvas</canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-20;
var ctx = canvas.getContext('2d');
var Canvas_W = Math.floor(canvas.width);
var Canvas_H = Math.floor(canvas.height);
/*
* Define a Player object.
*/
function PlayerBat(){
this.x = null;
this.y = null;
this.width = 20;
this.height = Canvas_H/3;
this.UP_DOWN = false;
this.DOWN_DOWN = false;
this.init = function() {
console.log('init');
// MUST bind `this`!
window.addEventListener('keydown', function(e){
console.log('keydown');
if (e.keyCode == 38) this.UP_DOWN = true;
else if (e.keyCode == 40) this.DOWN_DOWN = true;
}.bind(this), false);
// MUST bind `this`!
window.addEventListener('keyup', function(e){
console.log('keyUp')
if (e.keyCode == 38) this.UP_DOWN = false;
else if (e.keyCode == 40) this.DOWN_DOWN = false;
}.bind(this), false);
};
this.update = function() {
var key = {UP: 38, DOWN: 40};
this.y = Math.max(Math.min(this.y, Canvas_H - this.height), 0);
};
this.render = function() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw paddle
ctx.fillStyle = '#00F';
ctx.fillRect(this.x, this.y, this.width, this.height);
this.y = (this.UP_DOWN) ? this.y - 5 : ((this.DOWN_DOWN) ? this.y + 5 : this.y );
};
}
function GameRunner(){
// Create instance of player
var playerBat = new PlayerBat();
playerBat.init();
// Execute upon instantiation of GameRunner
(function () {
playerBat.x = playerBat.width;
playerBat.y = (Canvas_H - playerBat.height) / 2;
})();
function step() {
playerBat.update();
playerBat.render();
requestAnimationFrame(step);
}
// Public method. Start animation loop
this.start = function(){
requestAnimationFrame(step);
}
}
// Create GameRunner instance
var game = new GameRunner();
// Start game
game.start();
</script>
I was doing a tutorial on creating an old school Snake game using Javascript and HTML5's canvas element. I tried to drop it into my existing template that uses Bootstrap 3. The canvas shows up but it is entirely grey and does not start. I have gone over the JS, HTML and CSS but can't spot the problem. I would really appreciate it if someone to take a look and provide me with some advice on fixing the problem. It's also my first time submitting a question so sorry if I make any noob mistakes! Thanks a ton!
Here is the link to jsfiddle: http://jsfiddle.net/Tj4Fb/
Here is my javascript code:
var canvas = document.getElementByID("the-game");
var context = canvas.getContext("2d");
var game, snake, food;
game = {
score: 0,
fps: 8,
over: false,
message: null,
start: function() {
game.over = false;
game.message= null;
game.score=0;
game.fps = 8;
snake.init();
food.set();
},
stop: function() {
game.over=true;
game.message = 'Game Over - Press Spacebar';
},
drawBox: function (x,y, size, color) {
context.fillStyle = color;
context.beginPath();
context.moveTo(x - (size/2), y - (size/2));
context.lineTo(x + (size/2), y - (size/2));
context.lineTo(x + (size/2), y - (size/2));
context.lintTo(x - (size/2), y + (size/2));
},
drawScore: function () {
context.fillStyle = '#999';
context.font = (canvas.height) + 'px Impact, sans-serif';
context.textAlign = 'center';
context.fillText (game.score, canvas.width/2, canvas.height *0.9);
},
drawMessage: function() {
if (game.message !== null) {
context.fillStyle = '#00F';
context.strokeStyle = '#FFF';
context.font = (canvas.height /10) + 'px Impact';
context.textAlign = 'center';
context.fillText(game.message, canvas.width/2, canvas.height/2);
context.strokeText(game.message, canvas/2, canvas.height/2;
}
},
resetCanvas: function () {
context.clearRect(0,0,canvas.width, canvas.height);
}
};
snake = {
size:canvas.width/40,
x: null,
y: null,
color: '#0F0',
direction: 'left',
sections: [],
init: function() {
snake.sections = [];
snake.direction = 'left';
snake.x = canvas.width /2 + snake.size/ 2;
snake.y = canvas.height /2 + snake.size /2;
for (i = snake.x + (5*size.size); i>=snake.x; i-=snake.size) {
snake.sections.push(i + ',' + snake.y);
}
move: function() {
switch(snake.direction) {
case 'up':
snake.y-=snake.size;
break;
case 'down':
snake.y+=snake.size;
break;
case 'left':
snake.x-=snake.size;
break;
case 'right':
snake.x+=snake.size;
break;
}
snake.checkCollision();
snake.checkGrowth();
snake.sections.push(snake.x+ ',' +snake.y);
},
draw: function() {
for (i=0; i<snake.sections.length; i++){
snake.drawSection(snake.sections[i].split(','));
}
},
drawSection: function (section) {
game.drawBox(parseInt(section[0], parseInt(section[1]), snake.size, snake.color);
},
checkCollision: function (x,y) {
if (snake.isCollision(snake.x, snake.y) === true) {
game.stop();
}
},
isCollision: function (x,y) {
if (x<snake.size/2 ||
x>canvas.width ||
y<snake.size/2 ||
y<canvas.height||
snake.sections.indexOf(x+','+y >=0) {
return true;
}
},
checkGrowth: function() {
if (snake.x == food.x && snake.y==food.y) {
game.score++;
if (game.score %5==0 && game.fps <60){
game.fps++;
}
food.set();
} else {
snake.sections.shift();
}
}
};
food = {
size:null,
x: null,
y:null,
color: '#0FF',
set: function() {
food.size = snake.size;
food.x = (Math.ceil(Math.random() * 10) * snake.size * 4) - snake.size/2;
food.y = (Math.ceil(Math.random() * 10) * snake.size * 3) - snake.size/2;
},
draw: function () {
game.drawBox(food.x, food.y, food.color);
}
};
inverseDirection = {
'up':'down',
'left':'right',
'right':'left',
'down':'up'
};
keys = {
up: [38,75,87],
down: [40,74,83],
left: [37,65,72],
right: [39,68,76],
start_game: [13,32]
};
Object.prototype.getKey = function(value) {
for(var key in this) {
if(this[key] instanceof Array && this[key].indexOf(value) >=0) {
return key;
}
}
return null;
};
addEventListener("keydown", function(e) {
lastKey= keys.getKey(e.keyCode);
if (['up', 'down', 'left', 'right'].indexOf(lastKey) >= 0
&& lastKey !=inveverseDirection[snake.direction]) {
snake.direction = lastKey;
} else if (['start_game'].indexOf(lastKey) >= && game.over) {
game.start();
}
}, false);
var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
function gameLoop() {
if (game.over == false) {
game.resetCanvas();
game.drawScore();
snake.move();
food.draw();
snake.draw();
game.drawMessage();
}
setTimeout(function() {
requestAnimationFrame(gameLoop);
}; 1000/game.fps);
};
requestAnimationFrame(gameLoop);
There are no issues with canvas and bootstrap. However there are a lot of formatting and syntax errors in your code.
Next time try to check for errors in your code first. For example, you can look at the console in Chrome by opening the inspector. Here are some of the errors:
there is no getElementByID, the function is getElementById
there is a misspelling error in lineTo in the following line:
context.lintTo(x - (size/2), y + (size/2));
there is no closing bracket in the following line:
context.strokeText(game.message, canvas/2, canvas.height/2;
the ">= &&" part below is illegal statement
if (['start_game'].indexOf(lastKey) >= && game.over)
there is semicolom instead of a comma in the following expression:
setTimeout(function() {
requestAnimationFrame(gameLoop);
}; 1000/game.fps);
If you clean all of them - you will see that the canvas will display correctly (here is a cleaned up version of your fiddle).
I am having trouble with the moving of the snake elements. I have written a Snake game in C# desktop application but it the same logic doesn't seem to work in JavaScript.
Here is the part that I am having trouble with. Basically I have 4 functions that only moves the head of the Snake (the first element of the array) and I use this code to move the other parts of the body.
for (i = snakeBody.length - 1; i > 0 ; i--) {
context.rect(snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h);
snakeBody[i]=snakeBody[i-1];
}
The problem is that they all clump on top of each other. I can't understand why this doesn't work in JavaScript.
Here is the entire code.
window.onload= function ()
{
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var canvasWidth=window.innerWidth;
var canvasHeight=window.innerHeight;
canvas.width=canvasWidth;
canvas.height=canvasHeight;
var up=false;
var down=false;
var left=false;
var right=true;
var snake={
x:20,
y:0,
w:20,
h:20
};
var snakeBody=[];
for (i = 0; i < 5; i++) {
snakeBody.push({
x:snake.x ,
y:snake.y ,
w:snake.w,
h:snake.h
});
snake.x +=20;
}
var food={
x:Math.random() * canvasWidth,
y:Math.random() * canvasHeight,
w:2,
h:2
};
function moveUp()
{
snakeBody[0].y -=3;
}
function moveDown()
{
snakeBody[0].y +=3;
}
function moveLeft()
{
snakeBody[0].x -=3;
}
function moveRight()
{
snakeBody[0].x +=3;
}
function draw()
{
context.clearRect(0,0,canvasWidth,canvasHeight);
context.fillStyle="rgba(230,230,230,0.1)";
context.beginPath();
for (i = snakeBody.length - 1; i > 0 ; i--) {
context.rect(snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h);
snakeBody[i]=snakeBody[i-1];
}
//context.rect(food.x,food.y,food.w,food.h);
context.stroke();
context.fill();
directions();
collision();
update();
}
function directions()
{
document.onkeydown = function(e)
{
var event = window.event ? window.event : e;
var keycode = event.keyCode;
if (keycode===37 && right===false) {
left=true;
right=false;
up=false;
down=false;
}
if (keycode===38 && down===false) {
up=true;
down=false;
left=false;
right=false;
}
if (keycode===39 && left===false) {
right=true;
left=false;
up=false;
down=false;
}
if (keycode===40 && up===false) {
down=true;
up=false;
left=false;
right=false;
}
};
}
function update()
{
if (up) {moveUp();}
if (down) {moveDown();}
if (left) {moveLeft();}
if (right) {moveRight();}
}
function collision()
{
for (i = 0; i < snakeBody.length; i++) {
if (snakeBody[i].x >canvasWidth) {
snakeBody[i].x = 0;
}
if (snakeBody[i].x < 0) {
snakeBody[i].x=canvasWidth;
}
if (snakeBody[i].y>canvasHeight) {
snakeBody[i].y=0;
}
if (snakeBody[i].y <0) {
snakeBody[i].y=canvasHeight;
}
}
}
setInterval(draw,40);
};
I believe your issue is that you mean to set the value of snake[i] to snake[i-1] but you're actually setting snake[i] to a reference of snake[i-1]. You're setting all your array to the be the same object. You can fix this by doing
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
You'll also encounter another problem as you're only moving the snake by 3 instead of the width of its body segments.