fruitSound = loadSound('B.mp3');
scoreElem = createDiv('Score = 0');
scoreElem.position(20, 20);
scoreElem.style('color', 'black');
createCanvas(windowWidth, windowHeight);
rainbow = createImage(width, height)
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
let h = map(i, 0, width, 0, 100)
rainbow.set(i, j, color(h, 100, 70));
if (isRunning == false) titleScreen();
for (let i = 0; i < numSegments - 1; i++) {
line(xCor[i], yCor[i], xCor[i + 1], yCor[i + 1]);
updateSnakeCoordinates();
function updateSnakeCoordinates() {
for (let i = 0; i < numSegments - 1; i++) {
if (direction == 'right') {
xCor[numSegments - 1] = xCor[numSegments - 2] + diff;
yCor[numSegments - 1] = yCor[numSegments - 2];
else if (direction =='up') {
xCor[numSegments - 1] = xCor[numSegments - 2];
yCor[numSegments - 1] = yCor[numSegments - 2] - diff;
else if (direction =='left') {
xCor[numSegments - 1] = xCor[numSegments - 2] - diff;
yCor[numSegments - 1] = yCor[numSegments - 2];
else if (direction =='down') {
xCor[numSegments - 1] = xCor[numSegments - 2];
yCor[numSegments - 1] = yCor[numSegments - 2] + diff;
function checkGameStatus() {
xCor[xCor.length - 1] > width ||
xCor[xCor.length - 1] < 0 ||
yCor[yCor.length - 1] > height ||
yCor[yCor.length - 1] < 0 ||
const scoreVal = parseInt(scoreElem.html().substring(8));
scoreElem.html('Your score was : ' + scoreVal);
function checkSnakeCollision() {
const snakeHeadX = xCor[xCor.length - 1];
const snakeHeadY = yCor[yCor.length - 1];
for (let i = 0; i < xCor.length - 1; i++) {
if (xCor[i] === snakeHeadX && yCor[i] === snakeHeadY) {
function checkForFruit() {
if (xCor[xCor.length - 1] === xFruit && yCor[yCor.length - 1] === yFruit) {
const prevScore = parseInt(scoreElem.html().substring(8));
scoreElem.html('Score = ' + (prevScore + 1));
updateFruitCoordinates();
function updateFruitCoordinates() {
xFruit = floor(random(10, (width - 100) / 10)) * 10;
yFruit = floor(random(10, (height - 100) / 10)) * 10;
if (keyCode === LEFT_ARROW){
if (direction !== 'right') {
else if (keyCode === RIGHT_ARROW){
if (direction !== 'left') {
else if (keyCode === UP_ARROW){
if (direction !== 'down') {
else if (keyCode === DOWN_ARROW){
if (direction !== 'up') {
text('CLICK TO START', width/2, height/2);
text('GAME OVER', width/2, height/2);
updateFruitCoordinates();
for (let i = 0; i < numSegments; i++) {
xCor.push(xStart + i * diff);