Understanding Game Management with JavaScript Array Methods: A PUBG Example

In today's gaming world, many players have experienced Battle Royale games such as PUBG, COD, or Valorant. However, have you ever thought about the underlying complexity of how these games manage player counts, kills, K/D ratios, and more?

Whoever doesn't know about Battle Royale Games ,

A Battle Royale game like PUBG drops players onto an unknown map with strangers, which shrinks over time. Players jump out, find weapons, and fight to survive by killing others while avoiding the danger zone.

Let’s break this down using PUBG as an example and Imagine that this is a Real-world Game in Which Players can Eliminate Others for Survive, and explore how various JavaScript array methods could be applied. Imagine you're the Producer of the game.


Be ready for the ultimate version of this article, where I will take you from the start to the end of the Game while also explaining the JavaScript array methods

1. push(): Adding Players to the Match

Let's start with the lobby, a matchmaking area where players gather before the match begins. As players join, the count increases, and we need to track their information.

  • We create a temporary storage / queue for this specific game using a JavaScript array to store player details.

  • When a new player joins, their name is added at the end of the array using the push() method.

push() — Adds elements to the end of the array and returns its new length.

Example:

let playersQueue = ["Aarav", "Vivaan", "Arjun", "Vihaan", "Aditya"];

// Two new players, Hitesh and Piyush, join the match
playersQueue.push("Hitesh");
playersQueue.push("Piyush");

console.log(playersQueue);
// Output: ["Aarav", "Vivaan", "Arjun", "Vihaan", "Aditya", "Hitesh", "Piyush"]

Using the length property (not a method), we can easily display how many players have joined.


2. slice(): Dividing Players into Teams

Now, we need to divide the players into teams, each consisting of 4 players (a squad).

  • To do this, we use the slice() method to extract players from the queue in sets of 4 and form teams.

slice() — Returns a shallow copy of a portion of an array.

Example:

let teams = [];
for (let i = 0; i < 100; i += 4) {
    let team = playersQueue.slice(i, i + 4);
    teams.push(team);
}

console.log(teams);
// Output: Array of teams, each containing 4 players

3. pop(): Removing Players from the Queue

After Team Formation and the last player (e.g., the 100th player) joins the queue, we need to remove all players and transfer them into the plane for the match to begin.

  • To remove players, we can repetitively use the pop() method to remove the last player from the array until we only have the necessary players left.

pop() — Removes and returns the last element of the array.

Example:

let playersQueue = ["Aarav", "Vivaan", "Arjun", "Vihaan", "Aditya", "Hitesh", "Piyush", ... , "Abhinav", "Harsh", "Rohan"];
// There are 100 players in the queue

playersQueue.pop();
console.log(playersQueue);
// Output: ["Aarav", "Vivaan", "Arjun", "Vihaan", "Aditya", "Hitesh", "Piyush", ... , "Abhinav", "Harsh"]

playersQueue.pop();
console.log(playersQueue);
// Output: ["Aarav", "Vivaan", "Arjun", "Vihaan", "Aditya", "Hitesh", "Piyush", ... , "Abhinav"]

// Repeat the task until the queue is empty
for (let i = 0; i < playersQueue.length; ++i)
{
    playersQueue.pop();
}

We continue calling pop() until the queue is empty, transferring players into the match. We can Use “For Loop” for this.


Each team is formed, and now instead of just storing player names, we may need to store additional details, such as GameID, kills, Royal Pass status, device ID, cosmetics, and more. Therefore, we use an array of objects to store player information.


4. every(): Verifying Player Eligibility

In Battle Royale games, players must be over 18 years of age, and cheating is common. Therefore, before starting the match, we need to verify that no player is cheating.

  • We can use the every() method to ensure all players are eligible by checking various factors, such as their age, device ID, and any suspicious activities like unknown files or processes.

every() — Checks if all elements in the array pass a test (returns a boolean).

Example:

const allPlayers = [
  { playerId: 1, name: "Aakash", age: 21, isAllowed: undefined },
  { playerId: 2, name: "Abhinav", age: 23, isAllowed: undefined },
  { playerId: 3, name: "Anurag", age: 19, isAllowed: undefined },
  // More players...
];

let isEveryOneAllowed = allPlayers.every(isAllowed);

function isAllowed(player) {
  // Check player details (age, device ID, suspicious files, etc.)
  return player.age >= 18 && !hasCheatingProcesses(player);
}

if (isEveryOneAllowed) {
  // Start the match
} else {
  // Identify the disqualified players
}

5. find(): Identifying Disqualified Players

To find the player who is not allowed to join the match, we use the find() method. This helps us search for any player whose isAllowed property is set to false.

find() — Returns the first element that passes a test.

Example:

let isEveryOneAllowed() = allPlayers.every(isAllowed);

if(isEveryOneAllowed())
{
    // Start the Match
}
else
{
    let notAllowedPlayers = allPlayers.find(player => !player.isAllowed)
    // Remove notAllowedPlayers from that match
}

6. indexOf(): Identifying Eliminated Players

When a player is eliminated from the game, we need to remove them from the list of alive players. To do this, we first find their index in the alivePlayers array.

indexOf() — Returns the first index of a specified value.

Example:

let eliminatedPlayersIndex = [];
let index = alivePlayers.indexOf("Arjun");

console.log("Player " + index + " is Eliminated"); // Example: "Player 2 is Eliminated"
eliminatedPlayersIndex.push(index);

7. forEach(): Updating Player Stats

Once a player is eliminated, we need to update their stats, such as rank, points, final kills, and K/D ratio. We can loop through the eliminatedPlayersIndex array to update each player’s data using the forEach() method.

forEach() — Calls a function once for each array element.

Example:

eliminatedPlayersIndex.forEach(index => {
  alivePlayers[index].isEliminated = true;
  // Update other stats like rank, points, K/D ratio, etc.
});

8. filter(): Removing Eliminated and Not Allowed Players

To filter out all Eliminated and Not Allowed players from the match, we use the filter() method, which returns only those players who are still alive.

filter() — Creates a new array with elements that pass a test.

Example:

alivePlayers = alivePlayers.filter(player => 
  !player.isEliminated && 
  !notAllowedPlayers.find(element => element === player) // checking players with NotAllowedPlayers to filter them out
);

console.log(alivePlayers);

9. sort(): Ranking Players by Kills

At the end of the result for a specific team, we may want to announce the MVP of that team — the player with the most kills. To do this, we can sort the players by kills using the sort() method.

sort() — Sorts the array elements in place.

Example:

playerTeam.sort((a, b) => b.kills - a.kills);
console.log(playerTeam); // The player with the most kills will appear first

10. reduce(): Calculating Team Statistics

To calculate the total kills and total damage for a team, we can use the reduce() method. This method allows us to accumulate values across the entire team.

reduce() — Reduces the array to a single value by applying a function.

Example:

let totalStats = playerTeam.reduce((acc, player) => {
  acc.totalKills += player.kills;
  acc.totalDamage += player.points;
  return acc;
}, { totalKills: 0, totalDamage: 0 });

console.log(totalStats); // Output: { totalKills: 20, totalDamage: 2650 }

Wrapping Up!

I hope this breakdown of JavaScript array methods in a Battle-Royale Game scenario gave you a clearer perspective on how games manage complex player mechanics. It’s amazing how everyday coding concepts can apply to real-world systems.

How did you find this explanation? Was it easy to follow, or is there something you'd like to dive deeper into? I’d love to hear your thoughts and improve together. Thanks for reading — happy coding and gaming! 🎮🚀