What is the best way to retrieve a single result from a JavaScript for loop?

I've been working on a small JavaScript Zombie game using the p5 library. The goal is to keep track of hits when clicking on a Zombie and misses when failing to hit one. However, I'm facing an issue where 10 results are displayed per click when there are 10 Zombies in the array. Finding a solution has been challenging and I don't want to complicate the game with messy code. Thank you for any help!

// object storing arrays

let zom = [];
let hb = 25;

// player info and ui
;
let hits = 0;
let missed = 0;


function setup() {
  let cnv = createCanvas(600, 300, P2D);



  let pos = createVector((width / 2), (height / 2));
  // zombie spawnpoints
  let zp0 = createVector(height / 4 + 35, height / 3);
  let zp1 = createVector(width - 35, height / 2);


  zom.push(new Zombie(zp0));
  zom.push(new Zombie(zp1));


}

function draw() {
  background(220);
  fill(0);
  text("hits: " + hits, 10, 10);
  text("missed: " + missed, 10, 20);
 

  for (let i = 0; i < zom.length; i++) {
    zom[i].move();
    zom[i].show();
  }

}

function Zombie(pos) {

  this.pos = pos;

  Zombie.prototype.move = function() {
    this.pos.x += 0.2;
    if (this.pos.x > width + hb) {
      this.pos.x = -hb

    }
  }
  Zombie.prototype.show = function() {

    circle(this.pos.x, this.pos.y, hb);

  }

}

function mouseClicked() {
  hitBox();
}

function hitBox() {
  let mx = mouseX;
  let my = mouseY;
  for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
      mx < zom[i].pos.x + hb &&
      my > zom[i].pos.y - hb &&
      my < zom[i].pos.y + hb) {


      hits += 1;

    } else {

      missed += 1;
    }
  }
}
 
<!DOCTYPE html>
<html lang="en">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/addons/p5.sound.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>

  <body>

    <script src="main.js"></script>


  </body>

</html>

Answer №1

It seems like the issue lies in how you are looping through all zombies on each click event and updating +1 miss or +1 hit for every single one.

A more efficient approach would be to have a method that determines if it is a hit or a miss, and then increments +1 miss or +1 hit accordingly.

Here's a simplified example:

mouseclick...{
if(isHit()){
 hits+= 1
 }else{
 missed+=1
}

}

function isHit(){
 let mx = mouseX;
 let my = mouseY;
 for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
      mx < zom[i].pos.x + hb &&
      my > zom[i].pos.y - hb &&
      my < zom[i].pos.y + hb) {
  return true
} 
}
return false
}

Answer №2

To achieve your goal, you should increase the value of hits when any zombie is hit, or increase the value of missed if all zombies are missed. This can be accomplished by iterating through each zombie and checking for hits as soon as one is found, or counting a miss if no hits are detected after looping through all zombies.

function hitBox() {
  const mx = mouseX;
  const my = mouseY;
  for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
        mx < zom[i].pos.x + hb &&
        my > zom[i].pos.y - hb &&
        my < zom[i].pos.y + hb)
    {
      // Increment hit count and exit function if zombie is hit
      hits += 1;
      return;
    }

    // If loop completes without detecting a hit, it's a miss
    missed += 1;
  }
}

This approach assumes that only one zombie can be hit at a time due to non-overlapping positions.

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

jQuery issue: Inability of "Read More" span to reappear after clicking "Read Less"

Currently in the process of creating a portfolio website that showcases project descriptions with an excerpt, revealing full details upon clicking "Read More." My experience with jQuery is limited, but I managed to implement functionality where clicking "R ...

What is the process for enabling the experimental-modules option when running an npm package's bin command?

Beginning with Node v8.5.0, the support for ES6 style modules has been introduced. import x from 'x' You can access this feature by running node using the --experimental-modules option, like so: node --experimental-modules test.mjs By utilizi ...

What is the best way to test an oclif CLI tool that interacts with a Rest API

How can I efficiently test the TypeScript code I've written for an Oclif CLI that interacts with a Node.js and Express.js REST API? I'm currently using Mocha/Chai for testing, but I'm struggling with testing the specific command code from my ...

Managing onChange in ReactQuill Editor: Best Practices

I am using the ReactQuill component in my React project. On my page, I have multiple components such as TextBox, InputNumber Box, and DropDown, each of which calls an event. <TextField error={this.state.postForm.isValidationActive && !this.stat ...

Updating the component following an API request in ReactJS

I'm currently working on a component that allows users to search for friends by entering their email address. The interface consists of an input form where users can submit the email and I want to display the friend's information below the form a ...

How can we make the lines in the Highcharts force plot take up all the available width

Our design team has specifically requested that our stacked area charts fill 100% of the chart width, instead of stopping at the tick marks. To illustrate this, they have provided a mockup: View Mockup Currently, our chart does not extend to the full wid ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...

Why isn't httpUploadProgress functioning correctly with Buffer data?

Recently, I have ventured into the world of node.js/express as I am attempting to create a multiple image uploading application utilizing cloudfront and an s3 bucket. My goal is to display a progress bar for the user by integrating socket.io for real-time ...

What Causes My Issue with $(document).ready()?

Currently delving into the world of jQuery, but I've hit a roadblock. Below is the snippet in question: var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.4.1.min.js'; script.type = " ...

PHP: Evaluating User Array Against Database Array

Currently, I am in the process of implementing a product module where users can upload a CSV file to add products. I am trying to figure out how to develop a system that will skip adding products if they already exist in the database and only add new produ ...

Tips on utilizing controllers within AngularJs directives?

In order to utilize a controller in my directive, what is the best way to access all controller functions within the directive? directive.js angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) { & ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...

Unique Quiz Application with an Array Functionality to Ensure No Duplicate Questions are

Is there a more efficient way to design this app without duplicating the code? I'm attempting to create unique questions by fetching them from an array, but when I press the NextQuestion button multiple times, sometimes it repeats the same question b ...

Is there a way to make this animation activate when the entire area in front of the link is hovered over or tapped?

I am working on an animation that needs to run behind a link. Here is an example: https://codepen.io/ehbehr/pen/KKNbOvN and below is the HTML and CSS: *, *:before, *:after { margin: 0; padding: 0; } .container { position: relative; width: 100%; ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

Matching stroke-dashoffset in SVG between two distinct paths

I am currently working on animating stroke-dashoffset for two different paths to create a drawing effect. There are buttons provided to adjust the stroke-dashoffset values. My goal is to ensure that the filled paths align vertically as they progress. Is t ...

Utilizing a singular pointer to access elements within a 2D array

There is a plethora of code snippets similar to the one below: #include <stdio.h> int main(void) { int a[2][2] = {{0, 1}, {2, -1}}; int *p = &a[0][0]; while (*p != -1) { printf("%d\n", *p); p++; } retur ...

Display and conceal information upon tweeting

Can anyone help me troubleshoot an issue with hiding the Twitter button after displaying new content? I tried adding a script to make it work, but it's still not functioning properly. Any insights on what I might be doing wrong would be greatly apprec ...

Nothing is in the Laravel array when using `$request->all()`

In the process of developing a shopping cart using Laravel. Here are the details : Routes : Route::post('/cart/add', 'CartController@store')->name('cart.store'); Route::patch('/cart/{product}', 'CartContro ...

When the same component is conditionally rendered, it does not activate the mounted() hook

I am new to Vue and eager to learn. I am attempting to conditionally render a component like so: <div> <Map v-if="bool" mapSrc="src1.jpg" :idList="idList1" :data="dataVariable1"></Map> <Map v-else mapSrc="src2.jpg" :idList="idList ...