Snake script is not passing values to variable - javascript

So here is my snake script -
http://jsfiddle.net/6bKHc/24/
I started to create a snake game, but basically move(top), move(bottom) e.c. is not working. Any ideas why? I understand that I can't pass the elements to variable like this, so maybe you could show me how to do that correctly?

Ok cleared syntax and took a look at errors this should get you started
$(document).keydown(function(event){
var move, inter;
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
if(dir == 'top') {
snake.stop().animate({"top": "+=5px"});
}
if(dir == 'bottom') {
snake.stop().animate({"top": "-=5px"});
}
if(dir == 'left') {
snake.stop().animate({"left": "+=5px"});
}
if(dir == 'right') {
snake.stop().animate({"top": "-=5px"});
}
}, 500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
}; });​
fiddle
Couple of obvious additions to make:
boundary checking
smoothness of animation.

To make it work you will have to moodify your code like follows :
$(document).keydown(function() {
var inter;
return function(event) {
var move, prevDirection;
clearInterval(inter);
inter = setInterval(move = function(direction) {
var value, prop;
switch (direction || prevDirection) {
case "top":
prop = "top";
value = -5;
break;
case "bottom":
prop = "top";
value = 5;
break;
case "left":
prop = "left";
value = -5;
break;
case "right":
prop = "left";
value = 5;
break;
}
if (direction) prevDirection = direction;
$(".snake").css(prop, $(".snake").position()[prop] + value);
}, 500);
if (event.which == 40) {
move('bottom');
} else if (event.which == 39) {
move('right');
} else if (event.which == 37) {
move('left');
} else if (event.which == 38) {
move('top')
};
}
}());​
​
http://jsfiddle.net/6bKHc/42/

Related

cancel an if statement if another statement comes true

I have this function that plays different sounds to different keys. But if I press a key, then press another key right away, the previous sound will still play.
My question is, how do I cancel the previous sound when a new one is played?
Here's the code:
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(evt) {
if (evt.keyCode == "81") { //q
document.getElementById('enklyd').play();
}
if (evt.keyCode == "87") { //w
document.getElementById('lyd1').play();
}
if (evt.keyCode == "69") { //e
document.getElementById('lyd2').play();
}
if (evt.keyCode == "82") { //r
document.getElementById('lyd3').play();
}
if (evt.keyCode == "84") { //t
document.getElementById('lyd4').play();
}
if (evt.keyCode == "89") { //y
document.getElementById('lyd5').play();
}
}
This isn't really a matter of "stopping" the if statement because they are individually doing their job correctly. What you want to stop is the sound clip being played.
For this you can use the .pause() method, set the .currentTime to 0, or I believe you can also set the volume to 0 and just let it play out.
As mentioned in a comment, there are a few SO questions that may have already answered this. Is there a unique situation that isn't being answered in those?
I think this works for you:
var e = document.getElementById('enklyd');
function checkKeyPressed(evt) {
if (evt.keyCode == "81") { //q
e.pause();
e.currentTime = 0;
e = document.getElementById('enklyd');
e.play();
}
if (evt.keyCode == "87") { //w
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd1');
e.play();
}
if (evt.keyCode == "69") { //e
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd2');
e.play();
}
if (evt.keyCode == "82") { //r
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd3');
e.play();
}
if (evt.keyCode == "84") { //t
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd4');
e.play();
}
if (evt.keyCode == "89") { //y
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd5');
e.play();
}
}
Actually, the issue is not regarding the if condition. But you can try the following code, I think this will work fine for you.
window.addEventListener("keydown", checkKeyPressed, false);
var keyMap = {
"81": "enklyd", //q
"87": "lyd1", //w
"69": "lyd2", //e
"82": "lyd3", //r
"84": "lyd4", //t
"89": "lyd5", //y
};
var prevPlayed = null, target = null, prevTarget = null;
function checkKeyPressed(evt) {
prevTarget = document.getElementById(keyMap[prevPlayed])
target = document.getElementById(keyMap[evt.keyCode]);
if (prevPlayed !== null && prevTarget !== null)
prevTarget.pause();
if (keyMap[evt.keyCode] && target !== null) {
target.currentTime = 0;
target.play();
}
prevPlayed = evt.keyCode;
}
You should use 'switch' instead of using 'if'.Just add a common class to all your elements
const yourDiv = document.querySelector('yourDiv');
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(evt) {
yourDiv.currentTime = 0;
switch(evt) {
case '81':
document.getElementById('enklyd').play();
break;
case '87' :
document.getElementById('lyd1').play();
break;
case '69' :
document.getElementById('lyd2').play();
break;
case '82' :
document.getElementById('lyd3').play();
break;
case '84' :
document.getElementById('lyd4').play();
break;
case '89' :
document.getElementById('lyd5').play();
break;
default :
return null;
}
}

Simple move javascript game

what wrong with my code
function move(x,y)
{
setInterval(function()
{
gameArea.clear();
gamePiece.x += x;
gamePiece.y += y;
gamePiece.update();
}, 100);
}
document.getElementsByTagName('body')[0].onkeyup = function(e)
{
var myInterval;
if(e.keyCode == 37)
{
move(10,0);
}
else if(e.keyCode == 38)
{
move(0,-10);
}
else if(e.keyCode == 39)
{
move(-10,0);
}
else if(e.keyCode == 40)
{
move(0,10);
}
}
This produce output i'm not expected, and the object can't move correctly.
Please help me to fixed this.

Image change on pressing keyup and keydown

I am new to JavaScript and this community. I apologize if this has been asked before, but the threads I found for this topic did not really help me with this specific problem.
I would like to achieve the following working:
Image 1 is displayed.
If you press the left arrow key (keydown) the image should change to image 2.
If you stop pressing (keyup), it should change to image 3.
If you press the right arrow key it should change to image 4 and on keyup, change to image 5.
The code is:
<img src="img/image1.png" id="myIMG">
and
var imgs = ["img/image5.png", "img/image3.png", "img/image1.png", "img/image4.png"];
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
}
var keys = {};
$(document).keydown(function (event) {
keys[event.which] = true;
}).keyup(function (event) {
if(e.keyCode == 37){
delete keys[37];
changeIMG(+1);
}
else if(e.keyCode == 39){
delete keys[39];
changeIMG(+2);
}
});
function IMGLoop() {
if (keys[37]) {
changeIMG(+3);
} else if (keys[39]) {
changeIMG(+4);
}
setTimeout(IMGLoop, 20);
}
IMGLoop();
The issue is described below.
The keyup does not do anything and the keydown only works once and then I can not even switch between left and right anymore.
I need to do this with a loop because I also want to do other things on the loop that are not displayed in this code. I would appreciate any type of help.
Hope this helps you
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e) {
if (e.keyCode == 37) {
showImageName--;
if (showImageName == -1) {
showImageName = imgs.length - 1;
}
changeIMG(showImageName);
} else if (e.keyCode == 39) {
showImageName++;
if (showImageName == imgs.length) {
showImageName = 0;
}
changeIMG(showImageName);
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e);
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e);
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">
Update after question edited
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnDWTv5oLaNgUm_SXQFSzzBJl-21c7wLCC6Hgld-ndQ1k0knly"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e, str) {
switch (str) {
case "up":
if (e.keyCode == 37) {
changeIMG(2);
} else if (e.keyCode == 39) {
changeIMG(4);
}
break;
case "down":
if (e.keyCode == 37) {
changeIMG(1);
} else if (e.keyCode == 39) {
changeIMG(3);
}
break;
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e, "down");
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e, "up");
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">

Am I using keyup correctly?

This is an excerpt from a js file
$searchBox.keyup(function(event) {
if (event.keyCode === 13) { //enter
if(currentResult > -1) {
var result = $searchResults.find('tr.result a')[currentResult];
window.location = $(result).attr('href');
}
} else if(event.keyCode === 38) { //up
if(currentResult > 0) {
currentResult--;
renderCurrent();
}
} else if(event.keyCode === 40) { //down
if(lastResults.length > currentResult + 1){
currentResult++;
renderCurrent();
}
} else {
var query = $searchBox.val();
if (lastQuery !== query) {
currentResult = -1;
if (query.length > 2) {
self.search(query);
} else {
self.hideResults();
}
if(self.hasFilter(getCurrentApp())) {
self.getFilter(getCurrentApp())(query);
}
}
}
});
This means that it should only perform the action if the "Enter", "Up" or "Down" keys are pressed, right? Because the search start happening as soon as any key is pressed.
I also tried changing searchBox.keyup to searchBox.change but that messed up how something else was working.

snake game on jquery/javascript when pressing key, snake moving faster

My JavaScript code is as follows:
$(document).keydown(function(event){
var move, inter;
clearInterval(inter);
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 1500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
};
});​
http://jsfiddle.net/6bKHc/94/
When I hold down one of the arrows keys, the snake is starting to move faster, how can I turn that off? You can test it yourself.
Your setInterval is called inside your eventhandler. Move setinterval outside, along with a shared dir variable. Then you will have no need for clearinterval.
var dir = 'bottom';
setInterval(move = function() {
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 150);
$(document).keydown(function(event){
if(event.which == 40) {
dir = 'top';
} else if(event.which == 39) {
dir = 'left';
} else if(event.which == 37) {
dir = 'right';
} else if(event.which == 38) {
dir = 'bottom';
};
});
​
http://jsfiddle.net/zatsq/

Categories