how to add and subtract on single click with two different values - javascript

I am creating a game,now as the code,when i click attack,the enemies power lowers randomly,but i want same with player but the random value should be different from the one in enemies ..if possible,can there aso be a heal option to randomly raise players power and decrease it too because enemy is still attacking
appearence(current): http://amerish.webs.com/amerish/testgame.html
code:
<head>
<script>
var playerHealth=100;
var enemyHealth=100;
var strength=10;
function begin(){
document.getElementById'playerhealth').innerHTML= playerHealth;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
function hitEnemy(){
var attack=Math.floor(Math.random()*20 +strength);
enemyHealth =enemyHealth - attack;
document.getElementById('damage').innerHTML= attack;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
</script>
<body onload="begin()">
<input type="button" name="doit" id="doit" value="Attack!"
onclick="hitEnemy();">
<br /
<span>playerhealth</span>
<div style="font-ize:3em;"id="playerhealth"></div>
<span>enemyhealth</span>
<div style="font-size:3em;"id="enemyhealth"></div>
<br />
<span>You Did:</span><span style="font-size:3em;"id="damage"></span>
<span>damage</span>
</body>

This question looks like homework, did you write the code so far yourself? If you didn't, try to read through it and understand what each function is doing and where it is being invoked from.
the random value should be different from the one in enemies
Q: How can I generate random integers?
A: Here is a general-use function to generate pseudo-random integers
function rand_int(max, min) {
min = min | 0;
if (max === (max | 0))
if (max < min)
throw new RangeError("Range cannot be negative [" + min + '..' + max + ']');
else
return min + Math.floor(Math.random() * (max - min + 1));
throw new TypeError("Expected Integer for max but recieved: " + max);
}
Explanation: The random number is coming from Javascript's own Math.random which is between 0 and (but not equal to) 1. The x | 0 used to convert variables to 32-bit integers. Math.floor is used to change the floating point number into an Integer by always "rounding down". It works better than x | 0 for distributions over positive-and-negative numbers
can there aso be a heal option to randomly raise players power
Q: How can I add a random number to player's health?
A: Make a second <input> type button which causes something like the following to happen
playerHealth += rand_int(10); // add between 0 and 10
and decrease it too because enemy is still attacking
Q: Where do I put the code for the enemy turn?
A: Make a copy of the function hitEnemy, rename it to hitPlayer and change all occurances of enemy to player inside it. Then invoke it after hitEnemy is called, for example
<input
type="button" name="doit" id="doit"
value="Attack!" onclick="hitEnemy();hitPlayer();"
/>

Related

How to add functions on randomly generated numbers

Is it possible to add a function on randomly generated numbers. For example I used getRndInteger(min, max), Math.floor() and Math.random() to generate random numbers, and within those numbers you want to add function to see which of those generated numbers is the biggest. I was thinking maybe it was possible to put each randomized number in array and use Math.max() on them, but I'm not quite sure how you put those numbers in a function that for example on click, you see the generated numbers and result(the biggest number of them all) underneath it. I mainly want to know if it's even possible and if so, how. I'd be super thankful!
So I specifically want to use a random number from -35 to 76 including -35 and 76. I made a button that on click shows the randomized number. Another problem to me is, I'm not sure how to add a randomized number one after another instead of adding new one on click. (Haha sorry if it's a super newbie problem). Then I put an id on paragraph that displays the answer. And I was thinking to use the document.getElementById("") for the Math.max.apply() and make another paragraph with another ID that displays the answer.
<button onclick="document.getElementById('result').innerHTML = getRndInteger(-35,76)">Click Me</button>
Chosen number:
<p id="result"></p>
Biggest number:
<p id="result2"> </p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
<script>
Array.max = function(document.getElementById("result");) {
return Math.max.apply(document.getElementById"result");
};
</script>
When I put .getElementById() in Math.max.apply() as an array, even on click, java script no longer loads randomized number. Maybe you have to add id to the answers or something, I'm all out of ideas here. Any help would be greatly appreciated! I'd also like if I'd still use Math.max() to do this and avoid any overly complicated codes to understand the issue and use the answer in the future codes. Thank you loads!
You should store the previously generated maximum number to be able to determine that the currently generated number is higher than it. See snippet to get an idea.
(() => {
let max = null;
const range = {
min: -35,
max: 76
};
const result = document.querySelector("#result");
const maxResult = document.querySelector("#resultMax");
const allNrs = document.querySelector("p#all");
document.querySelector("button").addEventListener("click", handleButtonClick);
function handleButtonClick() {
const someRandomNumber = getRndInteger(range.min, range.max);
result.textContent = someRandomNumber;
max = max && someRandomNumber > max
? someRandomNumber
: max
? max
: someRandomNumber;
maxResult.textContent = max;
allNrs.textContent += ` ${someRandomNumber} `;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
})();
#all {
max-width: 400px
}
<p>
<button>Click Me</button>
</p>
Random number:
<span id="result"></span>
<br>Biggest number until now:
<span id="resultMax"></span>
<div>
<br>All numbers until now:
<p id="all"></p>
</div>

Random Number Generator Inside a var element is giving the same output each time its called on

So I'm trying to make a JS project that involves RNG (random number generation).
I'm using a var object with the random number generator in it. Heres an example of what I'm talking about:
var RNG = Math.floor(Math.random() * (863 - 768 + 1)) + 768;
document.getElementById("output").innerHTML = RNG +"&nbsp"+ RNG +"&nbsp"+ RNG;
I'm expecting this to give 3 different random numbers in the element with the ID "output". I instead get 3 of the same random number.
What can I do to get 3 different random numbers instead of 3 of the same random numbers?
Try using a function instead of a variable. A variable's value gets computed only once (unless you re-assign it later on) and then the result is saved in it for future uses. So a function is more adequate to your problem.
Something like this:
function RNG() {
return Math.floor(Math.random() * (863 - 768 + 1)) + 768;
}
document.getElementById("output").innerHTML = RNG() +"&nbsp"+ RNG() +"&nbsp"+ RNG();

Why is My Random Number in Javascript Code Concatenating Rather Than Adding?

I'm writing a basic random number generator (self teachingvia freeCodeCamp, going to use it for games with my 2 little boys). I'm using a basic HTML with no CSS added as the DOM and Javascript client side for the function (client side as my eldest is 5 and we have a family blog he loves to show people).
The problem is that the code below is working to a point - the Math random function is fine, it works with Math.floor well and the multiplcation * (maximum - minimum +1) is all working as expected.
The issue is that the last segment is not working: + minimum. From the results I have looked at the formula is generating a result up to and including the multiplcation bracked, but then concatenating the minimum on the end, rather than adding it to the result.
I have converted the maximum and minimum values to integers via parseInt when I first discovered the problem, in case there was an issue there (I didn't see why as they both worked fine in the multiplcation bracket), but that of course made no difference.
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
parseInt(maximum);
parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
<div id="dice">
<form name="randomDice">
<h1>Get a random number</h1>
<p>Maximum</p>
<input id="maximum" type="number" name="random"><br>
<p>Minimum</p>
<input id="minimum" type="number" name="random"><br>
<br>
<button onclick="randomNumberFunction()">Get a random number</button>
</form>
</div>
I'm looking to be able to capture the minimum and maximum values a user inputs, and produce a random integer from that range. Instead I get values like 01 when I input min 1, max 4, or 21. or 63 when inputting min 3, max 10.
You aren't assign value when you cast minimum and maximum variables
Try this:
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
maximum = parseInt(maximum);
minimum = parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}

Score counter doesn't count scores properly

First off, I have to say that I am very new to Javascript and programming in general so it's possible that the issue is related to my (current) lack of knowledge.
I've tried to make a simple game where a computer thinks of a random number between 0 and 10 and the user tries to guess that number by typing his guess in the text field. If the number is correct, the user gets the message that they guessed the number correctly and otherwise, they get the message that the numbers are not correct.
The first part works as intended. The problem is the score counter.
So this is the part of the HTML code that I wrote for the counter:
<p id="points">Number of points: </p><span id="points-number">0</span>
And this is the code that I wrote in JS:
<script type="text/javascript">
document.getElementById("instructions").onclick = function() {
alert("You need to guess the number that your computer imagined. Viable numbers are between 0 and 10. Every time you guess the number, score increases by 1 and every time you miss, you will lose a point")
}
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
var pointsNumber = 0;
randomNumber = Math.floor(Math.random() * 10);
ourNumber = document.getElementById("input").value;
if (ourNumber == randomNumber) {
alert("The numbers are equal!");
pointsNumber+=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
} else {
alert("The numbers are not equal! The number that your computer imagined is:" + randomNumber + ", and our number is: " + ourNumber);
pointsNumber-=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
}
}
</script>
Now here's the problem...whenever the user misses the number, the number of points goes to -1. But if he misses the second time, it stays at -1, it doesn't decrease further. After the user guesses the number, the value changes from -1 to 1. But, if he guesses again, it doesn't increase to 2, it stays at 1. Then when he misses, it jumps back to -1 and vice versa.
So, I believe I am missing something here, what should I do to make the counter work as intended? In other words, to make the score increase by 1 every time the user guesses the random number and make it decrease by 1 every time he doesn't get it right?
Thanks in advance.
basically, you are always starting with
var pointsNumber = 0;
instead, you should use:
var pointsNumber = + document.getElementById("points-number").innerHTML;
bonus:
and yes instead of:
randomNumber = Math.floor(Math.random() * 10);
use:
randomNumber = Math.floor(Math.random() * 11);
because, Math.random() lies between 0 (inclusive) and 1 (EXCLUSIVE), so could never reach 10.
see more about Math.random() at: https://www.w3schools.com/js/js_random.asp
You need to declare pointsNumber outside of the function:
var pointsNumber = 0;
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
Otherwise, each time the onclick function is called, you declare pointsNumber and set it to 0. Then it gets +1 or -1 depending on the if/else, which explains the behavior you are observing.

Var won't exceed billion

EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!

Categories

Resources