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/
Related
I'm making a snake clone, and I've got the head to the second segment working. The rest of the body checks should run through automatically, but it cuts off the body at the second segment without going through the rest of the segments, despite the fact that it should. My code is as follows:
var pixels = document.getElementsByClassName('pixel'); // 0 to 95
var dir = 'right';
var foodEat = true;
var dead = true;
var snakeLong = 1;
var headPos;
var foodPix;
var foodMake = function(){ // Create Food pixel (Not On Snake)
var tempnum = Math.ceil(Math.random() * (95 - 5) + 5);
var pixstate = window.getComputedStyle(pixels[tempnum]).getPropertyValue('--state');
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
console.log('Repeating');
foodMake();
} else {
console.log('Food Made!');
$(pixels[tempnum]).css('--state','food');
}
}
var directSend = function(reference,direction){
if (direction == 'left'){
reference -=1;
return reference;
} else if (direction == 'up'){
reference -=12;
return reference;
} else if (direction == 'right'){
reference +=1;
return reference;
} else if (direction == 'down'){
reference +=12;
return reference;
}
}
var snakeMake = function(refer,tsnakel){ // Continue To Form Snake
if (tsnakel > 0){
var tempdir = $(pixels[refer]).css('--goFrom');
console.log(directSend(refer,tempdir));
if (tsnakel = 1){
$(pixels[directSend(refer,tempdir)]).css('--state','empty');
} else {
refer = directSend(refer,tempdir);
}
tsnakel -= 1;
snakeMake(refer,tsnakel);
}
}
var snakeHEF = function(){ // Form First Sections of Snake
var Pheadpos;
var tdir;
if (dir == 'left'){ // Previous Segment Position
Pheadpos = 1;
tdir = 'right';
} else if (dir == 'up'){
Pheadpos = 12;
tdir = 'down';
} else if (dir == 'right'){
Pheadpos = -1;
tdir = 'left';
} else if (dir == 'down'){
Pheadpos = -12;
tdir = 'up';
}
$(pixels[headPos]).css('--state','snakeHead');
$(pixels[headPos]).css('--snakePos','1');
$(pixels[headPos]).css('--goFrom',tdir);
if (snakeLong == 1){ // No Food Eaten
$(pixels[headPos+Pheadpos]).css('--state','empty');
}
if (snakeLong >= 2){ // One Food Eaten
var send;
$(pixels[headPos+Pheadpos]).css('--state','snake');
$(pixels[headPos+Pheadpos]).css('--snakePos','2');
var temppos = $(pixels[headPos+Pheadpos]).css('--goFrom');
if (temppos == 'left'){
$(pixels[headPos+Pheadpos-1]).css('--state','empty');
send = headPos+Pheadpos-1;
} else if (temppos == 'up'){
$(pixels[headPos+Pheadpos-12]).css('--state','empty');
send = headPos+Pheadpos-12;
} else if (temppos == 'right'){
$(pixels[headPos+Pheadpos+1]).css('--state','empty');
send = headPos+Pheadpos+1;
} else if (temppos == 'down'){
$(pixels[headPos+Pheadpos+12]).css('--state','empty');
send = headPos+Pheadpos+12;
}
if (snakeLong > 2){ // More Than 1 Food Eaten
snakeMake(send,snakeLong-2);
}
}
}
var Game = setInterval(function(){
$(document).keydown(function(keyPressed){
if (keyPressed.keyCode == 88){ // Reset Game [x]
for (s = 0; s < 96; s++){
var pixstate = $(pixels[s]).css('--state');
if (pixstate == 'food'){
$(pixels[s]).css('--state','empty');
}
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
$(pixels[s]).css('--state','empty');
$(pixels[s]).css('--snakePos','not');
$(pixels[s]).css('--goFrom','none');
}
}
foodEat = true;
$(pixels[0]).css('--state','snakeHead');
$(pixels[0]).css('--snakePos','1');
$(pixels[0]).css('--goFrom','left');
dead = false;
snakeLong = 1;
headPos = 0;
dir = 'right';
} // Movement Set
if (keyPressed.keyCode == 37 && dir !== 'right'){ // [<-]
dir = 'left';
} else if (keyPressed.keyCode == 38 && dir !== 'down'){ // [^^]
dir = 'up';
} else if (keyPressed.keyCode == 39 && dir !== 'left'){ // [->]
dir = 'right';
} else if (keyPressed.keyCode == 40 && dir !== 'up'){ // [vv]
dir = 'down';
}
});
if (dead == false){ //Dead Check Then Do Game Calculations
if (dir == 'left'){ // Move Head
for (s = 0; s < 8; s++){
if (headPos == 0+(12*s)){
dead = true;
}
}
if (dead == false){
headPos -= 1;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'up'){
if (headPos < 12){
dead = true;
}
if (dead == false){
headPos -= 12;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'right'){
for (s = 0; s < 8; s++){
if (headPos == 11+(12*s)){
dead = true;
}
}
if (dead == false){
headPos += 1;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'down'){
if (headPos > 83){
dead = true;
}
if (dead == false){
headPos += 12;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
}
if (foodEat == true){ // Food generator
foodMake();
foodEat = false;
}
for (s = 0; s < 96; s++){
var tpixstate = $(pixels[s]).css('--state');
if (tpixstate == 'food'){
foodPix = s;
}
}
}
for (s = 0; s < 96; s++){ // Pixel Update
var pixstate = $(pixels[s]).css('--state');
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
$(pixels[s]).css('background-color','rgb(0,170,0)');
} else if (pixstate == 'food'){
$(pixels[s]).css('background-color','rgb(270,0,0)');
} else if (pixstate == 'empty'){
$(pixels[s]).css('background-color','rgb(68,68,68)');
}
}
},750);
Edit: To reduce confusion, I have now given the entire code.
As it turns out, I was calling the code to remove the third body segment every time, (lines 76 thru 88) even when the body was supposed to be longer.(I changed it to one '--state' changer, in an if statement checking for a body length of 2) Additionally, an if statement (line 40) was using = instead of ==, causing it to count as true each time, cutting off the fourth body segment.
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.
Basically I've made a little game, but what I'm wondering is how do I make my created object not go outside the lines of the canvas. When he reaches a border I want him to stop. Any help is appreciated
Hi there i made a little demo game my self. In that game there is what you are looking for. Working demo you can find it here
So what i did was to
1) track user keyboard press
document.onkeydown = function(e) {
e = e || window.event;
if(e.keyCode == "37") player.move("left");
else if(e.keyCode == "38") player.move("up");
else if(e.keyCode == "39") player.move("right");
else if(e.keyCode == "40") player.move("down");
};
2) getting a basic config of the player position (middle in my case)
var player = {
x: Math.round((w/2)/objectSizes),
y: Math.round((h/2)/objectSizes)
}
3) then on the function play.move i track the direction and do all the restrictions
player.move = function(direction) {
/**
* A temporary object to hold the current x, y so if there is a collision with the new coordinates to fallback here
*/
var hold_player = {
x: player.x,
y: player.y
};
/**
* Decide here the direction of the user and do the neccessary changes on the directions
*/
switch(direction) {
case "left":
player.x -= speed / modifier;
if(player.currentDirection == "stand") {
player.currentDirection = "left-1";
} else if(player.currentDirection == "left-1") {
player.currentDirection = "left-2";
} else if(player.currentDirection == "left-2") {
player.currentDirection = "left-1";
} else {
player.currentDirection = "left-1";
}
break;
case "right":
player.x += speed / modifier;
if(player.currentDirection == "stand") {
player.currentDirection = "right-1";
} else if(player.currentDirection == "right-1") {
player.currentDirection = "right-2";
} else if(player.currentDirection == "right-2") {
player.currentDirection = "right-1";
} else {
player.currentDirection = "right-1";
}
break;
case "up":
player.y -= speed / modifier;
if(player.currentDirection == "stand") {
player.currentDirection = "up-1";
} else if(player.currentDirection == "up-1") {
player.currentDirection = "up-2";
} else if(player.currentDirection == "up-2") {
player.currentDirection = "up-1";
} else {
player.currentDirection = "up-1";
}
break;
case "down":
player.y += speed / modifier;
if(player.currentDirection == "stand") {
player.currentDirection = "down-1";
} else if(player.currentDirection == "down-1") {
player.currentDirection = "down-2";
} else if(player.currentDirection == "down-2") {
player.currentDirection = "down-1";
} else {
player.currentDirection = "down-1";
}
break;
}
/**
* if there is a collision just fallback to the temp object i build before while not change back the direction so we can have a movement
*/
if(check_collision(player.x, player.y)) {
player.x = hold_player.x;
player.y = hold_player.y;
}
/**
* If player finds the coordinates of pokeball the generate new one, play the sound and update the score
*/
if(player.x == pokeball.x && player.y == pokeball.y) { // found a pokeball !! create a new one
console.log("found a pokeball of "+pokeball.spritePosition+"! Bravo! ");
pokePick.pause();
pokePick.currentTime = 0;
pokePick.play();
score += 1;
pokeball.generatePosition();
}
update();
};
Then at last i have this function to check any collision
/**
* Our function that decides if there is a collision on the objects or not
* #function
* #name check_collision
* #param {Integer} x - The x axis
* #param {Integer} y - The y axis
*/
function check_collision(x, y) {
var foundCollision = false;
if(((x > 3 && x < 9) && y == 6) || ((x > 4 && x < 9) && (y == 5 || y == 4 || y == 3))) { //collision on house
console.log("on house");
foundCollision = true;
}
if((x<1 || x>20) ||
(y<2 || y>20) ||
((y > 0 && y < 4) && (x == 20 || x == 19)) || //right corner
((y > 0 && y < 4) && (x == 2 || x == 3)) || //left corner
((y > 18) && (x == 2 || x == 3)) || //left corner
((x > 17) && (y == 19 || y == 20)) || //left corner
((x > 19) && (y == 17 || y == 18)) //left corner 2
) {
console.log("lost on the woods");
foundCollision = true
}
return foundCollision;
}
I have tried to make a code where a ball only moves when I press the arrow keys and when I let go it stops, but it continues to move. How can I fix this?
This is the part of the code that I have written:
document.onkeydown = function tast (e) {
if (e.keyCode == 39) { // høyre
høyre = 1;
} else {
høyre = 0;
console.log("ikke høyre")
}
if (e.keyCode == 37) { // venstre
venstre = 1;
} else {
venstre = 0;
}
if (e.keyCode == 38) { // opp
opp = 1;
} else {
opp = 0;
}
if (e.keyCode == 40) { // ned
ned = 1;
} else {
ned = 0;
}
}
if (venstre == 1){
kuler[0].x -= 4;
}
if (høyre == 1){
kuler[0].x += 4;;
}
if (opp == 1){
kuler[0].y -= 4;
}
if (ned == 1){
kuler[0].y += 4;
}
Other then setting your values to 0 on else. Use a onkeyup event handler. Then for onkeypress set your values to 1. And onkeyup set them to 0:
document.onkeydown = function tast (e) {
if (e.keyCode == 39) høyre = 1;
if (e.keyCode == 37) venstre = 1;
if (e.keyCode == 38) opp = 1;
if (e.keyCode == 40) ned = 1;
}
document.onkeyup = function tast2 (e) {
if (e.keyCode == 39) høyre = 0;
if (e.keyCode == 37) venstre = 0;
if (e.keyCode == 38) opp = 0;
if (e.keyCode == 40) ned = 0;
}
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/