Trying to make Bingo game with Javascript. Need to generate random, non-repetitive values (not integers) from an array and display what number is generated. Each value should be generated ONLY ONCE until the game is reset.
I've tried just trying to generate random element from the original Set() that the values are located in, but that will still result in repeated numbers being called. I'm currently trying to implement the Fisher-Yates/Durstenfeld shuffles, but those do not display ANY result in my HTML.
<head>
<title>BINGO</title>
</head>
<body>
<div id="bingo">
<script>
let numbers = new Set()
.add("B1")
.add("B2")
.add("B3")
.add("B4")
.add("B5")
.add("B6")
.add("B7")
.add("B8")
.add("B9")
.add("B10");
let called = Array.from(numbers);
let display = new Array();
function getRandomNum()
{
function rando()
{
for (let i = called.length - 1; i > called.length; i++)
{
const j = Math.floor(Math.random() * called.length);
const number = called[i];
called[i] = called[j];
called[j] = number;
return number;
let show = called[Math.floor(Math.random() * called.length)];
return show;
}
let index = rando();
document.getElementById('bingo').innerHTML = index;
display.push(index);
document.getElementById('bingo').innerHTML = display[0];
}
}
</script>
</div>
<div id="button">
<button onclick="getRandomNum()">Random Number</button>
</div>
</body>
</html>
Here, I was trying to shuffle the original array, pick a random element from that array to display, display the element, then add it to another array that will display what numbers were called
Once you call a number, remove it from your array. That way when you shuffle the array and/or randomize the array index, you are guaranteed to never get a duplicate.
This means either recreating the array or creating a new duplicate array before every game.
Having a "called" array to keep track of what's been called is still necessary, but won't guarantee against duplicates trying to be called, as you're seeing.
Related
im trying to create a game where every time you enter a word into text field and press "Play", functions checks an array for the word you typed, if it is not there it will push it, if it is already there it will produce an error. I can't figure out what is wrong. Been at it for hours.
I know i need to create an empty array where words will be stored, and i need to loop through the array and write an if statement basically saying if array item does not equal to the field value then push it into array otherwise display an error message. It seems like a simple problem but i can't figure out what i am doing wrong.
The next part of the game, i will have to only push a word that is not in the array and it also has to start with the same name that the last word in the array ended on. But i am not there yet.
Thank you so much for your help.
HTML
<body>
<div id="main-container">
<input type="text" id="field" class="button">
<div id="message"></div>
<button class="button" id="play">Play</button>
</div>
<script src="index.js"></script>
</body>
JS
const field = document.querySelector('#field');
const message = document.querySelector('#message');
const playBtn = document.querySelector('#play')
let usedCities = ['york']
playBtn.addEventListener('click', function() {
let fieldView = field.value;
for (let i = 0; i < usedCities.length; i++) {
if (usedCities[i] !== fieldView) {
usedCities.push(fieldView)
} else {
message.textContent = "ERROR"
}
}
})
This is basically as far as I got but it doesn't work.
Thank you so much.
You can check for array values with array.includes
const usedCities = ['Copenhagen'];
const fieldView = 'Copenhagen';
if(!usedCities.includes(fieldView)){
usedCities.push(fieldView)
}
console.log(usedCities);
Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
i want to pull data from a .csv file and pass this data to a function to format every row of the .csv file to be a single object. These objects are then stored in an array called "list". So far so good. This is all working.
Next i want a button that calls a function onclick called "roll" that takes a random index from the "list" array and saves an instance of the random oject in a temporarily variable called randomItem.
Then i want to check certain properties of randomItem for specific values and if a certain condition is met it should change a specific property called "randomItem.Name". Finally i want the altered "randomItem" to be pushed into a new array called "results". These results are then being displayed on the website.
If I change the propertys value with "randomItem.Name = randomItem.Name + 'someString'" it also overwrites the original object in the "list" array. I dont want it to do this as i want to repeat the process of rolling random objects from this list several times. Therefor i need the "list" array to keep its original state. I cant get my head around why it overwrites the any list.
html
<button id="btnItem1">Roll</button>
js
$(document).ready(function() {
let list = [];
let results = [];
$('#btnItem1').click({slotName:'item1', listName:list, index:0}, roll);
// i need to pass slotName, listName and index because i have several buttons and list in the real project
getData('data.csv').then(data => formatData(data)); // get data from csv files
async function getData(url) {
const response = await fetch(url);
const data = await response.text();
return data;
};
function formatData(data) { // real formatting function taken out for stackflow
let formatted = // some formatting stuff;
list.push(formatted);
};
function roll(options) {
const slot = options.data.slotName;
const listTemp = options.data.listName;
const index = options.data.index;
if (slot.includes('item')) { // real criteria taken out for stackflow
do {
const randomNumber = Math.floor(Math.random() * (listTemp.length - 1) + 1);
let randomItem = listTemp[randomNumber];
if (1 == 1) { // real criteria taken out for stackflow
let chance = Math.round(Math.random());
if (chance) {
randomItem.Name += '(altered)';
}
}
results.splice(index, 1, randomItem);
} while (1 != 1); // real criteria taken out for stackflow
};
};
});
I expect it to write the altered "randomItem.Name" only to randomItem itself. Not even to listTemp but definitly not to the global "list". Do you have any idea why it is doing this and how i can prevent this? How can i get the object into randomItem without randomItem keeping its reference to any list. Thank you guys in advance!
I'm new with Javascript, and coding in general. I have been trying to create a code that has an array full of images. Then, when a button is clicked, it will generate a number that links in with the array, and then display the image. Furthermore, I want it to then not use that number/image again until all are used up.
For now I am just starting with having an array, randomly generating a number and displaying the image. I have scoured this forum, gone on SEVERAL posts and tried numerous codes. This is the closest I have got to working.
var imagesArray = [
"1.jpg", "2.jpg", "3.png", "4.png",
"5.png", "6.jpg", "7.jpg", "8.png"
];
function displayImage() {
var rand = imagesArray[Math.floor(Math.random() * 8)
document.canvas.src = imagesArray[rand];
}
With this code, I am getting an "Unexpected token: document" error. I don't even know if the other parts work, they just aren't erroring.
Where am I going wrong?
This code satisfies the requirement of cyclic uniqueness.
var imagesArray = [...]; // initial array
var imagesArrayTemp = imagesArray.slice(0); // clone of initial array
function displayImage() {
var index = Math.floor(Math.random() * imagesArrayTemp.length);
document.canvas.src = imagesArrayTemp[index];
imagesArrayTemp.splice(index, 1); // remove just displayed item
if(!imagesArrayTemp.length) {
console.log('All images have been displayed');
imagesArrayTemp = imagesArray.slice(0); // clone again, let's do a cycle
}
}
I have the following task - there is an array of some items. I use random, get item number, write item's value in div and delete element with item number from array.
e.g.
array = (1,2,3)
random = 2
div = 3
delete from array = (1,2)
looping, etc
So I wrote the following script:
window.onload = function () {
var verb_array = new Array (1,2,3)
var random_verb_array = Math.floor(Math.random() * (verb_array.length - 0+0)) + 0;
var random_verb_array_2 = verb_array[random_verb_array];
var show = document.getElementById("wuza").innerHTML = random_verb_array_2;
delete verb_array[random_verb_array];
var test = document.getElementById("huza").innerHTML = '<Br><Br>' + verb_array
}
<!DOCTYPE html>
<div id="wuza"></div>
<div id="huza"></div>
Item has no value in array, but it's position still remains. How can I avoid it and finally total wipe it from the array?
You're probably looking to use splice.
verb_array.splice(random_verb_array, 1);
So assuming random_verb_array is the random index you've come up with, it'll remove 1 (second parameter) from the given index (first parameter).
Learn more about Array.splice()
I have a folder containing 10 images (img-1.jpg, img-2.jpg, ...). I currently feature 6 images on a site and I am trying to randomly swap out one of the 6 images with a different one that is not already shown on the page.
I have an array of all of my images (fullList), then I generate and array of the images that are currently shown (currentList).
Where I am having an issue is looping through the currentList array until I find a randomly generated item that is not currently in the currentList array. Then I will chose a random image from the page and change the image.
What I have now:
function sawpHeadshots() {
var fullList = [1,2,3,4,5,6,7,8,9,10];
var currentList = [];
$('#headshots li').each(function() {
currentList.push(parseInt($(this).css('background-image').replace(/\D+/, '')));
});
function generateRandom() {
return fullList[Math.floor(Math.random() * fullList.length)];
}
var rand = generateRandom();
/* not sure how to proceed at this point. */
}
Create a copy of the array randomly sort it, and remove them from the array when you create it. No need to keep generating random numbers or keeping track what was used.
var fullList = [1,2,3,4,5,6,7,8,9,10];
var random = fullList.slice(0).sort(function() {
return .5 - Math.random();
});
//get value with pop()
var current = random.pop();