Fruit Matching Game with HTML, CSS, JavaScript

JavaScriptJavaScriptIntermediate
Practice Now

Introduction

In this project, you will learn how to create a simple "Fruit for Fun" game using HTML, CSS, and JavaScript. The game involves matching pairs of fruit images by clicking on the squares on the game board.

👀 Preview

finished

🎯 Tasks

In this project, you will learn:

  • How to set up the project files and directories
  • How to implement the functionality of the Start button to show and hide the fruit images
  • How to implement the functionality of clicking on the squares to display the fruit images
  • How to implement the functionality to compare the two clicked images and update the score accordingly
  • How to update the score display in real-time

🏆 Achievements

After completing this project, you will be able to:

  • Structure and organize a web development project
  • Use JavaScript to manipulate the DOM and handle user interactions
  • Use jQuery to simplify JavaScript code and animations
  • Update the user interface in real-time based on game logic

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/DOMManipulationGroup(["`DOM Manipulation`"]) jquery(("`jQuery`")) -.-> jquery/UserInterfaceInteractionGroup(["`User Interface Interaction`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/async_prog("`Asynchronous Programming`") javascript/AdvancedConceptsGroup -.-> javascript/closures("`Closures`") javascript/DOMManipulationGroup -.-> javascript/dom_traverse("`DOM Traversal`") jquery/UserInterfaceInteractionGroup -.-> jquery/ui_effects("`UI Effects`") subgraph Lab Skills javascript/variables -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/data_types -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/arith_ops -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/comp_ops -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/cond_stmts -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/functions -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/array_methods -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/obj_manip -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/async_prog -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/closures -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} javascript/dom_traverse -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} jquery/ui_effects -.-> lab-300291{{"`Fruit Matching Game with HTML, CSS, JavaScript`"}} end

Set Up the Project Structure

In this step, you will set up the project files and structure. Follow the steps below to complete this step:

Open the project folder. The directory structure is as follows:

├──css
│ └── style.css
├── Images
│ ├── apple.png
│ ├── cherry.png
│ ├── grape.png
│ ├── peach.png
│ ├── pear.png
│ ├── strawberry.png
│ ├──tangerine.png
│ └── watermelon.png
├─ js
│ ├── index.js
│ └── jquery-3.6.0.min.js
└── index.html

Click on Go Live button in the bottom right corner of WebIDE, to run the project.

Next, open "Web 8080" on the top of the VM and manually refresh it to see the page. The game does not run properly when you click the start button, as follows:

unfinished

Implement the Compare Functionality

In this step, you will implement the functionality to compare the two clicked images. Follow the steps below to complete this step:

  1. At the bottom of the js/index.js file, add the following compare() function:
// Compare two images with each other to see if they are the same
function compare() {
  if ($("#" + images[0]).attr("src") == $("#" + images[1]).attr("src")) {
    score += 2;
    $("#score").text(score);
    // Hide
    $("#" + images[0])
      .parent()
      .css("visibility", "hidden");
    $("#" + images[1])
      .parent()
      .css("visibility", "hidden");
    images = [];
    foundImage += 2;
  } else {
    score -= 2;
    $("#score").text(score);
    $("#" + images[0]).hide();
    $("#" + images[1]).hide();

    images = [];
  }
}

This function compares the source of the two clicked images. If they are the same, the score is increased by 2 and the squares are hidden. If they are not the same, the score is decreased by 2 and the images are hidden. $("#score").text(score) updates the score display in the <p>The current number of points is <span id="score">0</span></p> section of the html file in real time.

Implement the Start Button Functionality

In this step, you will implement the functionality of the Start button. Follow the steps below to complete this step:

  1. Open the js/index.js file.
  2. In the startGame() function, add the following code to show and then hide the images on the squares when the Start button is clicked:
function startGame() {
  $(".img-box img").show(1000, function () {
    $(this).hide(1000);
  });
}
  1. In the startGame() function, continue with the previous code followed by the following code to hide the "Start" button:
// Hide Start button
$("#start").css("visibility", "hidden");

Implement the Click Functionality

In this step, you will implement the functionality of clicking on the squares. Follow the steps below to complete this step:

  1. Open the js/index.js file.
  2. In the startGame() function, add the following code to handle the click event on the squares:
function startGame() {
  $(".img-box img").show(1000, function () {
    $(this).hide(1000);
  });
  // Hide Start button
  $("#start").css("visibility", "hidden");
  $(".img-box").bind("click", function () {
    var id = $(this).children().attr("id"); // Get the id of the clicked image
    images.push(id);

    if ($(this).children().is(":hidden")) {
      $(this).children().show();
    } else {
      images.pop(id);
    }
    if (images.length == 2) {
      setTimeout(compare, 500);
    }
  });
}

This code will push the ID of the clicked image to the images array. If the image is hidden, it will be shown. If the image is already shown, it will be removed from the images array. When there are two images in the images array, the compare() function will be called after a 500ms delay.

After completing these steps, the "Fruit for Fun" game should be fully functional and the finished result is as follows:

finished

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like