Saturday, 25 March 2017

JAVASCRIPT SAMPLES - HUNGRY SNAKE

Hello Buddies.

Trying to make a simple snake like game using basic javascript and jquery this time.

The complete code is available here -


https://github.com/namitsharma99/hungrySnake





Here we go -

Logic we need to maintain while coding -

1. Arrow keys will redirect the snake into desired direction, and snake keeps on moving on its own.
2. As soon as our snake will eat up the food, that food will be removed from the screen, and a new food will be showed somewhere on the screen, using random function.
3. This will give a score up.
4. But as soon as we hit the wall, in any of the 4 directions, game gets over.
5. Reset button will reset the game.






Key-points to consider in the code -

1. Arrow keys direction -

switch (event.keyCode) { case 27: reset(); break; case 37: $("#snake0").stop() moveLeft(); break; case 39: $("#snake0").stop() moveRight(); break; case 38: $("#snake0").stop() moveUp(); break; case 40: $("#snake0").stop() moveDown(); break; }



2. Food generation and swallowing methods as follow -

function generateFood() { var max = 380; var min = 0; var randomPosX = Math.random() * (max - min) + min; var randomPosY = Math.random() * (max - min) + min; $("#food0").css({ top : randomPosY, left : randomPosX, position : 'absolute' }); }
function foodSwallowed() { var snakePos = $("#snake0"); var positionOfSnake = snakePos.position(); var leftOfSnake = positionOfSnake.left; var topOfSnake = positionOfSnake.top; var foodPos = $("#food0"); var positionOfFood = foodPos.position(); var leftOfFood = positionOfFood.left; var topOfFood = positionOfFood.top; if (Math.abs(leftOfFood - leftOfSnake) < 20 && Math.abs(topOfFood - topOfSnake) < 20) { score += 100; $("#scoreDisplay").val(score); generateFood(); } }

So, once you get the code flow, your snake is ready to flow :P

Try something better and share in the comment section for the buddies.

Happy Coding!

No comments:

Post a Comment

Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...