In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Below you will find the complete HTML and JavaScript code for reference. Additionally, there is a link to a jsbin demonstration of the game with all CSS, HTML, and JavaScript elements combined for easier understanding. Does anyone know how to implement a win condition that stops the game when all fish are clicked (removed) and triggers an alert saying "You Won!"?

Thank you

https://jsbin.com/fihebiwiqi/edit?html,css,output

<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>

    <link rel="stylesheet" type="text/css" href="css1.css">
    </head>

    <body  background="https://guideinparadise.files.wordpress.com/2013/01/down-below2.jpg">
      <h1>Fishing Game</h1>
      <img id="fishingrod" src ="https://pixabay.com/static/uploads/photo/2014/03/24/17/07/fishing-rod-295096_960_720.png">
    <p>Seconds:</p>
      <p id="clock"></p> 
        <form action="html.html">
        <input id='level1' type="submit" value="Level 1">
    </form> 
        <form action="html2.html">
        <input id='level2' type="submit" value="Level 2">
    </form> 
        <form action="html3.html">
        <input id='level3' type="submit" value="Level 3">
    </form> 
        <form action="html4.html">
        <input id='level4' type="submit" value="Level 4">
    </form> 
    <form action="html5.html">
        <input id='level5' type="submit" value="Bonus Level">
    </form> 


        <script> 
      document.body.style.cursor = 'none'; // remove cursor
    $(document).mousemove(function (e) { //mouse moves over image
       $('#fishingrod').offset({  
            left: e.pageX + -190,  
            top: e.pageY + -110
        });
    });

      var b = 1; 
      for (var i= 0; i<5;i++){ // create loop to display 5 fish images
      fish(b);
      }
    function position(element) {
        var x = document.body.offsetHeight-element.clientHeight;
        var y = document.body.offsetWidth-element.clientWidth;
        var Xcoord = Math.floor(Math.random()*1*x + 300);
        var Ycoord = Math.floor(Math.random()*y + 50);

        return [Xcoord,Ycoord]; 


    }

    function fish() {

        var img = document.createElement('img'); 
        img.className = 'fish2';
        img.setAttribute("style", "position:fixed;");
        img.setAttribute("src", "http://res.freestockphotos.biz/pictures/16/16806-illustration-of-a-cartoon-blue-fish-pv.png"); 
        img.setAttribute("width", "200");
        document.body.appendChild(img);
        var xy = position(img); 
        img.style.top = xy[0] + 'px'; 
        img.style.left = xy[1] + 'px'; 
       $(img).click(function(){ $(this).remove();}); 

    }
      myTimer = setInterval(myCounter, 1000); 
      var seconds = 0; 
      function myCounter() {
        document.getElementById("clock").innerHTML = ++seconds; 
    }
        </script>

    </body>
    </html>

Answer №1

There is a function fisk(b); that you have defined, but the argument is never utilized...
The variable myTimer does not have a var declaration and should be initialized at the beginning of the code.

Initialize a new variable:

var fishes = 5;

Use this variable in your for loop (instead of hardcoding 5)
Then update this line

$(img).click(function(){ $(this).remove();});
to:

$(img).click(function(){

     fishes -= 1;
     $(this).remove();

     if(!fishes) {
        clearInterval(myTimer);
        alert("It took you "+ seconds +" seconds.");
     }

});

Answer №2

To keep track of counts, you have the option to use a global counter or incorporate a counter within the fisk() function (functions can act as objects).

In the example below, we demonstrate how to integrate a variable into the function. If you prefer a global variable instead, simply substitute fisk.counter with fisk_counter - just remember to initialize var fisk_counter = 0 outside of your function.

I've trimmed down the content in the fisk() function for illustrative purposes, allowing you to observe the modifications made.

function fisk() { //creating a function
    fisk.counter += 1; // increase counter
    var img = document.createElement('img'); // creates an element 
    $(img).click(function(){
        $(this).remove();
        fisk.counter -= 1; // decrease counter
        if( fisk.counter === 0 ) { // checks if all fish have been removed
            // GAME WON =)
        }
    });
}
fisk.counter = 0; // Include counter in the function

Answer №3

By removing the fishes from the DOM, you eliminate any chance of clicking on them again after they've been taken out. To keep track of the clicks, consider storing the count in a closure variable. Here's a suggestion:

var totalFish = 5; // Use this value in your loop that invokes the fisk() function

function winGame() {
   // Add code here to indicate that you've won the game
}

(function() {
   var removedCount = 0;
   function fisk() {
      // Set up your code;
      $(img).click(function() {
         removedCount++;
         if(removedCount === totalFish) {
            winGame();
         } else {
            $(this).remove();
         }
      });
   }
}());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Whenever I attempt to use for or while loops in my application, it consistently crashes

I've recently started learning reactjs and I'm working on a simple app. I created a decrement button that should only work if the item count is greater than or equal to zero. However, when I tried using while and for loops in my code, my app cras ...

AngularJS $resource sends the id as a query parameter rather than including it in the URL

I'm trying to retrieve data from a rest API by using the product id as part of the URL, rather than as a query parameter. Here is the factory code: .factory('Products', ['$resource', function($resource) { return $reso ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

Tips for sending JSON information to a partial view

I have a main page with a layout that includes a dropdown menu and a section for displaying different partial views. I chose this setup because I want to have 4 links, each loading a unique partial view. <div class="selectOption1" id="custNum"& ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

Utilizing AJAX to submit an array of form inputs and securely storing the data in MySQL using

I have a set of code below that has been functioning well for a single input field. However, I also have additional code that adds extra fields to the form when a div with id #addForm is clicked, and these inputs are named "itemName[]". <script> ...

Is there a way to use CSS to prevent a user from being able to click on a table?

My CSS table appears standard: <table class="form grid"> <thead> <tr> <th>EId</th> <th>Number</th> ...

Error: The function exec in matchExpr[type] is not defined

I made some changes to Object.prototype and now I'm running into errors with jQuery's methods on selectors. The error message I'm getting is: Uncaught TypeError: matchExpr[type].exec is not a function Additionally, when trying to use $.po ...

Tips for generating a unique user validation hash or token

I have a registration endpoint in my express app where users need to verify their email before account activation. I'm struggling with creating a hash for the verification link. I considered using JWT, but it feels like an overcomplicated solution. Is ...

Navigation panel positioned on one side filling up the entire content container

I am currently developing a fresh website design. I envision a layout with the header positioned at the top, content in the middle, and a footer that will either stay at the bottom of the window if the content is minimal, or go to the bottom of the content ...

Focusing on styling specifically for Chrome rather than Safari using SCSS

Is there a method to specifically target only Chrome browsers within a mixin in SCSS? @mixin { &:after { border-bottom:black; @media screen and (-webkit-min-device-pixel-ratio:0) { border-bottom: red; } } } Currently, this code targets bot ...

employing flush for lodash's throttle wrapper

When using TypeScript with JavaScript and Angular: I am trying to use the throttle decorator from lodash to limit an API call while a user is navigating around the page, ensuring that it fires before they leave the site. In my TypeScript constructor, I h ...

WebSocket connection issues are being experienced by certain users

While using socket.io, I encountered an issue where some users were unable to send messages with the message "I can't send a message why?". After researching the problem, it seems that the firewall or antivirus software may be blocking websockets. If ...

Creating an HTML table using an array of objects

I'm currently working on creating a function that will generate an HTML table from an array of objects. The array provided below is what I need to convert into a table. let units = [ { 'code': 'COMP2110', &apos ...

How to highlight all the text within a 'pre code block' when double-clicked using JavaScript

Is there a way to make code blocks on my blog automatically selected when double-clicked without using jQuery? Here is the code I have so far: I apologize if this is a silly question, I am still learning! <script type="text/javascript" src="https://c ...

Displaying a Bootstrap modal with empty editing information

I am facing an issue with my modal bootstrap where the data is not loading into the bootstrap even though it is being passed from the controller. The Grid on my page pulls in data from a list for Notes Object @foreach (var notes in Model) { <tr> ...

Is it possible to create an array that organizes monthly income data from a JSON file?

I'm currently developing an Accounting System where I need to display a bar chart showing the monthly Incomes and Expenses. The data is retrieved from a database using AJAX, and it returns the following JSON: { "results":{ "his ...

The process of updating UseContext global state in React Native and ensuring that the change is reflected across all screens

Struggling with updating global state values using React useContext on different screens? Attempting to change theme color in the App, but changes only appear on the current screen and not carried over to others? Looking for assistance in resolving this ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

Issue with optimizing in Webpack 4

It's past 2am and I find myself going crazy trying to identify an error. The console keeps repeating the message: "Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." I've attempted modifyi ...