I have a "guess a random number" game, where my code generates a random number between 1 and 100, and you try and guess the number. I'd like to have a reset button that refreshes the game by changing the variable with the random number in it. This is the relevant code I have.
var comparedNumber = RandomNumber();
function RandomNumber(){
var randomNumber = Math.floor(Math.random() * 100) + 1;
return randomNumber;
};
refresh.onclick = function(){
genComparedNumber();
};
Function Random Number runs on page load, but I can't seem to get comparedNumber to change.
Same logic as #juvian's answer
var Game = {
comparedNumber : randomNumber(),
refreshNumber : function(){
this.comparedNumber = randomNumber();
alert(this.comparedNumber);
},
refreshButton : document.querySelector("#refresh-button")
}
function randomNumber(){
var randomNumber = Math.floor(Math.random() * 100) + 1;
return randomNumber;
}
Game.refreshButton.addEventListener("click",Game.refreshNumber,false);
<button id="refresh-button">Refresh</button>
Related
Recently I'm making the website which should contain the counter of population.
The idea is to add a random number(1-10) every second.
I've come up with the following piece, but it refreshes every time I restart the page.
var population = 150
var random = Math.floor(Math.random() * 10) +1;
var t = setInterval(function() {
population += random;
document.getElementById("pop").innerHTML = population;
}, 1000);
Thanks in advance!
var population = parseInt(localStorage.getItem("population")) || 150;
var random = Math.floor(Math.random() * 10) +1;
var t = setInterval(function() {
population += random;
document.getElementById("pop").innerHTML = population;
}, 1000);
localStorage.setItem("population", population);
Using local storage and parse Int you can get value after oge refresh also
I am generating a random number on click in jQuery. At the end of this post, you can see the code that I am working with.
Is there a way where every time a new random number gets generated it gets added to the old one in a variable called totalRandomNumbers?
I want to do it for all three variables random, random_0, random_1.
$("#reset").click(function(){
var random = Math.floor(Math.random() * 12);
var random_0 = Math.floor(Math.random() * 12);
var random_1 = Math.floor(Math.random() * 12);
$("#push0").html(random);
$("#push1").html(random_0);
$("#push2").html(random_1);
$('input[name="hamPush"]').val($("#push0").html());
$('input[name="zikPush"]').val($("#push1").html());
$('input[name="musPush"]').val($("#push2").html());
})
At the start of your JavaScript, make a variable:
var totalRandomNumbers = 0;
And when you generate your random number, add it to the variable.
totalRandomNumbers += (code to generate random number)
var randomSum = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};
function sumRandom() {
randomSum += getRandomInt(1, 100)
};
$('.genRandomButton').on('click', function() {
console.log(randomSum)
}
Just tried in browser console:
var _totalRandomNumbers = 0;
Object.defineProperty(window, "totalRandomNumbers", {
get: function() { return _totalRandomNumbers += Math.random(); }
});
console.log(totalRandomNumbers);
console.log(totalRandomNumbers);
and so on :-)
You can do anything in get accessor, store old values etc.
I am new to JavaScript, I have two roll functions for each roll of a frame. I am unable to get the values of each of those rolls into a frame function to call on and use. If someone could help this would be great! thanks in advance, My code is below.
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
I can only guess what you're trying to achieve. I refactored you code a little bit:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());
In my approach however, firstScore and secondScore are public properties.
To address the question of why the second roll can be negative: as your code currently stands, if the second roll is smaller than the first roll, the result will be negative. If you want it so that if the first roll is 6, the second roll will be a number between 0 and 4, try something like:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
Press "Run Code Snippet" over and over again to see it work.
Changes I've made:
I made a function, randomInt that gives a random number from 0 to some max number. This saves you from needing to write the same code twice.
I created a variable maxRoll that keeps track of what the highest possible roll is.
I subtract maxRoll from the first roll to determine what the max number for the second roll should be (maxRoll - rollOne). That's then given to randomInt.
So I wanted to code a simple project. When a button is clicked, the program generates a random number between 1 and 50 and then prints it inside my DIV.
I wanted a little feature that if the number happens to be 18, the background color changes to red.
So I've tried do do this many times, but the background changing randomly. No order or whatsoever.
I've tried to log the numbers, to see is there any connection between the them when it changing to red, but no luck.
However, in the console, a little grey 2 appears. Also at random times.
function getRandomNumber(){
var randomNumber = Math.floor(Math.random()*50) + 1;
return randomNumber;
}
myButton.addEventListener('click', ()=>{
para.innerHTML = getRandomNumber();
console.log(getRandomNumber());
if(getRandomNumber() === 18){
para.style.backgroundColor = "red";
}
});
Everytime you call getRandomNumber() it's generating a new number. Call it once, save it to a variable, and everything should work as you expect.
function getRandomNumber() {
var randomNumber = Math.floor(Math.random() * 50) + 1;
return randomNumber;
}
myButton.addEventListener('click', () => {
let number = getRandomNumber();
para.innerHTML = number;
console.log(number);
if (number === 18) {
para.style.backgroundColor = "red";
}
});
Set return value of getRandomNumber() as a variable. Toggle backgroundColor between "red" and "unset" or empty string ""
function getRandomNumber(){
var randomNumber = Math.floor(Math.random()* 4) + 1;
return randomNumber;
}
var para = document.querySelector("p");
var myButton = document.querySelector("button");
myButton.addEventListener("click", () => {
const rand = getRandomNumber();
para.innerHTML = rand;
para.style.backgroundColor = rand === 1 ? "red" : "unset";
});
<button>click</button>
<p></p>
Your issue is that you are calling getRandomNumber twice, which will get you two different random numbers. Save the random number to a variable var randomNumber = getRandomNumber() and then use this variable to set the innerHTML of your para and check if it's eighteen to see if the background should change.
The grey number 2 just means that the same number is being printed twice in a row.
I have been trying to find a answer for this but I couldn't really get it to work.
I need JavaScript code to display a random number 25 times with a 320ms delay for each number.
(Ignore the other things except for //start roll)
function roll() {
var win = Math.floor(Math.random() * 25) + 0
//change the button when rolling
rollButton.disabled = true;
rollButton.innerHTML = "Rolling...";
rollButton.style.backgroundColor = "grey";
rollButton.style.color = "black"
setTimeout(unDisable, 8000)
//start roll
(insert code here)
}
Thanks if you can help
You can use setInterval for make loop with some delay and clearInterval for stopping that loop !
$(function(){
t = 0;
var interval = setInterval(function(){
var win = Math.floor(Math.random() * 25) ;
var html = $('span').html();
$('span').html(html + win + '<br>')
t++;
if(t == 25)
stop();
}, 320);
function stop(){
clearInterval(interval);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
A simple thing you can do is simply:
function roll() {
//change the button when rolling
rollButton.disabled = true;
rollButton.innerHTML = "Rolling...";
rollButton.style.backgroundColor = "grey";
rollButton.style.color = "black"
setTimeout(unDisable, 8000)
//start roll
showNum(25)
}
const getRand = _ => Math.floor(Math.random() * 25) + 0
const showNum = n => {
if (n-- <= 0) {return}
document.getElementById("dispNum").innerHTML = getRand()
setTimeout(_ => showNum(n), 320)
}
It will keep spawning a new thread to print a random number while decrementing its iteration count, till it hits 0