Organize elements from an array in a clockwise manner into a container based on a boolean

I'm currently developing a visual card game and facing the challenge of organizing the seating arrangement for players around the table. The priority is to assign the player's ID, with the boolean "pov" set to "true," to the bottom container within the "_seats" structure. Subsequently, the remaining player IDs should be positioned clockwise around the table.

Furthermore, the game supports 2 to 4 players, leading to variations in the number of seats and table configurations:

For 2 Players: Seats - Bottom, Left
For 3 Players: Seats - Bottom, Left, Right
For 4 Players: Seats - Bottom, Left, Top, Right

I have devised a functional solution that achieves this objective; however, the code is lengthy and overly reliant on nested statements. I am seeking guidance on how to optimize and streamline this process effectively. Thank you in advance!

Below is an example of the array containing player information passed into the function:

let players =
    [{ name: "Player2", id: 1, admin: false, pov: false, curDealer: false },
    { name: "Player3", id: 2, admin: false, pov: false, curDealer: false },
    { name: "Player4", id: 3, admin: false, pov: false, curDealer: false },
    { name: "Player1", id: 4, admin: true, pov: true, curDealer: false }]

The object below outlines the final positions assigned to player IDs:

    _seats = {
        bottom: 0,
        left: 0,
        top: 0,
        right: 0
    };

This snippet illustrates my current implementation:

 renderPlayersAtTable(arr) {

        var seatCount = arr.length;

        arr.forEach(player => {
            if (player.pov === true) {
                this._seats.bottom = player.id

                if (seatCount === 4) {

                    switch (player.id) {
                        case 4:
                            this._seats.right = 3;
                            this._seats.top = 2;
                            this._seats.left = 1;
                            break;
                        case 3:
                            this._seats.right = 2;
                            this._seats.top = 1;
                            this._seats.left = 4;
                            break;
                        case 2:
                            this._seats.right = 1;
                            this._seats.top = 4;
                            this._seats.left = 3;
                            break;
                        case 1:
                            this._seats.right = 4;
                            this._seats.top = 3;
                            this._seats.left = 2;
                            break;
                    }
                }

                if (seatCount === 3) {

                    switch (player.id) {

                        case 3:
                            this._seats.right = 2;
                            this._seats.left = 1;
                            break;
                        case 2:
                            this._seats.right = 1;
                            this._seats.left = 3;
                            break;
                        case 1:
                            this._seats.right = 3;
                            this._seats.left = 2;
                            break;
                    }
                }

                if (seatCount === 2) {

                    switch (player.id) {

                        case 2:
                            this._seats.left = 1
                            break;
                        case 1:
                            this._seats.left = 2
                            break;
                    }
                }

            }
        })

    }

Answer №1

It is always beneficial to store data in structures and objects whenever possible. In line with this, the seatingChart has been implemented to display variations in seating arrangements based on the number of players. Since arrays in JavaScript are zero-based, the initial array in seatingChart, which represents 0 players, is empty.

Another crucial aspect is the utilization of array rotation using modulus indexing. Navigating through an entire array starting from a middle position involves looping from 0 to the array's length while incorporating the starting element and applying the modulus of the array length. For instance, if you want to start at element 3 in an array containing 0-4 elements, the desired indexes can be calculated as follows...

  • i = 0, index = ( i + 3 ) % 5 which equals 3 % 5 = 3.
  • i = 1, index = ( i + 3 ) % 5 which equals 4 % 5 = 4.
  • i = 2, index = ( i + 3 ) % 5 which equals 5 % 5 = 0.
  • i = 3, index = ( i + 3 ) % 5 which equals 6 % 5 = 1.
  • i = 4, index = ( i + 3 ) % 5 which equals 7 % 5 = 2.

Observe how the sequence of index values follows 3, 4, 0, 1, 2, traversing the entire array but starting at 3.

This fundamental concept is applied in the following for loop to initiate with the Point of View (POV) player, positioning them in the first seat (which is always designated as bottom in

seatingChart</code), and then arranging the other players accordingly throughout the array...</p>
<p><div>
<div>
<pre class="lang-js"><code>let players = [
    { name: "Player1", id: 1, admin: false, pov: false, curDealer: false, },
    { name: "Player2", id: 2, admin: false, pov: false, curDealer: false, },
    { name: "Player3", id: 3, admin: false, pov: false, curDealer: false, },
    { name: "Player4", id: 4, admin: true, pov: true, curDealer: false, }
];
    
seatingChart = [
  [],
  ['bottom'],
  ['bottom', 'top'],
  ['bottom', 'left', 'right'],
  ['bottom', 'left', 'top', 'right']
];

let _seating = {};

let povPlayerIndex = players.findIndex( p => p.pov );

for (let i = 0; i < players.length; i++ ) {
  povAdjust = ( i + povPlayerIndex ) % players.length;
  _seating[ seatingChart[ players.length ][ i ] ] = players[ povAdjust ].id; 
};

console.log( _seating );

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

Replace all line breaks in the byte stream with the sequence of characters CR LF

I am seeking a way to convert all new line separators to \r\n. The byte table consists of both \r and \r\n separators. byte[] data = (byte[]) transformedToByteObject; The 'data' variable holds the bytes, however, I am u ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Utilizing Jquery to wrap HTML content with div elements within a secure Content Management System

Despite my best efforts, I have hit a roadblock and need some help. I want to utilize Javascript/Jquery within this restrictive cms to wrap two lists in their own div. Take a look at the current code snippet below. Unfortunately, the closed cms is set in ...

Ways to activate a special function after clicking a social media button?

My goal is to implement a social media div locker on my website. The concept involves hiding a piece of text behind a div locker that prompts the user to share the content on Facebook, Google+, or Twitter in order to unlock it. After the visitor clicks on ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

"Using the selected option from a dropdown list to pass to a PHP file for autocomplete functionality

Although there is no error in the code, I am facing an issue where, after selecting an option from the brands dropdown, when I type in the product field, it passes "%" instead of the brand id (1, 2, or 3). Is there a way to modify the code so that it passe ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Unlimited height dialog overlay exclusive to Facebook

It seems like a crucial matter that needs attention. My dialog has an overlay with specific width settings as shown below: .ui-widget-overlay { width: 518px !important; } The height of the overlay will vary based on the page size controlled by JavaS ...

Comparing Items within an Array in Javascript

Forgive me if this comes across as quite basic, but I am a complete beginner when it comes to coding (though I am determined to improve!) I am working on creating a straightforward higher or lower card game using JavaScript where the user has to guess whe ...

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Having trouble retrieving the data property from the parent component within the child component slot

I am facing an issue with my Vue components. I have a rad-list component and a rad-card component. In the rad-list component, I have placed a slot element where I intend to place instances of rad-card. The rad-card component needs to receive objects from t ...

Having trouble muting the audio on my Vue audio player

I'm facing some challenges with muting the audio within my vue app. I have a list of songs that can be played, paused, shuffled, etc., but I can't seem to get the mute function working. Here's what I have in the JavaScript: mute() ...

The onClick event for a q-btn does not seem to be functioning properly when used

Inside the q-btn, there is a q-checkbox. Additionally, I included a div to style the text. <q-btn flat color="blue" class="full-width no-padding" @click="tog(item)" > <q-checkbox ...

Position the object at the center of the window

Trying to navigate the complex world of web development and facing a challenge that seems simple, yet tricky. Not quite sure how to properly refer to elements using HTML, Javascript and CSS. In my HTML page, I have used divs as clickable objects styled wi ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

The commands 'npm run watch' and 'dev' are no longer functioning on my computer for my Laravel project. I am encountering an error stating: '[webpack-cli] RangeError: Maximum call stack size exceeded'

Recently, while working on a Laravel website, I've been focusing on writing JavaScript code to integrate Meilisearch. To facilitate this process, I incorporated the 'dotenv' library with node to access variables from my .env file for securit ...

Tips for customizing the appearance of a single plot within a time series chart using FusionCharts or FusionTime

I've implemented a time series line graph using FusionCharts in the following code snippet: const MyChart = () => { const schema = [ { name: "Category", type: "string" }, { ...

Display an alert message through jQuery script if the input type file is not an image

When working with an input type file, if an image is selected it will show a preview. If something other than an image, like a PDF or DOCX file, is selected I want to show an alert as invalid. However, I am encountering an error: Cannot read property &apos ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...