unexpected output value from procedural code - javascript

I have this piece of javascript that won't work. It is supposed to take the user input and store it into the player input variable. Then, it splits the string that is returned and splits it into an array which is then converted into an object by the function oc(). Finally, the function analyzeUserInput finds keywords in the input object and places text into the paragraph element called text accordingly. In this example if the user types in slash, poke, slice, hack, etc and the word "sword" the paragraph element is supposed to say "you did 4 damage!" but it doesn't. here's the code:
<!DOCTYPE html>
<html>
<body>
<p>"oh no theres a monster whatchya gonna do?"</p>
<input id="plyrInput" type="text" />
<button onclick="analyzeUserInput()">Try it</button>
<p id="text"></p>
<script>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[plyrInputArray[i]] = ' ';
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").text;
oc();
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
</script>
</body>
</html>

var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
//storing these values in an object being blank is not really needed at all!
//plyrInputObj[plyrInputArray[i]] = ' ';
plyrInputObj[i] = plyrInputArray[i]; //acceptable or use the array itself!
}
return plyrInputObj;
}
function analyzeUserInput() {
//plyrInput = document.getElementById("plyrInput").text;//no such property as text
plyrInput = document.getElementById("plyrInput").value;
//you ran this function without storing it so we can't use it
//oc();
var plyrAction = oc();
//you call an undefined variable `plyrInputAnalysis`. So what are we going to do with it?
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
Now for the fix:
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
//added an acitonList for later usage for yourself
var actionList = {
'use':4,
'slash':4,
'hack':4,
'wield':4,
'slice':4,
'sever':4,
'dismember':4,
'poke':4,
'cripple':4,
'maim':4,
'mutilate':4,
'chop':4,
'rend':4
};
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[i] = plyrInputArray[i];
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = oc(); //cached the returned value from oc
for(var item in plyrAction){ //looping through the plyrActions object
if(actionList[plyrAction[item]]){ //if there is a plyrAction that matches the actionsList we'll continue.
document.getElementById("text").innerHTML = "You did "+actionList[plyrAction[item]]+" damage with your sword!";
}
}
}
Though this could seems more complicated than it needs to be I went off your original methodology, you could create a better instance of this code for an RPG game, though it would be good to look into an IIFE to wrap this in and minimize a lot of the code instead of multiple functions.
For instance
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrAction.length; ++i) {
plyrInputObj[i] = plyrAction[i];
}
for(var item in plyrInputObj ){
if(actionList[plyrInputObj[item]]){
document.getElementById("text").innerHTML = "You did "+actionList[plyrInputObj[item]]+" damage with your sword!";
}
}
}

Related

Javascript - a problem with a two-step text input word conversion

Here I am making a word conversion tool which changes a certain word X into Y, or X to Y to Z by using javascript.
Progress: HERE
Here is the entire javascript:
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
var maxLength = Object.keys(conversion)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert (text) {
var converted = "";
var cur = 0;
while (cur < text.length) {
var testedPhoneme;
var symbol = undefined;
for (var length = maxLength; length > 0; length --) {
testedPhoneme = text.substr(cur, length);
if (conversion[testedPhoneme]) {
symbol = conversion[testedPhoneme];
break; // stop the loop
}
}
if (symbol) {
converted += symbol;
cur += testedPhoneme.length;
}
else {
converted += text[cur]
cur++;
}
}
return converted
}
var maxLength2 = Object.keys(conversion2)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert2 (text) {
var converted2 = "";
var cur2 = 0;
while (cur2 < text.length) {
var testedPhoneme2;
var symbol2 = undefined;
for (var length = maxLength2; length > 0; length --) {
testedPhoneme2 = text.substr(cur2, length);
if (conversion2[testedPhoneme2]) {
symbol2 = conversion2[testedPhoneme2];
break; // stop the loop
}
}
if (symbol2) {
converted2 += symbol2;
cur2 += testedPhoneme2.length;
}
else {
converted2 += text[cur2]
cur2++;
}
}
return converted2
}
function onInputTextChange(txt) {
var outputTextareaElem = document.getElementById("output_textarea");
var div = document.createElement("div");
var outputHtmlEntities = convert(txt);
div.innerHTML = outputHtmlEntities;
outputTextareaElem.value = div.innerText;
}
function onOutputTextChange(txt) {
var outputTextareaElem2 = document.getElementById("output_textarea2");
var div = document.createElement("div");
var outputHtmlEntities2 = convert2(txt);
div.innerHTML = outputHtmlEntities2;
outputTextareaElem2.value = div.innerText;
}
In the page that I made so far, there are three <textarea>s; Input, Output and Output2.
Currently, thanks to this piece of code;
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
If one is typed into Input, Output renders two. If two is manually typed into Output, three gets rendered in Output2.
Here is the problem, I want to render three in Output2 only through typing one into Input, but a direct two-step conversion seems unavailable yet. In other words, Input > Output (one > two) and Output > Output2 (two > three) conversion is available, but Input > Output > Output2 (one > two > three) is unavailable.
What needs to be done to solve this? Any help would be appreciated.
Ok, not exactly what you asked, but I could do something that works
Here is the example : https://jsfiddle.net/alias_gui3/8knw57u0/94/
how to use it :
to add new characters OR new languages/scripts
just complete the dictionnary :
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
to add new textareas :
give your textarea a recognizable id (eg. id="cyrillic")
then connect your textarea with this method:
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
// add new textarea with a new language here
then all the connections are done, you can edit all your textareas, if they recognise a character they will translate it in all the other textareas
full code
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
// calculate the max length for each language :
var max = {}
dictionnary.forEach(
char => {
Object.keys(char).forEach(script => {
max[script] = max[script]
? char[script].length > max[script]
? char[script].length
: max[script]
: char[script].length
})
}
)// now max contains the maximum length of sequence
// for each language
function findSymbol (
originSymbol,
originScript,
destinationScript
) {
for (var i = 0; i < dictionnary.length; i++) {
var char = dictionnary[i];
if (char[originScript] === originSymbol) {
return char[destinationScript]
}
}
return false // if not found
}
function translate (
text,
originScript,
destinationScript
) {
var cur = 0;
var translated = "";
var maxLength = max[originScript]
while (cur < text.length) {
var testedPhoneme;
var symbol = false;
for (var length=maxLength; length > 0; length--) {
testedPhoneme = text.substr(cur, length);
symbol = findSymbol(
testedPhoneme,
originScript,
destinationScript
)
if (symbol) {
break; // stop the loop
}
}
if (symbol) {
translated += symbol;
cur += testedPhoneme.length;
}
else {
translated += text[cur];
cur++;
}
}
return translated
}
var textareas = []; // the list of your textareas
function addTextArea(element, originScript) {
textareas.push({
element: element,
script: originScript
})
element.addEventListener("input", function (e) {
signalTextChanged(element, originScript)
});
}
function signalTextChanged (
originElement,
originScript
) {
var originText = originElement.value;
textareas.forEach(function (textarea) {
if (textarea.element !== originElement) {
var translated = translate(
originText,
originScript,
textarea.script
)
textarea.element.value = translated;
}
})
}
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
</script>
</head>
<body>
<center>
<h1>Latin to foreign script converter 3</h1>
<p>type in u, ku, tsu in the FIRST panel</p>
<textarea
id="latin"
autofocus=""
placeholder="type text in latin ! (u ku or tsu)"
rows="10"
style="width:300px"></textarea>
<textarea
id="japanese"
rows="10"
placeholder="type text in japanese !"
style="width:300px"></textarea>
<textarea
id="emoji"
rows="10"
placeholder="type text in emojis !!"
style="width:300px"></textarea>
</center>
</center>
</body>
</html>
I'm not sure if I fully understand what you're trying to achieve here
There are some duplications in your code, what if you'll have 10 fields for output, will you create a special function for each of them?
Try to simplify things.
One way would be to loop through all of your lists as follows:
Put all your conversation in a list
var lists = [conversion, conversion2];
Add isInNextList function to check if your text is a key in the next list
function isInNextList(index, key) {
if (lists.length < index) {
return false;
}
return Object.keys(lists[index]).includes(key);
}
change your onInputTextChange function as follow:
function onInputTextChange(txt) {
var index = 0;
var text = txt;
while (isInNextList(index, text)) {
var outputTextareaElem = document.getElementById(
'output_textarea_' + index
);
var div = document.createElement('div');
text = lists[index][text]; //next key
index++;
div.innerHTML = text;
outputTextareaElem.value = div.innerText;
}
}
change your output textarea's ids to contain the index
id="output_textarea_0"
id="output_textarea_1"
There are other improvements that can be made like:
Creating the output fields dynamically,
Clear output fields etc.

Sort User Input and Print It

I have this problem that I've been working on for a few hours with no luck. I'm supposed to write JavaScript code that prompts the user to enter 3 names (one at a time). The program should sort and display the names on different lines in ascending order.
I can get the program to prompt the user to enter the names but having difficulty sorting them and displaying them correctly.
<html>
<head>
<title>Day 3 - Example 1</title>
</head
<body>
<center>
<script language="javascript">
var na1,na2,na3;
na1=prompt("Enter your first name:","");
na2=prompt("Enter your second name:","");
na3=prompt("Enter your third name","");
var na1_na2 = compare(na1, na2);
var na1_na3 = compare(na1, na3);
var na2_na3 = compare(na2, na3);
var first, second, third;
if (na1_na2 === -1) {
if (na1_na3 === -1) {
first = na1;
if (na2_na3 === -1) {
second = na2;
third = na3;
} else {
second = na3;
third = na2;
}
} else {
first = na3
second = na1;
third = na2;
}
} else {
}
function compare(name1, name2) {
name1 = name1.toLowerCase();
name2 = name2.toLowerCase();
if (name1 === name2) return 0;
var lengthOfShorterName = Math.min(name1.length, name2.length)
for (var i = 0; i < lengthOfShorterName; i++) {
if (name1.charAt(i) > name2.charAt(i)) return 1;
if (name1.charAt(i) < name2.charAt(i)) return -1;
}
if (name1.lenght < name2.length) return -1;
return 1;
}
</script>
</center>
</body>
</html>
Just put the names into an array and use Array.sort to order them.
// Create a new, empty array
var names = [];
// Prompt for the names and put each into the array:
names.push(prompt("Enter your first name:",""));
names.push(prompt("Enter your middle name:",""));
names.push(prompt("Enter your last name:",""));
// Sort the names:
names.sort();
// Print the results:
names.forEach(function(value){
console.log(value);
});

For loop wont run properly

I am trying to build a function that changes values in innerHTML of elements which have one class name, but different number values.
as in:
<div class="ingredient-assignment__quantity">5</div>
<div class="ingredient-assignment__quantity">300</div>
<div class="ingredient-assignment__quantity">250</div>
And I want a calculation (same for all) to run through all of them and then change the innerHTML of each to the result of each.
as in:
calcuation = 5 * innerHTML;
<div class="ingredient-assignment__quantity">25</div>
<div class="ingredient-assignment__quantity">1500</div>
<div class="ingredient-assignment__quantity">1250</div>
My JS function looks like this:
function ingredientChange (){
var portionsBefore = document.getElementById('portions');
var ingredients = document.getElementsByClassName('ingredient-assignment__quantity');
function getPortions(event) {
const getID = event.target.id;
if (getID == "minus") {
var y = Number(portionsBefore.innerHTML) - 1;
}
else {
var y = Number(portionsBefore.innerHTML) + 1;
}
changeIngredients(y);
portionsBefore.innerHTML = y;
}
function changeIngredients(y) {
var arr = Object.keys(ingredients).map((k) => ingredients[k])
for(var i = 0; i < arr.lenght; i++){
var changeValues = Number(arr[i].innerHTML) / Number(portionsBefore.innerHTML);
var changedValues = Number(changeValues) * y;
}
}
function addEventListeners () {
document.getElementById('minus').addEventListener('click', getPortions, false);
document.getElementById('plus').addEventListener('click', getPortions, false);
}
addEventListeners();
}
ingredientChange();
And everything except for the for loop works fine.
I cant find, whats wrong with the for loop
You have a typo in your for loop
arr.lenght should be arr.length.

Animate array from user input like typewriter (javascript)

I suppose my question is a bit similar to this one, but I can't really work out how to do my specific need from it. I'm building a very basic text adventure, and I'd like the returned text - after the user has entered a command - to be returned in a typewriter style. Here's a snippet of my commands so far (there'll be a lot more, I don't mind that this will be built in a bit of a tedious way)
<script>
textIn = document.getElementById("input-textbox");
textOut = document.getElementById("output-textbox");
function process(input) {
if (input == "hi") { textOut.innerHTML += "Hello to you too!<br><br>"; }
else if (input == "exit") { textOut.innerHTML += "No."; }
}
function go() {
var input = textIn.value;
textIn.value = "";
var output = process(input);
textOut.value += output + "\n";
}
</script>
and the HTML
<div id="output-textbox">
Returned text goes here.
</div>
<form onSubmit="go();return false;">
<input id="input-textbox" name="command" value="" autofocus="autofocus"/>
</form>
Thank you so much for your help in advance! This solution doesn't need to be beautiful, code wise, nor very nifty. It just has to work, I have no standards at all with this!
Based on William B's answer, here is a more condensed version:
https://jsfiddle.net/sators/4wra3y1p/1/
HTML
<div id="output-typewriter"></div>
Javascript
function typewriterText(text) {
var outEl = document.querySelector('#output-typewriter');
var interval = 50; // ms between characters appearing
outEl.innerHTML = '';
text.split('').forEach(function(char, i){
setTimeout(function () {
outEl.innerHTML += char;
}, i * interval);
});
}
typewriterText('this is an example');
Create a timeout for each character inside a loop, with each timeout being a bit later than the last. See: https://jsfiddle.net/fswam77j/1/
var outputEl = document.querySelector('#output-textbox');
var charInterval = 50; // ms between characters appearing
function showOutput(text) {
outputEl.innerHTML = '';
for(var i = 0; i < text.length; i++) {
showChar(text, i);
}
}
function showChar(text, i) {
setTimeout(function () {
outputEl.innerHTML += text[i];
}, i * charInterval);
}
showOutput('this is an example');
process the input:
function process(input) {
if (input == "hi") {
showOutput("Hello to you too!");
}
else if (input == "exit") {
showOutput("No.");
}
}

Textarea disappears after setting value

Here's what I'm trying to do:
Type initials (e.g. MS,AK,LT) by clicking on "Enter Names". This saves a string, which I then turn into an array (nameArray) in order to get each set of initials. After reordering these randomly, I want to place some of the initials into the textareas, but that's where things go wrong.
Here's what's wrong:
the initials display for a moment, then disappear after the function executes. (ALSO, I'm trying to have a div (with text "randomizing...") that is otherwise hidden, show itself for 4 seconds (4000 ms) while the initials are being reordered to indicate as such. That's what the setTimeout is for...but that doesn't work either. The div disappears along with the text). Why are these only in coordination with the execution of the function?
Here's the JS code:
var nameArray;
window.onload = pageLoad;
function pageLoad() {
$("#randomizingNotification").hide();
$("#prev_arrow").click(prevUser);
$("#next_arrow").click(nextUser);
$("#enter_names").click(orderNames);
}
function orderNames() {
nameArray = getNames();
randomizeNames();
displayNames();
}
function getNames() {
var initialsString = prompt("Please enter initials, separated by a comma (e.g LK,AS,NM)");
nameArray = initialsString.split(",");
return nameArray;
}
function randomizeNames() {
$("#randomizingNotification").show();
var timer = setTimeout(function(){randomize(nameArray);},4000);
$("#randomizingNotification").hide();
clearTimeout(timer);
}
function randomize(array) {
for (var i = 0; i < array.length; i++ ) {
var randNum = Math.floor(array.length*Math.random()) //random number between 0 and length of array (rounded down
var temp = array[i];
array[i] = array[randNum];
array[randNum] = temp;
}
}
function displayNames() {
var curr, up, prev, current, upcoming, previous;
curr = 0;
up = 1;
prev = null
current = nameArray[curr];
upcoming = nameArray[up];
$("#upcoming_pick").val(upcoming);
$("#current_pick").val(current);
}
Here's the relevant HTML code:
<body>
<div id="header">
<div id="randomizeNotContDiv">
<div id="randomizingNotification">randomizing...</div>
</div>
<div id="page_title"><h1>Welcome to Classtech Shift Scheduler!</h1></div>
<div id="helper_functions_div">
<div id="enter_names_div">
Enter Names
</div>
</div>
<div id="main_content">
<div id="name_tracker">
<div><img src="Images/prev_arrow.png"/></div>
<textarea name="upcoming_pick" cols="10" rows="1" class="picker_names" id="upcoming_pick"></textarea>
<textarea name="current_pick" cols="10" rows="1" class="picker_names" id="current_pick"></textarea>
<textarea name="previous_pick" cols="10" rows="1" class="picker_names" id="previous_pick"></textarea>
<div><img src="Images/next_arrow.png"/></div>
</div>
You've got at least few issues, but the main problem is the structure of your setTimeout. A setTimeout is like an AJAX call in that it's non-blocking. Anything inside the function you pass to it will only execute when the timer is done, while code that comes after it will execute immediately.
I've reorganized the hiding of your randomization message and the displayNames function to go inside of the setTimeout function and things work fine.
Here it is in a fiddle: http://jsfiddle.net/nate/LB6dz/
And here's the code:
var nameArray;
window.onload = pageLoad;
function pageLoad() {
$("#randomizingNotification").hide();
$("#enter_names").click(orderNames);
}
function orderNames(event) {
// Prevent the link's default action
event.preventDefault();
nameArray = getNames();
randomizeNames();
}
function getNames() {
var initialsString = prompt("Please enter initials, separated by a comma (e.g LK,AS,NM)");
nameArray = initialsString.split(",");
return nameArray;
}
function randomizeNames() {
$("#randomizingNotification").show();
var timer = setTimeout(function (){
randomize(nameArray);
// These items need to be inside the timeout, so they only run once it's done
$("#randomizingNotification").hide();
displayNames();
}, 4000);
// No need to clearTimeouts after they're done... they only run once
// clearTimeout(timer);
}
function randomize(array) {
for (var i = 0; i < array.length; i++ ) {
var randNum = Math.floor(array.length*Math.random()) //random number between 0 and length of array (rounded down
var temp = array[i];
array[i] = array[randNum];
array[randNum] = temp;
}
}
function displayNames() {
var curr, up, prev, current, upcoming, previous;
curr = 0;
up = 1;
prev = null
current = nameArray[curr];
upcoming = nameArray[up];
$("#upcoming_pick").val(upcoming);
$("#current_pick").val(current);
}

Categories