Displaying wrong answers - javascript

I have created a spelling game where the user spells the word by clicking on letters. To show the user how many they have wrong and right I count the amount of times the right and wrong message is displayed and print it to the user.
This works perfectly for correct answers but not for wrong answers. Can someone tell me why?
This is the script for the correct answers (works fine)...
var completeLetters = $('.wordglow2').length;
var completeWords = (completeLetters / 3);
if ($(right).show()) {
$('.counter').html("Right Answers = " + completeWords).show();
}
Here is the one for incorrect answers (exactly the same logic, but won't work!)...
var incompleteLetters = $('.wordglow4').length;
var incompleteWords = (incompleteLetters / 3);
if ($(wrong).show()) {
$('.counter2').html("Wrong Answers = " + incompleteWords).show();
}
So basically "wordglow4" is the style added to the letter when it is incorrectly spelt and "wordglow2" is the style added to the correctly spelt letters.
All the words are 3 letters long, hense the "(incompleteLetters / 3)"
Here is a fiddle to help http://jsfiddle.net/smilburn/Dxxmh/34/

the 'complete words' counter works because you always leave the '.wordglow2' style on the table cells when the word is completed. Therefor $('.wordglow2').length will always return the total completed letters (and hence words)
However, the incorrect words won't work, because as soon as the user gets it right, the style is changed (from '.wordglow4' to '.wordglow2' - p.s. you might want to think about using more descriptive class names - e.g. '.correctLetter' and '.wrongLetter'). Thus, you'll never have more than 3 '.wordglow4' letters on screen, so the incompleteWords counter will never get past 1.
To make the incorrect word counter work, you'll need to declare the counter outside the function, and do something like:
var incompleteLetters = $('.wordglow4').length;
incompleteWords += (incompleteLetters / 3);
This should then keep track of previous failures, and give you the behaviour you want

There is only ever one wrong answer indicated on the board by the table cells with the class .wordglow4, unlike the correct answers which maintain the .wordglow2 class after they have been guessed correctly.
So the count of .wordglow2 will always be correct, whereas the count of .wordglow4 will only ever be 3.
You should move the count variable outside of the .click() event and increment it when a word is guessed incorrectly.
So, in your example code, add...
var animation = false;
var incompleteWords = 0; // <-- this line
$('.drag').on('click', function(e) {
and change
var incompleteWords = (incompleteLetters / 3);
to
incompleteWords += (incompleteLetters / 3);

Related

How do I output a new random number to an HTML doc(via innerText) in JavaScript?

I am doing a simple math game in HTML and JavaScript for school, this is just a small part of it. Basically I have a button that I want to be able to press, and each time I press it I want it to output a new number to the innerText of a div in the HTML document.
Right now I get the random number, but I have to refresh the page to get a new one since it keeps outputting the same one if I press it again.
const mathQuestion = document.getElementById('math-question')
const newNumbers = document.getElementById('new-btn')
newNumbers.addEventListener('click', setQuestion)
function setQuestion () {
mathQuestion.innerText = calc.toString();
console.log(calc);
}
var calc = Math.floor(Math.random() * 100) + 1;
Yes, it's very simple and probably not the easiest or even the correct way to do it, but I am at a loss here.
I suspect I need to run another function for reseting the text or something after ive set the innerText, but I don't really know where to start.
Currently, you only generate the random number once and when you click the button, you set the same number in the HTML. That is why you see the same number irrespective of how many times you click the button.
Number changes on page reload because each time page reloads, new random number is generated.
You need to re-generate the random number every time the button is clicked. To do this, move the random number generation code inside the event handler function and it should work as expected.
function setQuestion () {
var calc = Math.floor(Math.random() * 100) + 1;
mathQuestion.innerText = calc;
}
Also, there's no need to explicitly convert the number into a string.

Javascript random number generator with function()

alright, so I have an assignment here where I need to generate a random number but its not working so well. I've done it before but things aren't working for me; basically even tho we are generating rnadom numbers it needs to show the user to go up or down if the guess isn't correct and at least one random time the nuber the user guesses is supposed to be correct. Apparently i have things misplaced but my coding is right. I'm trying to figure out how to get this working and an explanation why i was wrong because i'm still learning a lot. Thank you.
<html>
Number guessing game
Welcome to number guessing game. Please make a guess between 1 and 10 to find the hidden number
Make a guess
// 1. Generate a number between 1 and 10 - done
// 2. Create a function named guess so that when button is clicked function is executed. - done
// 2.1. Inside the function get the value user entered from the input box. - done
// 2.2. Inside the function check if the number is smaller than randomNumber, if so display "Go up" in the div with result id. - done
// 2.3. Inside the function check if the number is bigger than randomNumber, if so display "Go down" in the div with result id. - done
// 2.4. Inside the function check if the number is equal to randomNumber, if so display "You guessed right!" in the div with result id. - done
//If working correctly your page should allow the player to guess the correct number by getting instructions from your code.
function guess() {
var userInput = parseInt($("#guess").val());
console.log(userInput);
var randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber);
if (randomNumber == userInput) {
$("#result").html(`you guess correctly!`);
console.log(result);
} else if (randomNumber < userInput) {
$("#result").html(`higher!`);
} else {
$("#result").html(`lower!`);
}
}
</script>

Java Script + Node.js Calculator issue

I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;

Getting wrong output when trying to loop through the first 50 even Fibonacci numbers in JavaScript [duplicate]

This question already has answers here:
Javascript looping through Fibonacci numbers and testing for even numbers
(2 answers)
Closed 8 years ago.
I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.
I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”
I needed to:
1. create a loop that generates Fibonacci numbers.
2. test each one for whether it's even or odd.
3. Add up up the even ones, counting them as you go.
------------HERE IS MY CODE THUS FAR --------
<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is:
<span class="" id="sumFibResult"></span>
<script>
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function () {
fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum() {
var loopFib;
//Initialize fibonacci array
var fibonacci = new Array();
//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum = 0;
//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
for (loopFib = 2; loopFib <= 150; loopFib++) {
// Next fibonacci number = previous + one before previous
fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];
//test for even numbers with if then statement
var integer = parseInt(fibonacci[loopFib]);
if (integer % 2 == 0) {
//Add up the even fib numbers if even and output into dispay variable
var display = sum += fibonacci[loopFib];
//output results to html page
document.getElementById("sumFibResult").innerHTML = display;
}
}
}
</script>
http://jsfiddle.net/isherwood/38gPs
I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...
Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:
console.log('integer for ' + loopFib + '=' + integer);
Or
console.log('display=' + display);
To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.

How to make a game out of an html table?

I'm basically trying to make a game that involves a grid. Here's what I have so far (it'll help to see the game before I explain what I need to happen):
Javascript (see jsfiddle for html):
var score = 0;
var points = function(val, box) {
var noise = Math.round(Math.round(0.1*val*Math.random()*2) - 0.1*val);
score = score + (val + noise);
var square = document.getElementById(box);
square.innerHTML = val + noise;
square.style.display='block';
setTimeout(function() {
square.style.display='none';
}, 400);
document.getElementById("out").innerHTML = score;
}
http://jsfiddle.net/stefvhuynh/aTQW5/1/
The four red squares at the bottom left of the grid needs to be the starting point in the game. When you click on one of those boxes, you can then travel along the grid by clicking adjacent boxes. Basically, I need to make it so that the player can only travel up, down, left, and right from the box that they just clicked on. I don't want the points function to be invoked when the player clicks on a box that they're not supposed to click on.
Additionally, I need to make it so that the player can't click on another box until 400 ms have elapsed.
I'm relatively new to programming so any help at all would be great. I would also appreciate tips on how to make the program more efficient, if there's a way to do that.
General idea:
I'd suggest having a similar id for all your boxes, such as box_x_y, and storing a list of strings, let's say allowedSquares.
You would then be able to write a function which, upon clicking on a box, would check if it's id is in allowedSquares, and if it is, call points(val, box) then update the contents of allowedSquares to reflect the change of position.
The point of using a standard id convention for all your boxes is that you could write getPosition(box) and getBox(intX, intY) that would parse the id strings to return you the box position, or vice-versa.
You can even make the updateAllowedSquares(clickedBox) function change the color of adjacent boxes to show they're allowed next steps.
EDIT: Some example code:
Disclaimer: these are not the code lines you're looking for.
This is only a starting kit for you, which assumes a 3x3 grid with a single-square bottom right starting position. You will have to adapt this code a bit. Also, I predict something will go wrong concerning going out of bounds. I'll let you think with this a bit, as I prefer giving food for thoughts over complete solutions in those cases...
var allowedSquares = ["box_2_2"]; // Initial list
function decodePositionFromID(boxId) {
return boxId.split("_").slice(1,2);
}
function getIDfromXY(x, y) {
return "box_" + x + "_" + y;
}
function updateAllowedSquaresList(boxID) {
// 1 - We clear the array.
allowedSquares.length = 0;
// 2 - We get the adjacent boxes IDs.
var xyArray = decodePositionFromID(boxId);
var upperBoxID = getIDfromXY(xyArray[0], xyArray[1]-1);
// Rince, repeat, and add some gameboard boundaries checks.
// 3 - We add the new IDs to the list.
allowedSquares.push(upperBoxID, ...);
}
function boxClick(val, boxID) {
// We check if the box is a valid square to play.
if (allowedSquares.indexOf(boxID) != -1) {
points(val, boxID);
updateAllowedSquaresList(boxID);
}
}

Categories