Build a clsssic SNAKE game with P5js
Build a clsssic SNAKE game with P5js
Ref:
P5.js
p5.js is a JavaScript library for creative coding, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! p5.js is free and open-source because we believe software, and the tools to learn it, should be accessible to everyone.
Getting started with P5js
Add cdn path for p5.js in your head of index file
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"
integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
Create div to for canavs
<div id="canvasDiv"></div>
Create a sketch.js file add it in index file
<script src="sketch.js"></script>
Now do the basic setup for your canvas for p5.js
sketch.js
function setup() {
var myCanvas = createCanvas(winWidth, winHeight);
myCanvas.parent("canvasDiv");
}
function draw() {
background(51);
}
Load external fonts if needed
function preload() {
myFont = loadFont("./assets/aAbstractGroovy.ttf");
}
Use it in draw function
function draw() {
.
.
textFont(myFont);
text("Game Over", width / 2, height / 2);
textSize(20);
text("press 'r' to restart", width / 2, height / 2 + 50);
.
.
}
Now you are ready to write your game logic
Check the repo for final code Repository