0

I want to have a function that picks a random number, and depending on the number, selects a global variable and adds it to an array, repeating 5 times. I don't know if the idea even works. Its basically for a online 2D game, It needs to pick a random card, and then have the information of the card available, so later in the game the cards can vs each other.

Ive been googling stuff for like 2 hours and it still doesnt work, im probably missing something obvious or silly.

Right now i have an empty array outside of the function, and then a random number is picked and i have if statements that will correspond to the right card which will be put in the array. I also want the array to be accesible later in other functions, like I'll have to make functions where the cards have to be compared, so i just need something that gets a random selection of 5 cards and saves their information to be used in later functions.(later i will add more else if statements since there will be 16 cards total)

<script src="https://randojs.com/1.0.0.js"></script>
<script>
    
    let centaur = { name:'Centaur', class:'Common', health:50, attack:25, defence:15, strength:10, magic:10, image:'images/Cards/2_Common/CENTAUR.png' };
    let dryad = {name:'Dryad', class:'Common', health:10, attack:10, defence:10, strength:10, magic:50, image:'images/Cards/2_Common/DRYAD.png'};
    /*let  = {name:'', class:'', health:, attack:, defence:, strength:, magic:, image:''};*/
    
    var listofran = {};
    
    function findcard(){
        var random = rando(0,6);
        while (let i=5; i>0;i--){
            if (random == 0){
            listofran.push = centaur;
            }
            else if (random ==1) {
            listofran.push = dryad;
            }
            else if (random ==2) {
            listofran.push = gryffin;
            }
            else if (random ==3) {
            listofran.push = giant;
            }
            else if (random ==4) {
            listofran.push = harpy;
            }
            else if (random ==5){
            listofran.push = satyr;
            }
            else{
            listofran.push = mermaid;
            }
        i--;

        }
    }
    
    document.getElementById('rand').innerHTML=listofran;
    
</script>

Then in the body im just trying to see if it works, so i only have this just to see if i can make the list appear.

<p>random list<span id="rand"></span></p>>

Honestly I struggle with like what components need to go in what functions and where, so yeah, just any help would be very appreciated.

sonia
  • 3
  • 1
  • 1
    `listofran.push = centaur` -> `listofran.push(centaur)` – VLAZ May 02 '21 at 15:44
  • 2
    `listofran` is a plain Object (`{}`), it does not have a `push` method. You might want to use an Array instead: `[]`; Your `findcard` method could also be reduced to only a couple of lines if you store your original items in an Array. Then you can simply do this: [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array) – blex May 02 '21 at 15:46
  • Oh! yeah, I will try that thanks – sonia May 02 '21 at 15:55
  • can an array hold objects, or "let" things. Like could i make an array that is something like cardarray = [centaur, dryad] and it takes the info from the global varyables? – sonia May 02 '21 at 15:58

2 Answers2

0

You can try this code. You need an array to hold the values and add the item inside for loop.

    
    let centaur = { name:'Centaur', class:'Common', health:50, attack:25, defence:15, strength:10, magic:10, image:'images/Cards/2_Common/CENTAUR.png' };
    let dryad = {name:'Dryad', class:'Common', health:10, attack:10, defence:10, strength:10, magic:50, image:'images/Cards/2_Common/DRYAD.png'};
    /*let  = {name:'', class:'', health:, attack:, defence:, strength:, magic:, image:''};*/
    
    
    var listofran = [];
    
    function findcard(){
        for (let i=5; i>0;i--)
        {
          var random = rando(0,6);
          if (random == 0){
            listofran.push(centaur);
          }
          else if (random ==1) {
            listofran.push(dryad);
          }
        }
    }
    findcard();
    document.getElementById('rand').innerHTML=listofran.map(x => x.name).join(',');
    
<script src="https://randojs.com/1.0.0.js"></script>
<p>random list</p><span id="rand"></span>
Ayaz
  • 2,111
  • 4
  • 13
  • 16
0

You can pick a (pseudo random) creature from an array of creatures without the need for some loop. Refactored your code to minimal reproducable example.

document.addEventListener("click", handle);

const creatures = [
  { name:'Centaur', },
  { name:'Dryad', },
  { name:'Gryffin', },
  { name:'Giant', },
  { name:'Harpy', },
  { name:'Satyr', },
  { name:'Mermaid', },
];

let listOfRan = [];

// the function tho tame the creatures
function findCard(){
  // next 2 lines are what the answer is all about
  const randomIndex = Math.floor(Math.random() * creatures.length);
  listOfRan.push(creatures[randomIndex]);
  
  // output for this example
  document.querySelector('#rand').textContent = `Last added: ${
    JSON.stringify(listOfRan.slice(-1)[0])}\n`;
  document.querySelector('#all').textContent = `All of listOfRan: ${
    JSON.stringify(listOfRan, null, 2)}\n`;
}

// Not specific for this answer
// Function to handle all events in document
function handle(evt) {
  if (evt.target.dataset.handleid === "1") {
    return findCard();
  }
  
  if (evt.target.dataset.handleid === "2") {
    return document.querySelectorAll("pre")
      .forEach( elem => elem.textContent = "");
  }
  
  if (evt.target.dataset.handleid === "3") {
    if (confirm(`Are you sure?`)) { 
      listOfRan = [];
      document.querySelector('#all').textContent = "Empty";
    }
    return;
  }
}
<button data-handleid="1">Random creature please</button>
<button data-handleid="2">Clear output</button>
<button data-handleid="3">Clear [listOfRan]</button>
<pre id="rand"></pre>
<pre id="all"></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • This is great thank you so much. Could i just ask, why did you use two functions? could you just explain that a little so understand it a bit better. – sonia May 02 '21 at 17:33
  • Also if i add more buttons this section if (evt.target.nodeName === "BUTTON") will be activated, is there a way to rewrite it so it targets a specific button? – sonia May 02 '21 at 17:38
  • The `handle` function is for the event delegation part. To target specific buttons, you can give them a unique id or data-attribute. e.g. ` – KooiInc May 03 '21 at 05:45