Implement a function for a collection of items

Hey everyone, I'm a new object developer looking to create an animation of falling cubes. I've been following a guide on Falling animation to fill a webpage

Currently, I am facing some algorithmic challenges. I'm trying to implement a similar structure to a tetris game but with the ability for multiple pixels to fall simultaneously. I have constructed a player object with various methods to control pixel movement.

My current approach involves creating an array of objects like this:

var a_player = [];

function addPlayer(pos){
  var player = new Player(pos);
  a_player.push(player);
}

addPlayer({x: 3, y: 3});
addPlayer({x: 0, y: 0});

I want to incorporate public methods such as a collide() function:

function collide(arena, player) {
  const [m, o] = [player.matrix, player.pos];
  for (let y = 0; y < m.length; ++y) {
    for (let x = 0; x < m[y].length; ++x) {
      if (m[y][x] !== 00 &&
          (arena[y + o.y] &&
          arena[y + o.y][x + o.x]) !== 0) {
            return true;
          }
    }
  }
  return false;
}

However, I am unsure of the best approach to utilize this method. Should I loop through each player in the array using a "for" loop like this?

for (i = 0; i < a_player.length; i++){
            console.log(a_player[i].pos);
}

I am concerned about efficiency since I plan to have more than 20k players eventually. Any suggestions or advice would be greatly appreciated!

Answer №1

Here is the solution you've been searching for:

 function checkCollision(board) {
  const [piece, position] = [this.shape, this.location];
  for (let y = 0; y < piece.length; ++y) {
    for (let x = 0; x < piece[y].length; ++x) {
      if (piece[y][x] !== 0 && 
          (board[y + position.y] && 
           board[y + position.y][x + position.x]) !== 0) {
            return true;
          }
    }
  }
  return false;
}
Player.prototype.checkCollision = checkCollision;

for (i = 0; i < allPlayers.length; i++){
           allPlayers[i].checkCollision(gameBoard)
}

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

When the default action is prevented for a document in JavaScript, utilize the default event within a single element

I currently have an onMousedown and an onMouseup event handler set on the document that prevents the default action. However, I have a single form element (a select field) where I want to allow the default action to occur. Is there a way to trigger it fro ...

Tips for displaying negative numbers as positive in AngularJS

After fetching data from the server using $http.Get, I have a function that calculates the total value. The total value comes out as negative (-370), which is correct. However, when I try to use this value to create an angular chart, I need to display it a ...

How to achieve an endless cycle using Promise recursion in a NodeJS environment

I am planning to replace my blocking infinite while loop with promises. My run function is quite simple - it lights up an LED and then turns it off before moving on to the next one. Since Promises do not work inside while loops, I'm exploring how I c ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

It seems impossible to modify the border style of a div element through a dropdown select menu

I have created a dropdown menu that is intended to change the border style of a div element. The dropdown uses select and option HTML tags. However, when I trigger the .change() event, the border style does not update to the selected value. Can someone ple ...

Guide on how to retrieve server error responses in javascript using axios

I am currently using axios to send form data to a Laravel backend. While I can easily access the response upon success, I am facing difficulties retrieving the error response. In my browser's developer tools, under network > response, I see the fo ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Is there a way to modify the .htaccess file within WordPress to enable cross-browser domain access?

I made changes to my WordPress .htaccess file in order to enable cross-browser domain access, but unfortunately it's not functioning as expected. Here is the updated code snippet: # BEGIN WordPress <IfModule mod_rewrite.c> Header set Access-Con ...

Pacman-inspired Javascript game - scoring limitations on horizontal paths

I'm currently working on a fun project involving JavaScript that requires creating a ninja-like game similar to pacman. The objective is to control the ninja to eat sushis and earn points based on each sushi eaten. At the moment, I am facing an issue ...

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...

When pasting text into the Tinymce editor, it will remove all styles except for bullets and tables

Currently, I am utilizing the tinymce editor and one of my requirements is to remove all styles applied to content while pasting without losing the bullets and tables. Can this be accomplished? I attempted to initialize my tinymce editor in the following m ...

Our app is experiencing popup blockers while others are not impacted

Why are popups being blocked on our application but not others when users try to share content? This is the code execution process: 1.) User enters web page. 2.) User clicks on a share icon for Facebook, Twitter, or Google Plus. 3.) Onclick event trigg ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

.NET Core ViewModel with IFormFile attribute causing AJAX Request to freeze

Users now have the option to upload images for a retail product within an Add/Edit Product modal. Product Modal ViewModel: public class ProductModalViewModel { public ProductModalViewModel() { Product = new ProductDTO(); Images = ...

Can we implement binary search recursively in an array without knowing its size beforehand?

I'm currently developing a program that utilizes binary search through recursion to find integers provided by the user, with 0 being the last integer entered. The assumption is that the numbers will be entered in ascending order and not exceed 10 inte ...

Establish boundaries for D3.js circle reports

I am currently working on a visualization project where I want to arrange cells with higher values to appear towards the top and left, similar to a gravity force. However, I am facing difficulties in keeping multiple circles within the boundaries of the re ...

Tips for developing a web-based whiteboard application

I am tasked with developing a web application that allows users to design factory layouts by dragging and dropping pre-built components like robots, manufacturing cells, and conveyors onto a canvas. The goal is to create something similar to websites such ...

Clearing and refocusing on a text input using JavaScript

I have encountered an issue in my code where I aim to disable the button if the text input field is empty. Initially, this functionality was working well. However, when I added code to clear and refocus the input box, it inadvertently enabled the button. T ...

Guide on entering data, creating visual representations, and determining optimal curve fitting

My task involves plotting points with specific coordinates: (0.8,825.5) (1.1,1096) (1.3,1293) (1.5,1404) Next, I am required to determine a best-fit curve for the given equation: y = x*( a1*x + a2 )*( 1 – a12*25 ) The values of a1, a2, and a12 ne ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...