Building a Fruit Slicer Game with HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Turn your coding skills into a gaming masterpiece! Learn step-by-step to build an interactive Fruit Slicer Game using HTML, CSS, and JavaScript. Get ready for a coding adventure!


Building a Fruit Slicer Game with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Welcome to the exciting world of web-based game development! In this guide, we'll embark on a journey to create a captivating and interactive Fruit Slicer Game using the dynamic trio of HTML, CSS, and JavaScript. As the popularity of online games continues to soar, mastering these essential web technologies opens up a realm of creative possibilities.

Why a Fruit Slicer Game?

Fruit Slicer games are not only entertaining but also provide an excellent platform for honing your HTML, CSS, and JavaScript skills. From designing a visually appealing interface to implementing intricate game logic, you'll learn the ins and outs of web game development.

What to Expect

In the following sections, we'll guide you through each step of the development process, assuming a basic understanding of HTML, CSS, and JavaScript. Whether you're a seasoned developer or a coding enthusiast, this guide is crafted to help you create a seamless and engaging gaming experience.

Are you ready to turn lines of code into a vibrant and interactive Fruit Slicer Game? Let's dive in and make your coding adventure truly fruitful!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our game.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code section by section:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used, in this case, HTML5.

2. <html lang="en">: The root element of the HTML document, indicating that the document is written in English (en for English).

3. <head>: This section contains meta-information about the document, such as the title, character set, viewport settings, and links to external resources.

  • <title>Fruit Slicer Game</title>: Sets the title of the web page to "Fruit Slicer Game."
  • <meta charset="utf-8">: Specifies the character encoding for the document as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties for responsive design, ensuring the page adjusts to the device width and starts with an initial scale of 1.0.
  • <link rel="stylesheet" href="styles.css">: Links to an external CSS file named "styles.css" to apply styles to the HTML document.
  • <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">: Links to the jQuery UI CSS file for styling.

4. <body>: The main content of the HTML document.

5. <div id="container">: Acts as a container for the entire content of the page.

6. <div id="instructions">: Displays the instructions for the game - "Slice Fruits."

7. <div id="fruitcontainer">: Contains elements related to the game, such as score display, trials left, game introduction, and the image of a fruit.

  • <div id="score">: Displays the player's score.
  • <div class="scoreDisplay">: Includes an image and the actual score value.
  • <div id="trialsleft">: Placeholder for displaying the number of trials or attempts left.
  • <div id="front">: Contains a game introduction message and an image of a fruit logo.
  • <img id="fruit1" class="fruit">: Represents an image element with the ID "fruit1" and class "fruit."

8. <div id="startReset">: Represents a button to start or reset the game.

9. <!--for game over block-->: A comment indicating the presence of a game over block.

10. <div id="gameOver"></div>: Represents a block that will be dynamically populated with content when the game is over.

11. <!--for audio files-->: A comment indicating the presence of audio files.

12. <audio id="slicesound">: Represents an audio element with the ID "slicesound."

  • <source src="audio/slicefruit.mp3"></source>: Specifies an MP3 audio source file.
  • <source src="audio/slicefruit.ogg"></source>: Specifies an Ogg audio source file.
  • <source src="audio/slicefruit.wav"></source>: Specifies a WAV audio source file.

13. <script>: Includes JavaScript files for functionality.

  • <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>: Includes the jQuery library.
  • <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>: Includes the jQuery UI library.
  • <script src="script.js"></script>: Includes a custom JavaScript file named "script.js" for the game logic.

This is the basic structure of our fruit slicer game using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the fruit slicer game is in place, the next step is to add styling to the game using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our game. Let's break down the code section by section:

1. Styling for the entire HTML document:

html {
  height: 100%;
  background: radial-gradient
(circle, #fff, rgb(189, 182, 182));
  background-image: url("");
  background-size: cover;
  font-family: cursive, sans-serif;
}
  • Sets the HTML element's height to 100%.
  • Applies a radial gradient background with a circle shape, transitioning from white to a light gray color.
  • Adds a background image from the provided URL, and scales it to cover the entire background.
  • Sets the font family for the entire page to cursive, or sans-serif if cursive is not available.

2. Styling for a container with the ID "container":

#container {
  width: 750px;
  height: 600px;
  margin: 10px auto;
  padding: 20px;
  border-radius: 10px;
  position: relative;
}
  • Sets the container's width to 750 pixels, height to 600 pixels.
  • Centers the container horizontally with margin: 10px auto.
  • Adds padding and border-radius for styling.
  • Uses relative positioning.

3. Styling for an element with the ID "front":

#front {
  font-size: 40px;
  color: #d3901d;
  width: 650px;
  height: 450px;
  padding: 10px;
  margin: 30px auto 20px auto;
  z-index: 2;
  display: none;
}
  • Sets font size, color, width, height, padding, and margin for an element with ID "front".
  • Hides the element initially with display: none.

4. Styling for child elements of the element with ID "front" that are images:

#front img {
  width: 280px;
}
  • Sets the width of images inside the element with ID "front" to 280 pixels.

5. Styling for an element with the ID "instructions":

#instructions {
  width: 450px;
  height: 50px;
  margin: 10px auto;
  font-size: 30px;
  background-color: #d3901d;
  color: #2e1d11;
  text-align: center;
  line-height: 50px;
  border-radius: 20px;
  box-shadow: 0px 4px 0px 0px #775012;
}
  • Sets width, height, margin, font size, background color, text color, and other styles for an element with ID "instructions".

6. Styling for an element with the ID "fruitcontainer":

#fruitcontainer {
  background: url("");
  background-size: cover;
  width: 650px;
  height: 450px;
  padding: 10px;
  margin: 30px auto 20px auto;
  background-color: white;
  color: black;
  text-align: center;
  font-family: cursive, sans-serif;
  overflow: hidden;
  border-radius: 20px;
  box-shadow: 0px 4px 0px 0px #4b4b4e;
  position: relative;
}
  • Sets background, size, width, height, padding, margin, background color, text color, text alignment, font family, overflow, border radius, box shadow, and positioning for an element with ID "fruitcontainer".

7. Styling for elements with the class "fruit":

.fruit {
  display: none;
  position: absolute;
}
  • Sets the default display to none and absolute positioning for elements with the class "fruit".

8. Styling for an element with the ID "score":

#score {
  display: none;
}
  • Sets the default display to none for an element with ID "score".

9. Styling for elements with the class "scoreDisplay":

.scoreDisplay {
  z-index: 1;
  display: flex;
  background-color: transparent;
  color: #888e61;
  position: absolute;
  font-size: 30px;
  justify-items: center;
}
  • Sets styles for elements with the class "scoreDisplay" including z-index, flex display, background color, text color, positioning, font size, and alignment.

10. Styling for child elements of the element with ID "score" that are images:

#score img {
  width: 40px;
  align-items: center;
  padding-right: 5px;
}
  • Sets the width, alignment, and padding for images inside the element with ID "score".

11. Styling for an element with the ID "trialsleft":

#trialsleft {
  margin-top: 7px;
  display: flex;
  position: absolute;
  left: 550px;
  background-color: transparent;
  z-index: 1;
}
  • Sets margin, display, position, left offset, background color, and z-index for an element with ID "trialsleft".

12. Styling for elements with the class "life":

.life {
  width: 30px;
  padding-right: 5px;
}
  • Sets the width and padding for elements with the class "life".

13. Styling for an element with the ID "startReset":

#startReset {
  position: relative;
  width: 90px;
  padding: 10px;
  margin: 0 auto;
  cursor: pointer;
  text-align: center;
  background-color: #8d8315;
  box-shadow: 0px 4px 0px 0px #5c5619;
  border-radius: 5px;
  transition: all .2s;
}
  • Sets positioning, width, padding, margin, cursor style, text alignment, background color, box shadow, border radius, and transition for an element with ID "startReset".

14. Styling for the "startReset" element when it is in the active state:

#startReset:active {
  background-color: #69620c;
  box-shadow: 0px 0px #5c5619;
  top: 4px;
  color: white;
}
  • Adjusts styles for the active state of the element with ID "startReset".

15. Styling for an element with the ID "gameOver":

#gameOver {
  box-sizing: border-box;
  width: 500px;
  height: 300px;
  background: transparent;
  color: #d3901d;
  text-transform: uppercase;
  text-align: center;
  font-size: 3em;
  position: absolute;
  top: 170px;
  left: 150px;
  z-index: 2;
}
  • Sets box sizing, width, height, background, text color, text transformation to uppercase, text alignment, font size, positioning, and z-index for an element with ID "gameOver".

This will give our fruit slicer game an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

html{
  height: 100%;
  background: radial-gradient(circle,#fff,rgb(189, 182, 182));  
  background-image: url(https://raw.githubusercontent.com/Saumya-07/Fruit-Slicer/master/images/bg3%20-%20Copy.jpg);
  background-size: cover;
  font-family: cursive, sans-serif;
}
#container{
    width: 750px;
    height: 600px;
    margin: 10px auto;
    padding: 20px;
    border-radius: 10px;
    position: relative;
}

#front{
    font-size: 40px;
    color: #d3901d;
    width: 650px;
    height: 450px;
    padding: 10px;
    margin: 30px auto 20px auto;
    z-index: 2;
    display: none;
}
#front img{
    width: 280px;
}
#instructions{
    width: 450px;
    height: 50px;
    margin:  10px auto;
    font-size: 30px;
    
    background-color:#d3901d;
    color: #2e1d11;
    text-align: center;
    line-height: 50px;
    border-radius: 20px;
    box-shadow: 0px 4px 0px 0px #775012;
}
#fruitcontainer{
    background: url(https://raw.githubusercontent.com/Saumya-07/Fruit-Slicer/master/images/wood-bg2.jpg) ;
    background-size: cover;
    width: 650px;
    height: 450px;
    padding: 10px;
    margin: 30px auto 20px auto;
    background-color: white;
    color: black;
    text-align: center;
    font-family: cursive,sans-serif;
    overflow: hidden;
    border-radius: 20px;
    box-shadow: 0px 4px 0px 0px #4b4b4e;
    position: relative;
}

.fruit{
    display: none;
    position: absolute;
}
#score{
    display: none;
}
.scoreDisplay{
    z-index: 1;
    display: flex;
    background-color: transparent;
    color: #888e61;
    position: absolute;
   font-size: 30px;
   justify-items:  center;
}

#score img{
    width: 40px;
  align-items: center;
   padding-right: 5px;
}
#trialsleft{
    margin-top: 7px;
    display: flex;
    position: absolute;
    left:550px;
    background-color:transparent;
    z-index: 1;
}
.life{
    width: 30px;
    padding-right: 5px;
}

#startReset{
    position: relative;
    width: 90px;
    padding: 10px;
    margin: 0 auto;
  
    cursor: pointer;
    text-align: center;
    background-color:#8d8315;
    box-shadow: 0px 4px 0px 0px #5c5619;
    border-radius: 5px;
    transition: all .2s;
}
#startReset:active{
    background-color: #69620c;
    box-shadow: 0px 0px #5c5619;
    top: 4px;
    color: white;
}

#gameOver{
    box-sizing: border-box;
    width: 500px;
    height: 300px;
    background: transparent;
    color:#d3901d;
    text-transform: upperCase;
    text-align: center;
    font-size: 3em;
    position: absolute;
    top: 170px;
    left: 150px;
    z-index: 2;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. I'll provide a breakdown of the code:

1. Variable Declarations:

  • playing: Indicates whether the game is currently being played.
  • score: Keeps track of the player's score.
  • trialsleft: Represents the number of remaining attempts (lives) the player has.
  • step: Represents the vertical step (speed) at which the fruits descend.
  • action: Stores the setInterval function for animating the fruits.
  • fruits: An array containing the filenames of different fruit images.
var playing = false;
var score;
var trialsleft;
var step;
var action;
var fruits = ['1','2','3','4','5',
'6','7','8','9','10'];

2. Document Ready Function:

  • The code inside this function runs when the document is fully loaded.
  • Initializes some elements' visibility and sets up a click event for the "Start/Reset" button.
$(function(){
// ... (code truncated for brevity)

    $("#startReset").click(function () {
        if(playing == true){
 // Reload the page if already playing
            location.reload();
        } else {
 // Initialize game settings if not playing
            // ...
            // Start the game action
            startAction();
        }
    });

 // ... (code truncated for brevity)
});

3. Game Functions:

  • addhearts: Adds heart images representing the remaining lives to the page.
  • startAction: Initiates the animation of falling fruits and handles game logic.
  • chooseRandom: Randomly selects a fruit image and updates the displayed fruit.
  • stopAction: Stops the animation of falling fruits.
// ... (code truncated for brevity)

// Add hearts representing remaining lives
function addhearts() {
    // ...
}

// Start the game action
function startAction(){
    // ...
}

// Choose a random fruit image
function chooseRandom(){
    // ...
}

// Stop the animation
function stopAction(){
    // ...
}

// ... (code truncated for brevity)

4. Event Handling:

The code includes event handling for mouseover on the fruit image, incrementing the score, playing a sound, stopping the fruit animation, hiding the fruit, and scheduling the appearance of a new fruit.

$("#fruit1").mouseover(function () {
    // ... (code truncated for brevity)
});

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

var playing = false;
var score;
var trialsleft;
var step;//for random steps
var action;//for settime interval
var fruits = ['1','2','3','4','5','6','7','8','9','10'];//for fruits

$(function(){
    //click on start or reset button
    $('#front').show();
    $("#startReset").click(function () {
        if(playing == true){
            //if we are playing
            location.reload();//reload page
        }else{
            //if we are not playing from before
            $('#front').hide();
            $('#score').show();
            playing = true;
            //set score to 0
            score = 0;
            $("#scoreValue").html(score);

            //show trials left box
           
            $('#trialsleft').show();
            trialsleft=3;
            addhearts();
    
            //hide game over box
            $('#gameOver').hide();
    
            //change button to reset game
            $('#startReset').html('Reset Game')
    
            
            //start action
            startAction();
        }
    });
        //slice a fruit
        $("#fruit1").mouseover(function () { 
            score++;// increase score
            $("#scoreValue").html(score);

            //play sound
            $("#slicesound")[0].play();

            //stop fruit
            clearInterval(action);

            //hide fruit
            $('#fruit1').hide("explode",500);//slice fruit

            //send new fruit
            setTimeout(startAction,500);
        });
     

  //functions

   //addhearts
   function addhearts() {
    $('#trialsleft').empty();
    for(i = 0 ; i < trialsleft ; i++){
        $('#trialsleft').append('<img src="https://raw.githubusercontent.com/Saumya-07/Fruit-Slicer/master/images/wrong.png" , class="life">');
    }
}

  //start action
  function startAction(){
      //generate random fruit
      $('#fruit1').show();

      //choose random fruit
      chooseRandom();
      //random position
      $('#fruit1').css({
          'left': Math.round(550 * Math.random()),
          'top': -50
      });
      //generate random step
      step=1 + Math.round(5 * Math.random());//change steps
      //descend fruits down by 10ms
      action = setInterval(function(){
          //move fruit by one step
          $('#fruit1').css('top', $('#fruit1').position().top + step);

          //check if the fruit is too low
          if($('#fruit1').position().top > $('#fruitcontainer').height()-50){
              //yes it is low
              // check trails left
              if(trialsleft > 1){
                  //generate a fruit
                  $("#fruit1").show();
                  //choose random fruit
                  chooseRandom();
                  //random position
                  $('#fruit1').css({
                      'left': Math.round(550 * Math.random()),
                      'top': -50
                  });
                  //generate random step
                  step= 1 + Math.round(5 * Math.random());//change steps
                  
                  //reduce trials by one
                  trialsleft--;
                  //populate trails left box by one
                  addhearts();

              }else{
                  //game over
                  playing=false;//we are ot playing any more
                  $("#score").hide();
                  $('#startreset').html('Start Game');
                  $('#gameOver').show();
                  $('#gameOver').html('<p>Game Over!</p><p>Your score is '+ score + '</p>');
                  $('#trialsleft').hide();
                  stopAction();//stops Action
              }
          }
      },10);
  }

  //choose random fruits
  function chooseRandom(){
      $('#fruit1').attr('src','https://raw.githubusercontent.com/Saumya-07/Fruit-Slicer/master/images/' + fruits[Math.round(9*Math.random())]+'.png');
  }
   // Stop Action
   function stopAction(){
    clearInterval(action);
    $('#fruit1').hide();
}
});

Final Output:

Building a Fruit Slicer Game with HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations on completing this exhilarating journey of building your very own Fruit Slicer Game using HTML, CSS, and JavaScript! We've covered a range of topics, from setting up the project to adding engaging animations and implementing game logic.

Remember, game development is a continuous learning process. Stay curious, explore new possibilities, and don't hesitate to share your creations with the coding community.

Thank you for joining us on this coding adventure! We hope you continue to push the boundaries of web game development and create even more amazing projects in the future. Happy coding!

Code by: Saumya Gupta

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post