0

The idea was simple. WHen i push a button it lets oppoSpeed as random number and players speed is always 10. If yourSpeed>=oppoSpeed you attack first. It says that oppoSpeed is undefined but i dont see why. I really want this code to be as simple as this. Can you help?

<body>
    
<button onclick="spawnEnemy()">Summon Enemy</button> <!--Here the function is triggered-->
<button class="opponent" id="atak" onclick="attackHim()" style="display:block">Atak</button>
<button class="opponent" id="obrona" onclick="defendFromHim()" style="display:block">Obrona</button>
<button class="opponent" id="ucieczka" onclick="runFromHim()" style="display:block">Ucieczka</button>

<script>

let yourHp=10
let yourSpeed=5
let yourDmg=5
let yourDefence=5



console.log("Twoje statystyki na początek wynoszą: " + "\nHp: "+ yourHp+
"\nSpeed: "+yourSpeed+ "\nDmg: "+yourDmg+"\nDefence: "+yourDefence
)
console.log("---------------")

function spawnEnemy(){ //here its defining oppoSpeed

    let oppoHp=Math.floor(Math.random() * (11))
let oppoSpeed=Math.floor(Math.random() * (11))
let oppoDmg=Math.floor(Math.random() * (11))
let oppoDefence=Math.floor(Math.random() * (11))

    console.log("Statystyki wroga wynoszą: "+ "\nHp: "+oppoHp  +
"\nSpeed: "+oppoSpeed+ "\nDmg: "+oppoDmg+"\nDefence: "+oppoDefence)
console.log("---------------")
}

function attackHim(){
    if(yourSpeed>=oppoSpeed){ //it shows the problem here
oppoHp=oppoHp-2
console.log("Zadałeś obrażenia! Hp przeciwnika wynosi: "+oppoHp)
if(oppoHp<=0){
    console.log("Pokonałeś go! Idź dalej!")
} else if(oppoHp>0){
    yourHp=yourHp-2
    console.log("Otrzymałeś obrażenia! Twoje hp wynosi: "+yourHp)
}
    }else if(yourSpeed<oppoSpeed){
yourHp=yourHp-2
console.log("Otrzymałeś obrażenia! Twoje hp wynosi: "+yourHp)
if(yourHp<=0){
    console.log("Przegrałeś! Koniec gry!")
} else if(yourHp>0){
    oppoHp=oppoHp-2
    console.log("Zadałeś obrażenia! Hp przeciwnika wynosi: "+oppoHp)
}
    }
}




</script>

</body>
olioxpl
  • 9
  • 2
  • 1
    you defind oppoSpeed in a different function, the code doesnt recognize it when you are out of the function. google for scope in javascript – codingStarter Jan 07 '23 at 21:05

1 Answers1

1

You defined oppoSpeed locally inside of your function. That means that it can only be accessed inside of spawnEnemy .To fix this problem, declare oppoSpeed outside of the function. For example:

let oppoSpeed = 0;
let oppoHp = 0;
let oppoDmg =0 ;
let oppoDefence = 0; 
function spawnEnemy(){ //here its defining oppoSpeed

  oppoHp=Math.floor(Math.random() * (11))
 oppoSpeed=Math.floor(Math.random() * (11))
 oppoDmg=Math.floor(Math.random() * (11))
 oppoDefence=Math.floor(Math.random() * (11))

    console.log("Statystyki wroga wynoszą: "+ "\nHp: "+oppoHp  +
"\nSpeed: "+oppoSpeed+ "\nDmg: "+oppoDmg+"\nDefence: "+oppoDefence)
console.log("---------------")
}

This changes the scope of the variables so that they can be accessed by any function that uses them on this script.