What could be causing my loop to only recognize the value of the initial array element?

function ShuffleAndDeal()
{

var shuffledDeck:Array;
var playerOneCards: Array;
var playerTwoCards: Array;  
var first:int =0;
var second:int = 1;

shuffledDeck = new Array();
playerOneCards = new Array();
playerTwoCards = new Array();

//var CardsLeft:int = Deck.length;
for(var i = 0; i < Deck.length; i++) 
{   
    Debug.Log(Deck.length);

    var randomNum = Random.Range(1,Deck.length);

    shuffledDeck.Add(Deck[randomNum]);

    Debug.Log("shuffled deck: " + shuffledDeck.length);
}

//var halfDeck: int = (shuffledDeck.length / 2);

for(var j = 0; j <=26 ; j++)
{       
    Debug.Log(first);
    Debug.Log(second);

    playerOneCards.Add(shuffledDeck[first]); 
    playerTwoCards.Add(shuffledDeck[second]);

    Debug.Log(playerOneCards[first].img);   
    Debug.Log(playerTwoCards[second].img);  

    first += 2;
    second += 2;        
}
}

When attempting to divide the array into two separate arrays, it seems to be disregarding all elements except for the first one. There are 52 Card objects loaded into the shuffleDeck[] and I am trying to split the array so that each player can have their own deck.

Here is the console window for debugging purposes:

Answer №1

It appears that the issue lies with

var ranNum = Random.Range(1,Deck.length)
.

In order for ranNum to correctly generate a random index within the bounds of the array, it should be generating a number between 0 and Deck.length - 1, as arrays in programming languages typically start indexing at 0 instead of 1.

Answer №2

The issue lies in the logging statements below:

Debug.Log(playerOneCards[first].img);   
Debug.Log(playerTwoCards[second].img);

While first and second are valid indexes for suffledDeck, each player's deck only contains half as many cards. Consider using j as the index in both logging statements instead of first or second.

It is also important to adjust your loop condition to j < 26 rather than j <= 26. Currently, you are attempting to assign 27 cards to each player's deck.

Answer №3

due to the following reason:

 Debug.Log(playerTwoCards[second].img);  

in this case, the value of second is set to 1 while your array only contains one item at index zero, resulting in an ArgumentoutofRangeException.

to resolve this issue, you can try:

  for(var j = 0; j <=26 ; j++)
  {       
    Debug.Log(first);
    Debug.Log(second);

    playerOneCards.Add(suffledDeck[first]); 
    playerTwoCards.Add(suffledDeck[second]);

    Debug.Log(playerOneCards[j].img);   
    Debug.Log(playerTwoCards[j].img);  

    first += 2;
    second += 2;        
  }

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

What is the method for showcasing a specific value using a filter?

In my app, I have the following data: birthdayGreetings:Array<any> = [ { name: 'John', date: new Date(1994, 3, 19), greeting: 'Happy Birthday, John! Good luck!', displayName: false } ]; I ...

Remove an item with AngularJS

I have a JSON file that contains data which I am able to display using AngularJS. The information is presented in rows with checkboxes and a Delete button. My goal is to remove the data from both the display and the JSON file. To delete, simply click on th ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Guide to swapping images using HTML forms and JavaScript

I have been attempting to create an image swapping code using a form with two drop-down options. The options are for color choices for an item, in this case, let's call it a widget, with both exterior and interior colors. I have been brainstorming on ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

The return statement seems to be coming up blank

Why is the return statement not producing any output or errors? I've tested it on Chrome, Firefox, and repl.it. Here's the code snippet in question: //Function that returns the product of two numbers function multiply(num1, num2){ ret ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

double<complex> overflow error size

The constant variable qwerty is set to a value of 500000, resulting in an array of doubles with that size. I am working with a signal that contains 500k samples. However, I encountered an issue when trying to use the signal as complex or double data types ...

Empty req.body in Node.js when POST method is used

I'm completely new to exploring REST and Express, and I've been following this insightful tutorial on creating a REST API. Here's a glimpse of my programming journey through the lens of my app.js code: var express = require('express&ap ...

Interactive World Map with Fluid Motion Animation built using HTML, CSS, and JavaScript

I am in need of an uncomplicated way to visually represent events taking place around the globe. This involves creating a 2D image of a world map, along with a method to show visual alerts when events occur at specific geographical coordinates [lat, lng]. ...

I am interested in manipulating the ng-show directive by referencing values in an ng-repeat array

In my coding project, I am trying to dynamically set the value of `ng-show` using a variable so that I can update it as needed. The AngularJS code snippet is as follows: var arrowup, arrowdown; arrowdown = false; $scope.header=[{"name":"Subsection ...

The object has been successfully loaded but is currently not visible

Currently, I am working with Nuxtjs and Threejs. The website's default script displays the geometry and animation correctly. However, I need to use a custom model, so I installed OBJLoader and MTLLoader using npm, which were successfully installed. & ...

When using Vuepress behind a Remote App Server, pages containing iframes may return a 404 error

Creating a static website using Vuepress was a breeze, especially since I included a dedicated section for embedded Tableau dashboards. The website functioned perfectly when accessed online without any issues, displaying the Tableau dashboards flawlessly. ...

Guidelines for utilizing basepath for specific pages in NextJS

I'm currently working on a NextJS application using version 13 and I have a question regarding setting the basepath for specific pages only. For example: "/auth/*" --> should not display the basepath "/remaining-pages" --& ...

What is the best way to organize multidimensional arrays in CakePHP?

Can anyone provide suggestions on how to achieve the desired array structure in CakePHP? I have already sorted the result set by "combined_score" and now want to sort it further based on "average_votes." The current and desired array structures are shown b ...

How can "this" be synergized with other components?

Incorporating PHP and jQuery into my project, I am faced with a challenge. Here is what I am attempting to achieve: $(this + ' .my_child_class').html('test'); Within a dynamic list of elements, when I click on a button, I use "this" t ...

Displaying minute scale from right to left using jQuery technology

I successfully created a minute scale that is functioning well, but now I am encountering an issue with displaying my scale. Instead of being oriented left to right, I would like it to be displayed from right to left. Can anyone suggest what might be wron ...

Execute the php code once more following a database row update

Is it possible to rerun a PHP line after updating a table in the database? I have an HTML button that triggers a jQuery post request: btn.onclick = function(e) { $.post('inc/pstPts.php', { pts: pts }); } I ...

Running npm build/deploy is not functioning properly and is throwing a "failed to compile errors" message

I attempted to use npm run deploy/build, but it was unsuccessful and resulted in an error in the terminal. As a novice in git and github, I am looking to upload the changes I made in my most recent commit to my github pages. However, no matter how many tim ...

Is it possible to verify the necessary node_modules for the project?

Is there a more efficient method to identify and remove unnecessary node_modules packages from my create-react-app project, rather than individually checking all utilized packages and their dependencies? I'm hoping to trim down the project's siz ...