I have this idea to prove a theory of mine.
So what I want to happen is when I run the program it will rapidly test a random chance. So, when I launched it it would rapidly test yes or no and there is a 1/1000000000 chance of "yes" and if it was yes, It would count one number up.
I browsed Stack Overflow and I found this:
<html>
<script>
// Greetings
var words = ['Hello', 'Hey', 'What\'s up!?'];
function randomAlert() {
// Index for picking the greeting you want to show
var alertIndex;
// Generates a number between 0 and 1
var randomValue = Math.random();
// 50% chance of 'Yes'
if (randomValue < 0.5) {
alertIndex = 0;
}
// 50% chance of 'No'
else if(randomValue < 0.5) {
alertIndex = 1;
}
alert(words[alertIndex])
}
</script>
<button onClick="randomAlert()">Click me!</button>
</html>
But what happens is it makes the button and does what I want (does not work in stack overflow and i'm not sure why. It works when I run it as a file on my comp), but it does not count every time it comes out as "yes" and it has to be done manually. (That is why I have to make the chances so large)
I just read what I wrote and it sounds like I'm asking for a favor rather than asking to learn how to code it. Please, do not take this as a "job". I would like what functions to use to make a random value and rapidly test it. THNX
If you want to do more than 1 draw, then you'll need a loop.
A for is the simplest, a while is also possible.
Also you'll need to have counters for each 'low or high' outcome.
I have made those changes, with a slightly different chance setting to keep it from running forever, with this result:
<script type="text/javascript">
function randomCount() {
var countLow = 0;
var countHigh = 0;
var cutOff = 1 / 1000;
var totalTries = 10000;
for (var i = 0; i < totalTries; i++) {
var randomValue = Math.random();
if (randomValue < cutOff)
countLow++;
else
countHigh++;
}
console.log("Result: countLow = " + countLow + ", countHigh = " + countHigh + ".");
}
</script>
<button onClick="randomCount()">Click me!</button>
Related
I'm making a very each game for school project, it should works like this:
User click spin, 3 cards will display elements
If all 3 cards matches, the balance will add $50, and pop up alert "you won!"
Otherwise, it will subtract $10 for each spin doesn't match.
If the balance fall below $10, pop up alert "you have less than $10.
I'm trying to make the alert pop up after the slots rendered and balance updated, however the alert always pop up ahead. Any idea how to fix it?
let slotsContainer = document.getElementById('slots');
let balanceContainer = document.getElementById("balance-container");
let tries = document.getElementById("tries");
const INITIAL_AMOUNT = 1000;
let values = ['❤', '🌞', '👻'];
let number_of_spinners = 3;
let spinCount = 0;
let slot_els = [];
let balance = INITIAL_AMOUNT;
balanceContainer.innerHTML = balance;
function render(result) {
slotsContainer.innerHTML = '';
for (var i = 0; i < number_of_spinners; i++) {
let spinner = document.createElement('div');
spinner.innerHTML = result[i];
slotsContainer.appendChild(spinner);
slot_els.push(spinner);
}
}
render(['?', '?', '?'])
function getOneRandomNumber() {
return Math.floor(Math.random() * values.length);
}
function spin_func() {
let firstRandomValue = getOneRandomNumber();
let secondRandomValue = getOneRandomNumber();
let thirdRandomValue = getOneRandomNumber();
render([values[firstRandomValue], values[secondRandomValue], values[thirdRandomValue]]);
if ((firstRandomValue === secondRandomValue) && (secondRandomValue === thirdRandomValue)) {
balance += 50;
balanceContainer.innerHTML = balance;
alert("you won!");
} else {
if (balance >= 10) {
balance -= 10;
balanceContainer.innerHTML = balance;
} else {
alert("You have less than $10");
}
}
console.log('spin!!!');
}
let spin_button = document.getElementById('spin');
spin_button.onclick = spin_func
The DOM is rendered asynchronously so you need to trigger the alert asynchronously.
Try replacing alert("xyz"); with setTimeout(alert, 0, "xyz"); where you are using it.
If you want the player to have time to read the result before triggering the alert, just increase the delay expressed in milliseconds from 0 to 2000 (2 seconds).
Ok. This is because the JS code runs so fast it spins but you don't see it.
This code
for (var i = 0; i < number_of_spinners; i++) {
let spinner = document.createElement('div');
spinner.innerHTML = result[i];
slotsContainer.appendChild(spinner);
slot_els.push(spinner);
}
Would need to be slowed down using a delay. The delay would need to be say 1/4 of a second per animation. Then the code would allow you to see it. Afterwhich the alert would fire and it would work as expected.
The problem here now is that you would need to make the code asynchronous.
Otherwise it still will not work.
Here is a Question of SO re a loop with a delay
How do I add a delay in a JavaScript loop?
You need to make this call your alert (finish) code when the loop completes otherwise, it still won't work.
The principle is:
run a loop that fires the animation
delay the next iteration by the animation speed say 600ms
call the alert/end code when the loop completes
I trying to make a small text based rpg game, but I came across array in js and then I came to problems, I failing to increase the index number by using i instead of 0 like myArray[i]
I made a jsfiddle so you guys can see what I mean.
jsfiddle
When you press the button til you get a warming, it should increase the i to 2, but it don't, but still comes with warming and increasing the attack variable.
This is your attackUp function:
function attackUp(){
var i = 0;
var attackCost = xpforlevel[i];
if (attackCost < attackxp) {
alert("WARMING!");
attack++;
document.getElementById('attack').innerHTML = attack;
i++;
document.getElementById('i').innerHTML = i;
}
}
Notice that your var i = 0 statement doesn't really make sense (because everytime attackUp is called, i will be reset to = 0 at the beginning). To fix that, erase this var i = 0 statement from your function and put in the beginning of your JS code:
var i = 0;
var attackxp = 0;
var attack = 1;
Further, your function will only update i if attackCost < attackxp, otherwise it will change nothing. You need to put the i++; statement outside your if-block, like this:
function attackUp(){
//erase this line: var i = 0;
var attackCost = xpforlevel[i];
i++; //added this line
if (attackCost < attackxp) {
alert("WARMING!");
attack++;
document.getElementById('attack').innerHTML = attack;
//erase this line: i++;
document.getElementById('i').innerHTML = i;
}
}
As your i is a local variable, it is initiated as 0 every time you call attackUp(). You should put it besides attackxp and attack.
For more information about the scope of variable in JavaScript, see w3schools or this question.
Recently began studying Javascript, trying to read out of Javascript: The Definitive Guide and Eloquent Javascript, while going off on my own to experiment with things in order to really etch them in my memory. I thought a good way to get my head around arithmetic operations and conditional statements, I'd build a series of little games based around each Math operator, and began with addition.
function beginAdditionChallenge() {
var x = Math.ceiling(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
else {
alert("Fail.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
You can see the whole thing thus far on JSFiddle, here. The idea is that clicking the button generates a random number between 1 and 100, displays it to the user, then prompts them to provide two addends, giving them 3 attempts. If the sum of these addends is equal to the RNG number, it congratulates the user and ends the program. If they do not provide suitable addends, the loop prompts them to try again, until they've hit 3 attempts, at which point the program snarks at them and ends.
I know the event listener is not the failure point here, as when I change beginAdditionChallenge to simply display a test alert, it works, but I don't know what exactly is wrong with the loop I've created.
You did it correctly. However, Math.ceiling isn't a function and should be Math.ceil. In addition, your code (in jsfiddle) should be set to wrap in head. Why? Because right now you call initChallenge when the page loads. However, in your jsfiddle example, the code runs onLoad so the load event never gets called. Essentially, you're adding a load event after the page has loaded.
http://jsfiddle.net/rNn32/
Edit: In addition, you have a for loop that goes up to three. Therefore
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
should be
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
because when i === 2, the user's last chance has ended.
Everything is fine. Just change:-
var x = Math.ceiling(Math.random()*100);
to:-
var x = Math.ceil(Math.random()*100);
I am trying to create a function that continuously adds the same number to itself. Or simply displays multiples of one number every so many seconds with the setInterval method.
For now, let's just say I want to display multiples of ten.
I know how to get a regular while loop to simply display multiples of ten in a row, but what I want to do here is continually replace the previous text every time the function is called. I am trying to create a game and this is going to be the experience calculator. So it needs to display the total experience earned over the given time.
I was trying something along the lines of this:
window.setInterval(
function writeExp ()
{
var j;
while (rounded > 0)
{
var i = w*10;
var j = j + i;
}
document.getElementByID("exp").innerHTML=j;
}, experience)
This seems logical enough to me, but obviously something is wrong, as it does not work. I have tried googling various things like how to sum numbers in javascript or continuously sum, among others, but it is somewhat difficult to word to get it more centered to my needs. So this is the best way to get my questions answered.
There are lot of undefineds in your code, but general example would be
var interval = 1000,
result = 0,
elem = document.getElementByID("exp");
window.setInterval(function () {
result *= 10;
elem.innerHTML = result;
}, interval);
or without global variables
var interval = 1000,
multiply = function (elem) {
var result = 0;
return function () {
result *= 10;
elem.innerHTML = result;
}
};
window.setInterval(multiply(document.getElementByID("exp")), interval);
So, here's my issue.
I need to write a script to be run in the console (or via Greasemonkey) to automate clicking of certain links to check their output.
Each time one of these links is clicked, they essentially generate an image in a flash container to the left. The goal here is to be able to automate this so that the QC technicians do not have to click each of these thumbnails themselves.
Needless to say, there needs to be a delay between each "click" event and the next so that the user can view the large image and make sure it is okay.
Here is my script thus far:
function pausecomp(ms) {
ms = ms + new Date().getTime();
while (new Date() < ms){}
}
var itemlist, totalnumber, i;
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""));
for(i = 0; i < totalnumber; i = i + 1) {
console.log(i);
itemlist[i].childNodes[1].click();
pausecomp(3000);
}
Now, totalnumber gets me the total number of thumbnails, obviously, and then itemlist is a list of get-able elements so I can access the link itself.
If I run itemlist[0].childNodes[1].click() it works just fine. Same with 1, 2, 3, etc. However, in the loop, it does nothing and it simply crashes both Firefox and IE. I don't need cross-browser capability, but I'm confused.
There is a built-in JS function "setInterval(afunction, interval)" that keeps executing a given function every "interval" miliseconds (1000 = 1s).
This fiddle shows how to use setTimeout to work through an array. Here is the code:
var my_array = ["a", "b", "c", "d"];
function step(index) {
console.log("value of my_array at " + index + ":", my_array[index]);
if (index < my_array.length - 1)
setTimeout(step, 3000, index + 1);
}
setTimeout(step, 3000, 0);
Every 3 seconds, you'll see on the console something like:
value of my_array at x: v
where x is the index in the array and v is the corresponding value.
The problem with your code is that your pausecomp loop is a form of busy waiting. Let's suppose you have 10 items to go through. Your code will click an item, spin for 3 seconds, click an item, spin for 3 seconds, etc. All your clicks are doing is queuing events to be dispatched. However, these events are not dispatched until your code finishes executing. It finishes executing after all the clicks are queued and (roughly) 30 seconds (in this hypothetical scenario) have elapsed. If the number of elements is greater that's even worse.
Using setTimeout like above allows the JavaScript virtual machine to regain control and allows dispatching events. The documentation on setTimeout is available here.
People were correct with SetInterval.
For the record, here's the completed code:
/*global console, document, clearInterval, setInterval*/
var itemlist, totalnumber, i, counter;
i = 0;
function findmepeterpan() {
"use strict";
console.log("Currently viewing " + (i + 1));
itemlist[i].scrollIntoView(true);
document.getElementById("headline").scrollIntoView(true);
itemlist[i].style.borderColor = "red";
itemlist[i].style.borderWidth = "thick";
itemlist[i].childNodes[1].click();
i = i + 1;
if (i === totalnumber) {
clearInterval(counter);
console.log("And we're done! Hope you enjoyed it!");
}
}
function keepitup() {
"use strict";
if (i !== 0) {
itemlist[i - 1].style.borderColor = "transparent";
itemlist[i - 1].style.borderWidth = "medium";
}
findmepeterpan();
}
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""), 10);
counter = setInterval(keepitup, 1500);