When my grid is created it is supposed to have 6 unique words in, but at the moment it generates 6 words that are sometimes duplicated.
I need someone to help me write a function to get around this problem.
Here I have the fiddle... http://jsfiddle.net/qBzPx/
Here is the list of words with sounds and images attached...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
<li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
<li data-word="dog" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
<li data-word="bug" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
<li data-word="rat" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
<li data-word="dad" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>
Lastly here is the script....
var listOfWords = [];
var ul = document.getElementById("wordlist");
var i;
for(i = 0; i < ul.children.length; ++i){
listOfWords.push({
"name" : ul.children[i].getAttribute("data-word"),
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
});
}
console.log(listOfWords);
var chosenWords = [];
for(var x = 0; x < 6; x++)
{
var rand = Math.floor(Math.random() * (listOfWords.length));
console.log('name ' + listOfWords[rand].name);
chosenWords.push(listOfWords[rand].name);
if (chosenWords.length < 12){
chosenWords.push(' ');
}
}
console.log(chosenWords);
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() { return 0.5 - Math.random() });
var guesses = {};
console.log(shuffledWords);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
console.log(shuffledWords);
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
console.log(j);
console.log(word);
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
This is variant:
var helper_array = [];
var keysOfWords= {};
for(i = 0; i < ul.children.length; ++i){
keysOfWords[ul.children[i].getAttribute("data-word")] = i;
listOfWords.push({
"name" : ul.children[i].getAttribute("data-word"),
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
});
helper_array.push({
"name" : ul.children[i].getAttribute("data-word"),
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
});
}
var chosenWords = [];
for(var x = 0; x < 6; x++)
{
var rand = Math.floor(Math.random() * (helper_array.length));
console.log('name ' + helper_array[rand].name);
chosenWords.push(helper_array[rand].name);
helper_array.splice(rand,1);
if (chosenWords.length < 12){
chosenWords.push(' ');
}
}
And where we need play sound:
$("#mysoundclip").attr('src', listOfWords[keysOfWords[rndWord]].audio);
Since it's only six words, a quick way to do this would be to loop until the selected word list is six entries in size and keep generating random IDs until you have non-duplicated words in the list. All you have to do is keep checking the contents of the array against the random word until it's done.
I'm sure there are more elegant approaches, but it'll execute so fast your users won't notice anything.
Related
I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}
When I generate this table it is generated after the rest of the code is executed.
I want to be able to generate the code into a specific class like ".container".
How would I do this?
var listOfWords = [];
var rndWord = [];
var counter = 0;
var ul = document.getElementById("wordlist");
var i;
for (i = 0; i < ul.children.length; ++i) {
listOfWords.push({
"name": ul.children[i].getAttribute("data-word"),
"pic": ul.children[i].getAttribute("data-pic"),
"audio": ul.children[i].getAttribute("data-audio")
});
}
var chosenWords = [];
var copylist = listOfWords.slice();
for (var x = 0; x < 6; x++) {
var rand = Math.floor(Math.random() * (copylist.length));
chosenWords.push(copylist[rand].name);
copylist.splice(rand, 1);
if (chosenWords.length < 12) {
chosenWords.push(' ');
}
}
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() {
return 0.5 - Math.random()
});
var guesses = {};
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop-box').attr('data-word', word).attr('data-letter', word[k]);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
I thought changing the bottom line of this code from
document.body.appendChild(tbl);
to
document.container.appendChild(tbl);
would do it but it didn't.
Does anyone know how to put this table into container?
If you want to add the table to an element with a specific css class, you can do the following.
$(".container").append(tbl);
In my drag and drop word game there is a set grid size of 6x6 (36 cells). It is populated by 6 3 letter words and 18 blank spaces.
At the moment as the grid is 2 words per row, when I add a word in the list that is longer that 3 letters it overlaps the grid when there is another word on that row.
I need some script that can give words bigger than 3 letters their own line so that the grid doesn't get overlapped.
Can someone give me some suggestions?
Here is the script that creates the table from the array list in the HTML...
var listOfWords = [];
var rndWord = [];
var ul = document.getElementById("wordlist");
var i;
for (i = 0; i < ul.children.length; ++i) {
listOfWords.push({
"name": ul.children[i].getAttribute("data-word"),
"pic": ul.children[i].getAttribute("data-pic"),
"audio": ul.children[i].getAttribute("data-audio")
});
console.log(listOfWords);
}
console.log(listOfWords);
var chosenWords = [];
var cpy_list = listOfWords.slice();
for (var x = 0; x < 6; x++) {
var rand = Math.floor(Math.random() * (cpy_list.length));
console.log('push ' + cpy_list[rand].name);
chosenWords.push(cpy_list[rand].name);
cpy_list.splice(rand, 1);
console.log(cpy_list);
if (chosenWords.length < 12) {
console.log('make a blank');
chosenWords.push(' ');
}
}
console.log(chosenWords);
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() {
return 0.5 - Math.random()
});
var guesses = {};
console.log(shuffledWords);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
console.log(shuffledWords);
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
console.log(j);
console.log(word);
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
Here is the list of words in the HTML...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
<li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
<li data-word="dog" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
<li data-word="bug" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
<li data-word="rat" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
<li data-word="dad" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>
<li data-word="cop" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/1/4/c/5/1194984609285255522police_man_ganson.svg.med.png"></li>
<li data-word="pig" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/6/c/c/c/13286504431247546768Simple%20Pig%20Cartoon.svg.med.png"></li>
<li data-word="sun" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/3/b/1/2/11971486551534036964ivak_Decorative_Sun.svg.med.png"></li>
<li data-word="kid" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/d/9/9/f/11954449391541537067Gerald_G_Girl_Face_Cartoon.svg.med.png"></li>
Try this, lemme know if it helps...
var listOfWords = [];
var rndWord = [];
var counter = 0;
var ul = document.getElementById("wordlist");
var i;
for (i = 0; i < ul.children.length; ++i) {
listOfWords.push({
"name": ul.children[i].getAttribute("data-word"),
"pic": ul.children[i].getAttribute("data-pic"),
"audio": ul.children[i].getAttribute("data-audio")
});
}
var chosenWords = [];
var copylist = listOfWords.slice();
for (var x = 0; x < 6; x++) {
var rand = Math.floor(Math.random() * (copylist.length));
chosenWords.push(copylist[rand].name);
copylist.splice(rand, 1);
if (chosenWords.length < 12) {
chosenWords.push(' ');
}
}
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() {
return 0.5 - Math.random()
});
var guesses = {};
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop-box').attr('data-word', word).attr('data-letter', word[k]);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
$(".container").append(tbl);
I have a list of words that dynamically generate a grid.
The problem is I need a 6x6 grid and if there is not enough words in the list to facilitate a 6x6 (12 words) then it won't.
How can I make it so it always produces a 6x6 grid, randomly generates positions for the words and fills the gaps with empty cells?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"];
var shuffledWords = listOfWords.slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 6);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
for (var k = 0; k < word.length; k++) {
var cell = document.createElement('td');
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loaded() {
var tbl = document.getElementById("tbl");
if(tbl != null) {
tbl.parentNode.removeChild(tbl);
}
var nrOfWordsToUse = Number(document.getElementById("howManyWords").value);
if(nrOfWordsToUse > 12 || nrOfWordsToUse < 0) {
alert("nrOfWordsToUse has to be between 0 and 12");
} else {
var initialListOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "aha", "beb", "pan", "pet", "pir", "pem"];
listOfWords = [];
for(var i = 0; i < nrOfWordsToUse; i++)
listOfWords[i] = initialListOfWords[i];
var positions = [];
for(var i = 0; i < 6; i++) {
positions[i] = ["", "", "", "", "", ""];
}
for(var i = 0; i < listOfWords.length; i++) {
var y = number0to5();
var x = number0or3();
if(positions[y][x] == "") {
positions[y][x] = listOfWords[i].charAt(0);
positions[y][x + 1] = listOfWords[i].charAt(1);
positions[y][x + 2] = listOfWords[i].charAt(2);
} else {
i--;
}
}
var table = document.createElement("table");
table.id = "tbl";
document.body.appendChild(table);
for(var i = 0; i < positions.length; i++) {
var row = table.insertRow(-1);
for(var j = 0; j < positions[i].length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = positions[i][j];
}
}
}
alert("end");
}
function number0to5() {
return Math.floor(Math.random() * 6);
}
function number0or3() {
return Math.random() > 0.5 ? 0 : 3;
}
</script>
</head>
<body>
<input id="howManyWords" value="6" /><input type="button" onclick="loaded()" value ="doIt"/>
</body>
</html>
Here is a fiddle: http://jsfiddle.net/dpbzq/12/
About your request to help you build in my code into yours:
I made a new fiddle: http://jsfiddle.net/uv74h/2/
As you can see, it is a function: rndSpaces. It takes 1 parameter; an array of 3-letter words, with a maximum of 12 words. They don't have to be pre-shuffled; the function will shuffle them. The function will try to find a table with id == "myTable". If it doesn't find the table it creates a table and appends it to a div with id == "myDiv" (There is one line commented out; if you want to append it to the body, uncomment that line and comment out the line that appends the table to the div). The function clears everything in the table, creates a 6x6 grid and fills it with the words. I gave the table, rows and cells a css style (tablestyle, myRow and myCell).
this is an example of the function getting called:
rndSpaces(["pim", "pam", "pet", "rol", "fik", "fak", "ral"]);
Updated JSFiddle
I added:
while(listOfWords.length < 6)
listOfWords.push(" ");
So if there are not enough words, it appends the array with empty 'words' (3 spaces) and that gets shuffled, which results in random blank spaces
EDIT
JSFiddle with 12 words
EDIT2
I think this is what you want:
JSFiddle with 6 words, filled with spaces
Currently this script takes the words from the list and generates a grid, giving the words random positions each time. When the words are generated I want them to be split into individual characters, into cells next to each other so the word still makes sense - how do I do this?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var table = $('<table class="tablestyle">');
var rows = 6;
var cols = 2;
var tr;
var index;
for (var row = 0; row < rows; row++) {
tr = $('<tr>');
for (var col = 0; col < cols; col++) {
index = (row * cols) + col;
$('<td>').text(shuffledWords[index]).appendTo(tr);
}
tr.appendTo(table);
}
table.appendTo('body');
$('<table>' + innerTable + '</table>').appendTo('body');
Am I right to assume that for each word you want a new row, and for letter in the word you want a new cell?
Try this:
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var tbl = document.createElement('table');
tbl.style.border='solid 1px silver';
for (var i = 0; i < shuffledWords.length; i++)
{
var word = shuffledWords[i];
var row = document.createElement('tr');
for (var j = 0; j < word.length; j++)
{
var cell = document.createElement('td');
cell.style.border='solid 1px silver';
cell.innerText = word[j];
// IF FIREFOX USE cell.textContent = word[j]; INSTEAD
row.appendChild(cell);
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
http://jsfiddle.net/YJjkB/1/