Snake Game Using P5Js Library In javascript
Posted By : Pushpandra Kumar | 13-Dec-2017
We have used P5JS javascript library for drawing 2D objects on the canvas.
Implemented just basic functionality like keypress event, placing food on the grid and eating food.
So, the basic structure is like this we have a used OOPs features like Objects. Here we have made a Snake object who can
We have
We have initialized our snake object at the beginning and made it globally so that we can use the snake object wherever we want. We have used an SQL variable that is a scale factor means size of the snake how much we want it fat.....LOL. Now next we have
And Main logic comes here in keyPressed() to do some action on pressing UP, DOWN, LEFT and RIGHT buttons.
You can refer the below code for more details.
Here is the Code.
script.js
var snake = new Snake();
var scl = 15;
var food;
function setup(){
createCanvas(600,600);
frameRate(10);
pickLocation();
}
function pickLocation(){
var cols = floor(width/scl);
var rows = floor(height/scl);
food = createVector(floor(random(cols)),floor(random(rows)));
food.mult(scl);
}
function draw(){
background(51);
snake.update();
snake.show();
fill(255,0,100);
rect(food.x,food.y,scl,scl);
if(snake.eat(food))
{
pickLocation();
}
}
function keyPressed(){
if(keyCode === UP_ARROW){
snake.dir(0,-1);
} else if(keyCode === DOWN_ARROW){
snake.dir(0,1);
} else if(keyCode === LEFT_ARROW){
snake.dir(-1,0);
} else if(keyCode === RIGHT_ARROW){
snake.dir(1,0);
}
}
function Snake(){
this.x = 0;
this.y = 0;
this.xSpeed = 2;
this.ySpeed = 0;
this.total = 0;
this.tail = [];
this.death = function(){
for(var i=0;i
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script src="js/snake.js" type="text/javascript" ></script>
<script src="js/p5.js" type="text/javascript" ></script>
<!-- <link rel="stylesheet" type="text/css" href="css/snake.css" /></link> -->
<title>Snake Game</title>
</head>
<body>
<div id="score"></div>
</body>
</html>
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pushpandra Kumar
Pushpender has experience in Core Java, C & C++. His hobbies are learning new technologies and listening music.