HomeCSSFruit Fall Game Javascript

Fruit Fall Game Javascript

Introduction:

In the ever-evolving world of web development, creating dynamic and interactive websites has become a crucial skill. In this tutorial, we will embark on a journey to build a fruit fall game using HTML, CSS, and JavaScript. Whether you’re a beginner looking to enhance your coding skills or an experienced developer seeking a refresher, this tutorial is designed to cater to all skill levels.

Things You Will Learn:

  1. HTML Setup: We’ll begin by setting up the HTML structure for the game canvas, score container, and start button.
  2. CSS Styling: Learn how to style the game elements using CSS to create an appealing visual interface.
  3. JavaScript Game Logic: Dive into the JavaScript code to understand how the game logic works. We’ll cover the creation and animation of fruits, handling user clicks, updating the score, and managing game flow.
  4. Event Handling for Touch Devices: Explore how to handle touch events to ensure a seamless gaming experience on both desktop and mobile devices.

Video Tutorial:

Here is the video tutorial for this project. If you like the tutorial subscribe to my YouTube channel. I post new projects based on HTML, CSS, and Javascript on my channel regularly.

Project Folder Structure:

Before we start coding we take a look at the project folder structure. We start by creating a folder called – ”Fruit Fall Game”. Inside this folder, we have 3 files and images. These files are :

  • index.html
  • style.css
  • script.js

HTML:

We begin with the HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fruit Fall Game</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="cover-screen">
      <h2 id="over-text" class="hide">Game Over</h2>
      <p id="result"></p>
      <button id="start-button">Start Game</button>
    </div>
    <div id="score-container" class="hide">0</div>
    <canvas id="canvas"></canvas>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

 

CSS:

Next, we style our game using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #fae6c3;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}
#score-container {
  position: absolute;
  width: 3em;
  padding: 0.5em;
  background-color: #000000;
  color: #ffffff;
  text-align: center;
  left: 0;
  top: 0.5em;
}
#start-button {
  background-color: #d6624f;
  border: none;
  padding: 1em 2em;
  font-size: 1.2em;
  border-radius: 0.3em;
  color: #ffffff;
  cursor: pointer;
}
.cover-screen {
  background-color: #fae6c3;
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.hide {
  display: none;
}
.container {
  background-color: #fae6c3;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}
.fruit {
  display: block;
  position: absolute;
  bottom: 0;
  animation: float 6s linear infinite;
  width: 100px;
}
@keyframes float {
  0% {
    bottom: 0;
  }
  100% {
    bottom: 100%;
    display: none;
  }
}

 

JS:

Finally, we add functionality using Javascript. For this once again copy the code below and paste it into your script file.

//Number of fruits
const FRUIT_COUNT = 10;

const scoreContainer = document.getElementById("score-container");
const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
const startButton = document.getElementById("start-button");
const coverScreen = document.querySelector(".cover-screen");
const result = document.getElementById("result");
const overText = document.getElementById("over-text");

const base = "./images/";
let fruits = [];
let points = 0;
const fruitsList = ["apple", "banana", "grapes"];

//Events object
let events = {
  mouse: {
    down: "mousedown",
  },
  touch: {
    down: "touchdtart",
  },
};

let deviceType = "";

let interval, randomCreationTime;
const isTouchDevice = () => {
  try {
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//Random number generator
const generateRandomNumber = (min, max) =>
  Math.floor(Math.random() * (max - min + 1) + min);

//Fruit
function Fruit(image, x, y, width) {
  this.image = new Image();
  this.image.src = image;
  this.x = x;
  this.y = y;
  this.speed = generateRandomNumber(1, 5);
  this.width = width;
  this.clicked = false;
  this.complete = false;

  //Move fruit
  this.update = () => {
    this.y += this.speed;
    if (!this.complete && this.y + this.width > canvas.height) {
      this.complete = true;
    }
  };

  //Draw fruit
  this.draw = () => {
    ctx.drawImage(this.image, this.x, this.y, this.width, this.width);
  };
  this.compare = (mouseX, mouseY) => {
    return (
      mouseX >= this.x &&
      mouseX <= this.x + this.width &&
      mouseY >= this.y &&
      mouseY <= this.y + this.width
    );
  };
}

//Create a new fruit
function createRandomFruit() {
  //set random time for next fruit
  randomCreationTime = generateRandomNumber(3, 9);
  if (fruits.length < FRUIT_COUNT) {
    let randomFruit =
      fruitsList[generateRandomNumber(0, fruitsList.length - 1)];
    const randomImage = `${randomFruit}.png`;
    const randomX = generateRandomNumber(0, canvas.width - 50);
    const fruitWidth = generateRandomNumber(100, 200);
    let fruit = new Fruit(randomImage, randomX, 0, fruitWidth);
    fruits.push(fruit);
  }
  if (fruits.length == FRUIT_COUNT) {
    let checker = fruits.every((fruit) => {
      return fruit.complete == true;
    });
    if (checker) {
      clearInterval(interval);
      coverScreen.classList.remove("hide");
      canvas.classList.add("hide");
      overText.classList.remove("hide");
      result.innerText = `Final Score: ${points}`;
      startButton.innerText = "Restart Game";
      scoreContainer.classList.add("hide");
    }
  }
}
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const fruit of fruits) {
    fruit.update();
    fruit.draw();
  }
  requestAnimationFrame(animate);
}
animate();
isTouchDevice();

canvas.addEventListener(events[deviceType].down, function (e) {
  let clickX =
    (isTouchDevice() ? e.touches[0].pageX : e.pageX) - canvas.offsetLeft;
  let clickY =
    (isTouchDevice() ? e.touches[0].pageY : e.pageY) - canvas.offsetTop;
  fruits.forEach(function (fruit) {
    let check = fruit.compare(clickX, clickY);
    if (check && !fruit.clicked) {
      fruit.clicked = true;
      points += 1;
      scoreContainer.innerHTML = points;
      fruit.complete = true;
      fruit.y = canvas.height;
    }
  });
});

canvas.addEventListener("touchend", (e) => {
  e.preventDefault();
});

startButton.addEventListener("click", () => {
  fruits = [];
  points = 0;
  scoreContainer.innerHTML = points;
  canvas.classList.remove("hide");
  coverScreen.classList.add("hide");
  createRandomFruit();
  randomCreationTime = generateRandomNumber(3, 9);
  interval = setInterval(createRandomFruit, randomCreationTime * 1000);
  scoreContainer.classList.remove("hide");
});

 

Conclusion:

By the end of this tutorial, you’ll have gained valuable insights into creating a fruit fall game using HTML, CSS, and JavaScript. The structured project folder, coupled with the detailed code walkthrough, ensures that you not only understand the code but also develop good coding practices. Now, go ahead and start building your own dynamic web projects with confidence!

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5 − 3 =

Most Popular