I'm making a blackjacks or 21 game, and I cannot figure out why my function value won't change, basically, this function gives you a random number, and what I want it to do is, give it a new number each time this function is called, and not the same one up to three times. (depending on the users choice.) If someone is able to solve this, I would be much appreciated, thanks.
function cardNumber(a, b) {
var cardTotal = a + b;
alert(`Your card numbers are ${a} and ${b}!`);
return cardTotal;
}
var cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardSum = cardNumber(cardOne, cardTwo);
//want to give new number each time this function is called below
function moreCards(a, b) {
alert(`Your extra card is ${a}!`);
var cardTotal = a + b;
return cardTotal;
}
extraCard = cardRange[Math.floor(Math.random() * cardRange.length)];
var i;
for (i = 0; i < 3;) {
var input = prompt(`Which makes your card total ${cardSum}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null) {
window.location.replace("http://stackoverflow.com"); //placeholder link
//take this back to home.html ^^^
i += 3;
}
//Random number doesn't change
else if (input === "1") {
i++;
cardSum = moreCards(extraCard, cardSum);
}
//Random number doesn't change
else if (input === "0") {
i += 3;
}
else {
alert("Wrong input, enter 1 or 0 on your keyboard!");
}
}
When you set a variable, it only gets set once - even if you are setting it to the return of a function. To fix your code, you need to make your variable ExtraCard into a function, such as
function extraCard() {
let newCard = cardRange[Math.floor(Math.random() * cardRange.length)]
return newCard
}
and then change where you call the variable to call it as a function, like so:
else if (input === "1") {
i++;
cardSum = moreCards(extraCard(), cardSum);
}
Related
I am new in JavaScript. I am trying to link a slider and checkbox to a counter. The slider should increase the counter's value depending on the range. And then the checkboxes have fixes values depending on the users(the slider's value are users, I will explain later) that they should add to the counter if it is checked or not.
var slider = document.querySelector('#myRange'); //Input
var output = document.querySelector("#value-range"); //Output
let rangeValue = document.querySelector('#final-price'); //Counter
const boxesContainer = document.querySelector('.price-boxes__container'); //Checkboxes
I created an event for the checkboxes, so when you click on it, adds the value.
boxesContainer.onchange = function(e) {
if (e.target.classList.contains('checkbox')){
const price = parseInt(e.target.getAttribute('value'))
if (e.target.checked === true) {
total += price;
} else {
total -= price;
}
rangeValue.innerHTML = total
}
}
And I created another event for the slider as well.
slider.oninput = function () {
let value = slider.value;
userPrice(value)
output.style.left = (value/2.88);
output.classList.add("show");
rangeValue.innerHTML = prices[value-25];
function userPrice (value) {
if (value == 25) {
output.innerHTML = '6 €p'
} else {
output.textContent = `${prices[value-25] - prices[value-26]} €p`;
}
}
}
The slider has min 25, max 1000, step = 1, value = 25. Each step is one user. I created an array that has the price depending on the slider's value. Between 26-50 users 6€ per user, 51-250 4€/p, 251-500 3€/p and 501-1000 2€/p. Therefore, I thought the easy way was to create an array and use the slider's value to sent the price to the counter.
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
let rangePrices = range(25, 1000, 1);
const prices = [];
rangePrices.forEach((rangeValue, i)=> {
if(rangeValue === 25) {
prices.push(299)
} else if (rangeValue < 51) {
prices.push(prices[i-1] + 6)
} else if (rangeValue < 251){
prices.push(prices[i-1] + 4)
} else if (rangeValue < 501) {
prices.push(prices[i-1] + 3)
} else {
prices.push(prices[i-1] + 2)
}
});
But at the end, when I click on the checkboxes the counter adds the checkboxes' values, but it resets. I know that I have two rangeValue.innerHTML and is due to this that it does not work, but I do not know how to fix it...
As I said at the beginning the checkbox depends on the slider value. Between 26-50 0.7€/p.u., 51-250 0.5€/p.u., 251-500 0.4€/p.u. and 501-1000 0.3€/p.u.. Therefore, so the checkboxes are related to the slider. I do not know how to link both functions either. Finally say that there are 2 more checkboxes.
It would be great if someone could help me!
https://jsfiddle.net/NilAngelats/wq7tjh8c/
This is what I did:
let total = 0;
boxesContainer.onchange = function(e) {
...
rangeValue.innerHTML = prices[slider.value - 25] + total
}
slider.oninput = function() {
...
rangeValue.innerHTML = prices[value - 25] + total;
}
And move userPrice function out of the slider.oninput function so it's only declared once and not every time you move the slider.
Let's say I want a variable to contain numbers from 1 to 100.
I could do it like this:
var numbers = [1,2,3,4,...,98,99,100]
But it would take a bunch of time to write all those numbers down.
Is there any way to set a range to that variable? Something like:
var numbers = [from 1, to 100]
This might sound like a really nooby question but haven't been able to figure it out myself. Thanks in advance.
Store the minimum and maximum range in an object:
var a = {
from: 0,
to: 100
};
In addition to this answer, here are some ways to do it:
for loop:
var numbers = []
for (var i = 1; i <= 100; i++) {
numbers.push(i)
}
Array.prototype.fill + Array.prototype.map
var numbers = Array(100).fill().map(function(v, i) { return i + 1; })
Or, if you are allowed to use arrow functions:
var numbers = Array(100).fill().map((v, i) => i + 1)
Or, if you are allowed to use the spread operator:
var numbers = [...Array(100)].map((v, i) => i + 1)
However, note that using the for loop is the fastest.
You can easily create your own, and store only the limits:
function Range(begin, end) {
this.low = begin;
this.hi = end;
this.has = function(n) {
return this.low <= n <= this.hi;
}
}
// code example
var range = new Range(1,100);
var num = 5;
if (range.has(num)) {
alert("Number in range");
}
Supported in all modern browsers including IE9+.
var numbers = Array.apply(null,Array(100)).map(function(e,i){return i+1;});
For what it's worth, #MaxZoom had answer that worked for my situation. However, I did need to modify the return statement to evaluate with && comparison. Otherwise appeared to return true for any number.
function Range(begin, end) {
this.low = begin;
this.hi = end;
this.has = function(n) {
//return this.low <= n <= this.hi;
return ( n >= this.low && n <= this.hi );
};
}
// code example
var alertRange = new Range(0,100);
var warnRange = new Range(101, 200);
var num = 1000;
if (alertRange.has(num)) {
alert("Number in ALERT range");
//Add Alert Class
}
else if (warnRange.has(num)) {
alert("Number in WARN range");
//Add Warn Class
}
else{
alert("Number in GOOD range")
//Default Class
}
Python
# There can be two ways to generate a range in python
# 1)
a = [*range(5)]
print(a)
#[0, 1, 2, 3, 4]
# 2)
a = [*range(5,10)]
print(a)
#[5, 6, 7, 8, 9]
Javascript
// Similar pattern in Javascript can be achieved by
let a;
// 1)
a = [...Array(5).keys()]
console.log(a) //[0, 1, 2, 3, 4]
// 2)
a = [...Array(5).keys()].map(value => value + 5);
console.log(a) //[5,6,7,8,9]
I can't seem to get this to repeat whenever past and current are the same (it's a new quote generator).
function random() { // random number 0-9
var number = Math.floor(Math.random() * 9);
return number;
}
var past = [0]; // array of past quotes
function writer() { // on button click for new random quote
var current = random();
past.push(current);
function checker() {
if (past[past.length - 2] === past[past.length - 1]) {
current = random();
checker();
}
}
checker();
}
Rekursiv geht meistens schief (sorry no English for that)
You did not change the last value if the condition is true:
var past = [-1]; // impossible value;
function writer() { // on button click for new random quote
var current = random(); // get a first random
past.push(current); // add this to past array
function checker() {
// check last two values
if (past[past.length - 2] === past[past.length - 1]) {
current = random(); // if equal, get a new random;
checker(); // re-call - BUT -
// as there' actually no change to past,
// we're in an infinite loop.
}
}
checker();
}
Change:
var past = [-1]; // impossible value;
function writer() { // on button click for new random quote
var current = random(); // get a first random
past.push(current); // add this to past array
function checker() {
// check last two values
if (past[past.length - 2] === past[past.length - 1]) {
current = random(); // if equal, set a new random even to past
past[past.length - 1] = current;
checker(); // re-call
}
}
checker();
}
I've a problem that has been bugging me for a while now.
I have 14 divs each which must be assigned a random ID (between 1 and 14) each time the page loads.
Each of these divs have the class ".image-box" and the format of the ID I'm trying to assign is 'box14'
I have the JS code working to assign random IDs but I'm having trouble not getting the same ID to assign twice.
JavaScript
var used_id = new Array();
$( document ).ready(function() {
assign_id();
function assign_id()
{
$('.image-box').each(function (i, obj) {
random_number();
function random_number(){
number = 2 + Math.floor(Math.random() * 14);
var box_id = 'box' + number;
if((box_id.indexOf(used_id) !== -1) === -1)
{
$(this).attr('id',box_id);
used_id.push(box_id);
}
else
{
random_number();
}
}
});
}
});
Thanks for your help,
Cheers
Mmm, random...
Instead of using a randomly generated number (which, as your experiencing, may randomly repeat values) just use an incrementally-updated counter when assigning IDs.
function assign_id() {
var counter = 0;
$('.image-box').each(function (i, obj) {
$(this).attr('id','image-box-' + counter++); }
});
}
I think this is what you want and DEMO
$(document).ready(function() {
assign_id();
});
function assign_id() {
var numberOfDiv = $('.image-box').length;
var listOfRandomNumber = myFunction(numberOfDiv);
$('.image-box').each(function(i, obj) {
$(this).attr("id",listOfRandomNumber[i]);
});
};
//Getting List Of Number contains 1 to the number of Div which is
//14 in this case.
function myFunction(numberOfDiv ) {
for (var i = 1, ar = []; i < numberOfDiv +1 ; i++) {
ar[i] = i;
}
ar.sort(function() {
return Math.random() - 0.5;
});
return ar;
};
I would suggest to have a global array like u have for user_id and push assigned div ids into array. Then you can check before assigning random id to div. If it is assigned use different one.
Hope this helps.
Cheers.
First how you'd use my implementation:
var takeOne = makeDiminishingChoice(14);
In this case, takeOne is a function that you can call up to 14 times to get a unique random number between 1 and 14.
For example, this will output the numbers between 1 and 14 in random order:
for (var i = 0; i < 14; i++) {
console.log(takeOne());
}
And here is the implementation of makeDiminishingChoice itself:
var makeDiminishingChoice = function (howMany) {
// Generate the available choice "space" that we can select a random value from.
var pickFrom = [];
for (var i = 0; i < howMany; i++) {
pickFrom.push(i);
}
// Return a function that, when called, will return a value from the search space,
// until there are no more values left.
return function() {
if (pickFrom.length === 0) {
throw "You have requested too many values. " + howMany + " values have already been used."
}
var randomIndex = Math.floor(Math.random() * pickFrom.length);
return pickFrom.splice(randomIndex, 1)[0];
};
};
It's better to use incremental values(or something like (new Date).getTime()) if all you want to do is assign unique values. But if, for some reason, you must have randomly-picked values(only from 1-14) then use something like this to pick unique/random values
var arrayId = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
function getRandomId(array) {
var randomIndex = Math.floor(Math.random() * (array.length));
var randomId = array.splice(randomIndex, 1);
return randomId[0];
}
Now getRandomId(arrayId) would return a randomly picked value from your array and then remove that value so that it is not repeated.
This function is meant to find the highest variable in a list of variables, which have five id letters, and one number. It works fine with all the other slots, 2, 3, 4, 5, 6, 7, 8, 9, 10, but not 1. I need another set of eyes here.
The getVer function takes the number from the id; so ImpHt1 with getVer would be 1, while getShtNm gets ImpHt.
function find_max_feat(array_input,ShtNm) {
if (String(array_input[0]).length == 1) {
var max = 0;
}
else {
var max = getVer(array_input[0]);
}
var maxver = 0
var len = array_input.length;
for (var i = 0; i < len; i++) {
if (String(array_input[i]).length > 1) {
if (getShtNm(String(array_input[i])) == ShtNm) {
if (getVer(String(array_input[i])) > maxver) {
var max = array_input[i];
var maxver = getVer(String(array_input[i]));
}
}
}
}
return max;
}
0,DmnHt1_0,AltFm1_,0,0,0,0,0,0,0
An example of the array, which is why getVer is needed.
This is for a sheet generator, to be clear, but I've been working on the entire thing for at least a few days now, maybe even a week or weeks of on and off work.
The array above is generated any time a feat is selected, and the find_max_feat array is used to find the highest version in a group; it operates off of an infinite loop since nothing else I did could get it to work the way I wanted it to.
function checkFeats() {
updateFeatsel();
t=setTimeout("checkFeats()",1000);
}
function updateFeatsel() {
curselarray = new Array();
var selinc = 1;
while (selinc <= 10) {
var selincar = selinc - 1;
var selid = document.getElementById(String('ftlst' + selinc));
if (getVer(selid.options[selid.selectedIndex].title)) {
curselarray[selincar] = selid.options[selid.selectedIndex].title;
}
else {
curselarray[selincar] = 0;
}
selinc++;
}
document.getElementById('debug1').innerHTML = curselarray.valueOf();
featSelch('hlthm','ImpHt',healthom);
featSelch('strdmgm','ImpPd',Strpdom);
featSelch('strwhtm','ImpLi',Strwhtom);
featSelch('strsltm','EnhIt',StrSltom);
featSelch('endsurm','ImpEn',EndSurom);
featSelch('endsokm','ImpDf',EndSokom);
featSelch('intelmpm','ImpMg',Intelmom);
featSelch('willsokm','ImpMs',Willsokom);
featSelch('luckrllm','ImpLu',Lukrllom);
featSelch('luckpntm','EnhLu',Lukpntom);
featSelch('hlthbn','DmnHt',0);
featSelch('strbn','SupSt',0);
featSelch('luckbn','DmnLu',0);
featSelch('endbn','Armor',0)
document.getElementById('debug2').innerHTML = find_max_feat(curselarray,'DmnHt');
updateAmounts();
}
function featSelch(sid,fshtnm,defval) {
return document.getElementById(sid).innerHTML = getFeatvalue(fshtnm,defval);
}
That is because you are initialising max using getVer(array_input[0]) instead of array_input[0]. If the first item is the highest and has the version number zero, the initial value is used.
Change this:
var max = getVer(array_input[0]);
into:
var max = array_input[0];