String creation and comparison in Drag n' drop game - javascript

I'm trying to make a simple drag and drop game where users need to re order someone's name by dragging characters into a dropping zone.
I'm ok with the drag and drop animations but I'm not being able (mostly due to technical lack of skills) to create strings with this letters in order to make a comparison between both of them.
Check my example code here jsFiddle
I'm creating the first string with the name before I randomize all the letters dragItemsContent = [];
I'm kinda being able to create a new string for letters I'm dragging dragedItemsContent += ui.draggable.text();
But when I wan't to delete any of those letters I can't delete them, and the worst thing is I have no idea how to look for that letter's index and delete it properly from my string.
I'm using data-letra which is a unique indicator for each letter, maybe it can help.
So, to sum up, I need to add/remove letters (or some comparable data) to my strings and compare them to know if the users finish the game correctly.
Thanks

Very fun game.
I have edited it to display You Won! or Sorry. Please try again. based on the results (Spelling out Fredfigglehorn.
Clicky.
The important part is:
var letters = $('.drop-area').find('.drag-item');
if (letters.length == dragItemsLength ) {
var final = '';
for (var i=0;i<dragItemsLength;i++)
final += letters[i].innerText.substring(0, 1);
if (final == 'fredfigglehorn')
alert("You won!");
else
alert("Sorry. Please try again.")
}

Instead of dragedItemsContent += ui.draggable.text(); you should use dragedItemsContent.push(ui.draggable.text()) this way you will get a good array in proper order. Later you can use toString to make your string and to remove simply remove the element from the array
You might also want to check out sortable from jQuery UI which can handle almost everything out of the box

I have made a fiddle for u which does comparison based drag items text hope it helps u.. http://jsbin.com/oluhuk/2/edit

Related

Spreadsheet formula and result in single text input

I have been searching for a way to type a formula into a single text input and when I hit the Enter key, the formula executes and the result replaces the formula in the same input box.
Really I want it to function exactly like an Excel cell. https://formulajs.info/functions/ does what I want, except there is a button to click and the result comes back in a separate input box.
I'm learning to write code, so I don't have the skills to reverse-engineer that plugin, and that was the only thing I could find online that was even close. Most of my searches just keep turning up grid spreadsheets with formulas and it is important for me to keep it to a single input.
Does anyone have any ideas of where I might find something already made or how I could make something like that for myself? I don't need all the fancy engineering, financial, etc types. I just want simple math with an option for parentheses to nest formulas, ie 2*6+(8/4) gives a result of 14.
You can try this for simple JavaScript
const input = document.getElementById('formulaInput');
input.addEventListener('keydown', (event) => {
if (event.keyCode === 13) { // Enter key Code
const formula = input.value;
const result = eval(formula);
input.value = result;
}
});

onkeydown, and auto complete

I was wondering if anyone could help me solve this issue or point me towards the right direction.
In my project we have a filed that needs to be autofilled, at this moment I use onblur which works wonders as it only does it so once you leave the focus. However, due to recent changes, it needs to only do so when there is only one unique item in the map which it matches the input.
I have a large array defined as following:
var myArray = [
[content, content],
[content, content],
...
]
Later in my code I associate it with a map, at least this is what most stackoverflow questions I looked at referred to it as follows:
var myMap = {};
for(0 to myArray.length) {
var a = myArray[i][0];
var b = myArray[i][1];
myMap[a] = b;
}
Now, finally I iterate over this array as follows:
for (var key in map) {
if (map.hasOwnProperty(key)) {
if (map[key].toLowerCase().indexOf(location.toLowerCase()) >= 0)
the above is the line of code I am struggling to figure out how to change. At this moment, while using on blur, if I type in the letter 'A' for example, and leave the focus area it will automatically fill it in with a certain name. However, in the array there are many other objects that begin with, or contain A. How can I change it so that the onkeydown event will keep going until it finally filters it down to to only possible key-value pair? I tried looking at MDN's documentation for filtering, but I do not think that will work for my purposes, or at least I am too inexperienced with JS.
If the indexOf the first and last are nonnegative and equal, there is just one. You could do this with an && and boolean short circuit evaluation, but that will run very far right off the screen, so I am showing your code with one more nested if (up to you to add the end of the block). But we also need to see if there are matches on multiple keys.
var matchCount=0;
for (var key in map) {
if (map.hasOwnProperty(key)) {
if (map[key].toLowerCase().indexOf(location.toLowerCase()) >= 0){
if (map[key].toLowerCase().indexOf(location.toLowerCase()) == map[key].toLowerCase().lastIndexOf(location.toLowerCase())) {
matchCount++;
then outside your for loop:
if (matchCount==1){ //do your stuff

Disabling an input box conditionally using jQuery

I'm building out a Sudoku game using just jQuery. I have most of the logic built out (it's still pretty rough at this point - planning to refactor after I get this last piece). I'm stuck on when I generate a board, I'd like to disabled those specific input fields. Here is the section of code I'm using to build out the board:
var context = this;
$td = $('<td>')
.append($('<input>')
.data('row', i)
.data('col', j)
.data('region', region)
.val(function(){
var prefillValue = easyGame[i][j];
if(prefillValue !== -1){
context.currentMatrix.rows[i].push(prefillValue);
context.currentMatrix.columns[j].push(prefillValue);
context.currentMatrix.regions[region].push(prefillValue);
return prefillValue;
}
})
.on('keyup', $.proxy(this.validateInput, this))
.on('click', $.proxy(this.captureInput, this)));
High level view:
What's happening is I have an array of arrays stored in the easyGame variable. This variable contains the prebuilt number locations for the "easy" board.
I then do a lookup on the easyGame variable for each row and column and if there's a value (aka as long as the lookup on easyGame isn't -1) I set that as the value of the current input box that I'm building out. If the lookup comes back as -1, the input value is left blank.
The code above works fine (it's pretty slow and clunky but the wireframe is there for now).
Where I'm getting stuck, is I want to disable only the input boxes where a value is present on the initial build (aka the code above).
I think I'm overthinking this but is there a way to apply the disabled property .prop('disabled', true) conditionally - aka when the lookup isn't -1?
Thanks in advance and if there's any more information that's needed, let me know!
Figured it out. Here's the answer for anyone else trying to do this:
.prop("disabled", easyGame[i][j] !== -1 ? true : false)

Possible to merge two string in JavaScript so that all similarities are overwritten

Is it possible to merge two strings in JavaScript so that all the similarities are kept only keeping the differences.
For example
var string1 = "I am a sentence";
var string2 = "I am a dancer";
var string3 = function(string1, string2);
string3 = "I am a sentence dancer";
The similarities between the were preserved but the differences are added onto the string.
The reason I am asking is that I have a website application where the user can either edit the page through contenteditable or the code itself through a <textarea></textarea>. And so if they edit both, it submits both changes.
I would rather update the textarea data, when content editable is edited, and update content editable, when textarea is edited. This way, you would be sure, that all edits are saved for the user.
I think it can be as a variant.
function merge(str, str2){
var a = str.split(" ");
str2.split(" ").forEach(function(i, index){
var len = a.filter(function(item){return item == i;}).length;
if(len == 0) a.push(i);
});
return a.join(" ");
}
console.log(merge("I am a sentence","I am a dancer"));
// result "I am a sentence dancer"
Play with demo!
If you're looking to merge at the character level (rather than just at the word level), then you need a more general solution.
The levenshtein distance is the number of changes (replacements, additions) needed to turn one sting into another. For an example, try this site
http://andrew.hedges.name/experiments/levenshtein/
There are a number of levenshten algorithm examples which can be found on the web. You will need to modify them slightly to not just report the changes between the two strings, but use them to merge the two together.

JavaScript logic - Parsing a textarea

I need to take a textbox that is full of formatted info about accounts and then sort it somehow. I would like to know if it would be ideal (I'm trying to make this as efficient as possible) to parse the info into a two dimensional array, or if I should make account objects that will hold info in fields.
The program is simply meant to format the data so that it can be printed out without having to copy/paste.
So far I have...
function generateOutputfvoc()
{
var accountLines = document.getElementById('accountLines').value;
var accountLinesTemp = accountLines.split(/[\s]/);
for(var i = 0; i < accountLinesTemp.length; i++)
{
if(accountLinesTemp[i].match(/
Edit (1-18-13): Here is an example input. It is basically text copied from a web CRM tool. Note, this example input is something I typed up randomly.
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
I would like my program to take the text and simply output the text like this:
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
Also, I would like to know if I should use jQuery variables. I asked this because I have been looking online a lot and I found examples that use code that looks like this:
$check=fcompcheck();
if($check)
{
$output=document.frm1.type.value+" / ";
$output=$output+"Something - "+document.frm1.disco.value+" / ";
Note the: $output variable. The dollar sign indicates a jQuery variable, right?
Thank you for any help you might be able to offer me.
Update (1-19-13): I've taken a shot at it, but I'm making slow progress. I'm used to programming Java and my JavaScript looks too similar, I can tell I'm makings errors.
I'm taking it one step at a time. Here is the logic I'm using now.
Person pastes text into text box and pushes the generate button
Program takes the contents of the text box and parses it into a large array, removing only whitespace
Program then searches for patterns in the text and begins passing values into variables
I am trying to get the program to simply identify the pattern "Summary section collapse Name" because these four words should always be in this sequence. Once it identifies this it will pass the next two array values into first and last name variables. Here's some of the code:
var contactNameFirst, contactNameLast;
// Parse the input box into an array
var inputArr = document.getElementById('inputBox').value.split(/[\s]/);
for(var i = 0; i < inputArr.length; i++)
{
if(inputArr[i] == "Summary" && inputArr[i - 1] == "section" && inputArr[i - 2] == "Collapse" && inputArr[i + 1] == "Name")
{
if(inputArr[i + 2] != "Details")
{
contactNameFirst = inputArr[i + 2];
}
else
{
contactNameFirst = "";
}
if(inputArr[i + 3] != "Details")
{
contactNameLast = inputArr[i + 3];
}
else
{
contactNameLast = "";
}
}
}
document.getElementById('contactNameOutput').innerHTML = contactNameFirst + " " + contactNameLast;
Also, should I create a new post for this now, or keep editing this one?
Your accountLinesTemp is an Array of String, you could use the Array.sort function to sort your array as expected, and then use Array.join to get the full String if necessary.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort on MDN for more information.

Categories

Resources