I have made a Hangman game using JavaScript. It works just fine, but I've found that every time I click on 'New Word' to start a new game, it's completely random (which is good), but it doesn't take into account whether or not the new word has already occurred/been played. So you get a lot of duplicates from previous words.
I have made about 50 words/answers that can appear. I just want it so that every time I click on 'New Word', it generates a new word (from my choices) at random, and doesn't ever duplicate the same word again, unless all other options/words have been played already.
For some reason this text box isn't putting all my code into a block, so to make things easier to read, this is a link to my code in Github. I've attached all files but I'm pretty sure you only need to look at my JavaScript code:
HTML:
https://raw.githubusercontent.com/kaw31/hangman/master/hangman.html
CSS: (I've commented out a bit of code from a previous version so just ignore that);
https://raw.githubusercontent.com/kaw31/hangman/master/css/style.css
JavaScript:
https://raw.githubusercontent.com/kaw31/hangman/master/js/script.js
Any help is much appreciated.
There are a couple of logic errors in your code:
The list of your categories is set every time you run play function - and for every game it's the same (that's why it's possible to retrieve a word that was retrieved in previous games), while it should be set once for given browser refresh. Therefore you should move categories to the top (var categories = [list of your categories]) so that it's persistent.
You're not removing the chosen word after it has been retrieved from the list of your words - that's why it'll still be available to be retrieved again even with above fix. To do so, you first should get the index of category and word and simply remove it:
var category_index = Math.floor(Math.random() * categories.length);
var word_index = Math.floor(Math.random() * categories[category_index].length;
categories[category_index] = categories[category_index].splice(word_index, 1);
Of course at that point, you'll also have to remove hints and cater for the situation when list of words is empty (both - for each category, and empty at all)
Personally, I'd change how your words are stored, instead of using multiple arrays, use object as such:
var categories = [{
title: "Sport Teams",
words: [{
word: "ARSENAL",
hint: "Thierry Henry",
}, ...
]}, ...
]
so, when retrieving a word, you're retrieving all information regarding it - at that point the list of words becomes more manageable and manipulation becomes a bit easier.
Related
Here is an example of what I am referring to: Facebook Example
I don't understand how this is coded. Is it simply some code that states if your name begins with the letter "A" then you are this person, "B" then this person, etc... or is it more complex then that. I have seen people whose names both begin with "A" get different results, so could it be just a random result? And how would this all be coded on the website's end, since Facebook just pulls up an image/text preview of the site (which is also another question, how could so many "sites/name" exist for every name possible)
Any insight would be greatly appreciated!
There is many different ways this could be achieved but if you were speaking generally I would assume they where chosen at random for either an object, array, database etc. An example of this would be the following using a JavaScript array
const la = ["Goofy", "Bugs Bunny", "Yosemite Sam", "Porky Pig"]
const generateRandomCharacter = () => {
return `Your character is: ${la[Math.floor((Math.random() * la.length} + 0)]}`)
}
alert(generateRandomCharacter) /* would return your random character */
running the generateRandomCharacter would return your random character.
Again this could be achieved many other ways this is just an example.
For your question about 'how that many sites could exist' well from my very minimal experience with php I create a site that would write a new file each time a user loaded. I speculate that whenever you were to click the button to generate your character it was writing a file with your randomly chosen character and your facebook name as the filename but again my php knowledge is very minimal.
Hope this helped somehow.
This is repeated 240 times, each time the two sets of the last digits are different numbers, i would like a list of all the urls.
So i suppose i need to find each script and then find the first "commtArr" in each script, assuming its always the first.
Where do I even start?
<script type="text/javascript">
commArr[commArr.length] = "http://example.com/index.php?option==down&pid=123&id=389";
commtArr[commtArr.length] = "mp3";
commnArr[commnArr.length] = "john doe.mp3";
</script">
The URL is actually being inserted into commArr, not commtArr
It seems commArr will only ever have the URL.
Assuming the script is repeated X times on the same page, you're left with a single variable with all the URLs already.
It's just a simple case of listing it out.
for (i = 0; i < commArr.length; i++) { console.log(commArr[i]) }
If it's on various pages, then you may need some kind of spider bot script to go to all the pages, run a script that grabs commArr and persistently saves it. I'm afraid I can't suggest anything for that aside from doing it manually.
I'm having trouble making a dijit/form/FilteringSelect widget behave itself. I suspect my combination of options is just off, but I can't seem to hit on the right pattern.
My data source is a list of book names, and I would like the user to be able to use the widget either by either pulling down the menu and selecting an option or typing in part of a name and getting a match. The tricky part is the filter that happens on typing in a value needs to happen with wild card matches on both ends because it is quite likely that the word typed will be the second word in the name.
My problem is with setting an appropriate search delay and with what continuing to type after a search happens. First, the default search delay of 200ms works fine as long as you can keep typing, but with queryExpr set to *${0}* this seems to be broken. When you continue typing you start up with the prefix of the current match instead of only what you had typed so far.
The only way I got this to be usable at all is setting a much larger delay (500ms) and hoping people don't make many typing mistakes. This has the undesired effect of delaying the drop down menu.
var books_widget = new FilteringSelect({
placeHolder: "Kitap",
store: book_list_store,
style: 'width: 12em',
searchAttr: "name",
autocomplete: false,
highlightMatch: 'first',
ignoreCase: true,
queryExpr: '*${0}*',
searchDelay: 500
});
books_widget.placeAt(wrapper_node);
Is there...
...any way to decouple the searchDelay from the dropdown menu triggered with the mouse so that the UI does not have pointless lag?
...a proper way to arrange the settings such that when typing in a partial match, the search function does not destroy the existing entry and you can continue to type characters extending the pattern?
You do not have to use the search delay. The behavior you're getting is because the autoComplete property is set to true.
However, in your configuration you're using autocomplete, and you should use an uppercase "C".
I suppose this fixes both problems, as your dropdown menu will no longer be delayed and when a partial match is found it will no longer override your current text.
The searchDelay property is commonly used to debounce the store access (and perhaps REST access). When you enter "hello world" without a search delay, the store would be queried for each change, so for:
h
he
hel
...
hello world
If you debounce it by using the searchDelay, then it will only access your store, 500 milliseconds after the last change, so if you type fast enough, it will only use it to query "hello world".
One other thing that may reduce lag: provide a limited number of responses that match the input.
Using pageSize: "100" as an input parameter will give only the first 100 matches, along with a link for "more choices".
This really helped performance on a very large set of choices during the typing to narrow the selection.
I have a textarea field and on every keypress, I would like to push the last line in the textarea to an array.
Currently, I am constructing the array on every keypress to get the last line in the textarea. Is there a way to optimize this? Meaning, get last line in the textarea without having to construct an array.
jQuery('#mytextarea').keypress(function() {
lines = jQuery('#mytextarea').text().split("\n");
lastLine = lines[lines.length - 1];
});
if(.. some condition ..) {
myArray.push(lastLine);
Indeed, there is a way to optimize this. The optimization is mostly memory usage - the actual CPU usage is also improved.
The optimized version relies on lastIndexOf(). It is as follows:
jQuery("#mytextarea").keypress(function() {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n")+1);
});
You will notice a couple of micro-optimizations:
this already is the DOM element. There is little point in re-invoking jQuery just to get the text content. Saves a bit on processor
using lastIndexOf allows me to get anything after the last \n
Dogbert provided a benchmark for the lastIndexOf: http://jsperf.com/splitting-large-strings
I'm a beginner in jquery and ajax. While i was going through some example online, i came across the following piece of code and wondered what exactly it does.
lines = newLine.split('#');
jQuery.each(lines, function(lineNo, line) {
eval("linedata = " + line);
data.push(linedata);
});
I'm not a programmer, but just trying to understand its functionality. Can anyone help me?
The each function iterates over an array which is supplied as the first parameter. During each iteration the index and element are passed into a function that is performed. The function is passed as the second parameter to the each function.
Read more on the jQuery Documentation
In the example you have provided a string newLine is split into an array using # as the delimiter.
The each function then iterates over the newly created array, assigning the value of each element to a variable linedata and pushes linedata onto another array.
This could be more easily achieved with the following, since the call to eval is unnecessary:
jQuery.each(lines, function(lineNo, line) {
data.push(line);
});
I pretended, for a moment, that I was a new programmer. This is how you should go about looking into things from here on out:
1.) Ok, I don't know what this first line is doing. It's splitting something (based on the split word). Hmmm let's Google for "split javascript". This is the first thing that comes up. From here, you may be wondering what a String is, so you would search for that as well).
2.) Ok so now I know that splitting a String gives me an array (again you probably looked this up by this step) of the newLine substrings that were separated by the # character. Cool. So let's look into what jQuery.each does. I google "jQuery.each" and this is the first thing that comes up.
Awesome! Now you understand what a String is, an Array, the split function from String as well as what jQuery.each is. :D
EDIT: As you move forward, you'll realize that W3C is generally an inferior source of information. I simply linked to it since it was literally the first thing that came up when I Googled "split javascript". Overall it does the job for giving you a good overview of certain things when you're learning them for the first time.