I have a spelling game that uses JavaScript.
Currently when the word is spelled correctly it will display a message.
if(++score >= str.length) {
var text = 'Well done! The correct word is ' + str + '!'
drawBackground(background, images.back, text);
}
I would like to display one point for each correct word and increment it.
This is what i have tried but no luck
function points() {
var points = 0;
if(++score >= str.length) {
points++;
document.getElementById("points").innerText="Score: " + points;
}
}
The HTML to display the score
<p>Score: <span id="points"></span></p>
Problems with your code:
The value of points is being reset to 0 every time you enter the points() function. You must move var points = 0 outside of points(), making it a global variable.
As you cannot have a function and a global variable with the same name, you must rename the points variable (e.g. to numPoints).
The el.innerText property will only work on IE. Replace it el.textContent.
Improved version of your code:
let numPoints = 0;
function points() {
if(++score >= str.length) {
numPoints++;
document.getElementById("points").textContent = "Score: " + numPoints;
}
}
Related
I've already had one questions regarding this game answered, but I keep getting stuck up on keeping track of my "wins" and "losses" and then reseting my random word after a win or a loss. Here is what I have so far:
var guess; //user guess
var letters = []; //correctly guessed letters
var wrongLetters = []; //incorrectly guessed letters
var counter = 7; //counts correct letters
var losses = 0;
var wins = 0;
document.getElementById("counter").innerHTML = counter;
document.getElementById("losses").innerHTML = losses;
document.getElementById("wins").innerHTML = wins;
var wordList = ["cat", "dog", "wolf", "laser", "apple"]; //FILL LIST LATER!!
//randomly chooses a word from wordList
var word = wordList[Math.floor(Math.random() * wordList.length)];
//choosen word is replaced with
function start() {
for (i = 0; i < word.length; i++) {
letters[i] = "__";
}
document.getElementById("answer").innerHTML = letters.join(" ");
console.log(word);
}
//checks if letter is in the word or not
function checkLetter() {
document.onkeyup = function(event) {
guess = event.key.toLowerCase();
var found = false;
for (i = 0; i < word.length; i++) {
if (guess === word[i]) {
letters[i] = guess;
document.getElementById("answer").innerHTML = letters.join(" ");
found = true;
}
}
//wrong letters go into the wrongLetters array and are displayed
if (found) return;
if (wrongLetters.indexOf(guess) < 0) {
wrongLetters.push(guess);
document.getElementById("wrongGuesses").innerHTML = wrongLetters.join(" ");
counter--;
console.log(counter);
//+1 to the losses if 7 words are missed
if (counter === 0) {
document.getElementById("losses").innerHTML = losses + 1;
console.log(losses);
confirm("play again?"); {
counter = 7;
letters = [];
wrongLetters = [];
start();
}
}
}
}
}
//need the counter to subtract 1 with every wrong guess
//when counter hits zero losses = losses + 1
//make a wins var that adds 1 when word is guessed
//reset if either are
start();
checkLetter();
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>Hangman!</h1>
<span>Just start writing to play.</span>
<p>
<font size="+3"><span id="answer"></span></font>
</p>
<p id="counter"></p>
<p id="wrongGuesses"></p>
<p>Wins: <span id="wins"></span></p>
<p>Losses: <span id="losses"></span></p>
</body>
</html>
The counter is ALMOST working! It seems to be counting down from 7 and adding 1 to the losses when it reaches zero as it should; however, the count displayed is off (even though the count logged to the console seems right).
Another issue is that this "losses" count won't continue to add past 1 even if the counter resets and hits 0 again.
Also, when I try to grab a new random word after the player fails to answer the first, the game chooses the same word as it did before.
I feel like most of these issues have to deal with the scope of my variables, but none of the reworking I try seems to have any affect (if it doesn't make things worse). I know I'm asking a lot here, but if anyone could even point me in the right direction it would be greatly appreciated!
Lets start with fixing the random word.
The variable word needs to be accessed by several functions so it need to be defined on a scope outside the current functions. But you want to set it new each time inside the start() function. You can do that by declaring the variable outside of the function where it is now, but set it inside the function. You should also reset the counter here.
//randomly chooses a word from wordList
var word
//choosen word is replaced with
function start() {
word = wordList[Math.floor(Math.random() * wordList.length)];
counter = 7;
document.getElementById("counter").innerHTML = counter;
for (i = 0; i < word.length; i++) {
letters[i] = "__";
}
document.getElementById("answer").innerHTML = letters.join(" ");
console.log(word);
}
The counter isn't working, because it doesn't look like you're updating the html when the counter changes. You need something like this with each guess:
document.getElementById("counter").innerHTML = counter;
counter--;
console.log(counter);
The losses aren't incrementing because you are only changing the HTML but not the losses variable (kind of the opposite of the above). You need both:
losses++
document.getElementById("losses").innerHTML = losses;
There is also one subtly problem -- you are catching all the keyups including an enter keyup when you first start. You can catch only letters with something like this:
document.onkeyup = function(event) {
// don't catch numbers, punctuation, enter, etc.
if (!(event.which <= 90 && event.which >= 65)) return
I have a job. Unfortunately I got stuck. Could you help me.
Project:
Ask a sentence of user analysis.
Ask to see which letters you want the user to count the block.
Count the number of times that the letter occurs in the sentence.
A pop-up window and then type the following sentence: "The letter X times Y occurs in this sentence."
Must be use function!
I write this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
for (i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) {
alert("The letter " + letter + " occurs " + sentence.charAt(i) + " times in this sentence.")
}
}
return;
}
bernardTheLetterCounter();
You have to finish the counting (the inside of the loop) then print the result after the loop is done. Like this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
var count = 0; // the counter (initialized to 0)
// use var i instead of i (to make i local not global: this is just an advice)
for (var i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) { // if it is THE LETTER
count++; // increment the counter (add 1 to counter)
}
}
alert("The letter " + letter + " occurs " + count + " times in this sentence."); // use counter to print the result after the counting is done
// the return here has no meaning
}
bernardTheLetterCounter();
What you was doing is printing a message every time the letter is found (which is ugly for the user, especially if the count of that letter is big).
The function in this example can be re-used and tested. (ps. the for-loop is not a functional way of solving your problem).
var sentence = prompt("Please type in the phrase to be examined:");
var letter = prompt("Please enter the letter you are looking for:");
function countLettersInString(source, letterToFind) {
return source
.split('')
.filter(function(letter) { return letter === letterToFind; })
.length;
}
console.log([
'letter', letter,
'was found', countLettersInString(sentence, letter),
'times.'
].join(' '));
Im trying to get a counter to register the least number of rolls it took to get a double and then when they play the 'game' again if they got an even lower number of doubles it replaces the first answer with the newer one.
count=0, doubles=0, lowest=10000000;
function Roll()
// Assumes: die images are in http://dave-reed.com/book/Images
// Results: displays a randomly selected image of a 6-sided die
{
var roll1, roll2;
roll1 = RandomInt(1, 6);
roll2 = RandomInt(1, 6);
document.getElementById('die1').src =
"http://dave-reed.com/book/Images/die" + roll1 + ".gif";
document.getElementById('die2').src =
"http://dave-reed.com/book/Images/die" + roll2 + ".gif";
count += 1;
if (roll1==roll2) {
doubles += 1;
}
if (doubles==3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
doubles=0;
count=0;
}
if (doubles==3 && lowest>count){
lowest=count
document.getElementById('lowestLine').innerHTML = count;
}
document.getElementById('countLine').innerHTML = count;
document.getElementById('doublesLine').innerHTML = doubles;
}
You set doubles to 0 once it becomes 3 and then you check if doubles equals 3 which is never true.
It looks like you should put
if (lowest > count) {
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
inside first doubles === 3 check, but before you setting globals to 0.
Like this:
if (doubles === 3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
if (lowest > count){
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
doubles = 0;
count = 0;
}
I'm trying to get a user to write a sentence and then have the computer confirm each word in a separate "confirm window" without using spaces.
In order to figure out if this code is the correct code to do this task I have to run the code, but
I'm getting the error listed in the title for line four. First, I don't understand what the error is saying. And if it is telling me that on line four the ifstatement is not a function and it can not run it, then how come?
<script>
function sentenceFinder (sentence){
for (counter = 0; counter < sentence.length; counter++){
if (sentence.substring(counter, counter + 1) !== " "){
words.push(sentence.substring(counter, counter + 1));
}
else {
comfirm(words[0]);
}
};
}
var x = prompt("Please type in the sentence that will be seperated.")
sentenceFinder(x)
var words = []
</script>
You have two issues which are causing errors.
You are using subscript where I think you intended to use substring.
You are using words before you set it to an array.
I think this is what you intended to write.
function sentenceFinder (sentence){
for (counter = 0; counter < sentence.length; counter++){
if (sentence.substring(counter, counter + 1) !== " "){
words.push(sentence.substring(counter, counter + 1));
}
else {
comfirm(words[0]);
}
};
}
var words = [];
var x = prompt("Please type in the sentence that will be seperated.");
sentenceFinder(x);
I am trying out javascript for (more-or-less) the first time and find myself completely baffled by the following .js script.
var pair = newArray();
var id = newArray();
var pairs = 2;
function newGame(){
var randomid = 0;
alert("newGame() called!");
// Sets a specific part of the image sprite to each pair[].
for (var i=0 ;i < pairs; i++){
alert("For loop started!");
pair[i] = "url(Cardfront.jpg) -"+100 * Math.floor((Math.random()*13)+0)+"px -"+200 * Math.floor((Math.random()*4)+0)+"px";
// For every pair, assigns a part of the image sprite to two id[]-s.
alert("Pair " + i + "is " + pair[i]);
for(var j=0; j < 2; j++) {
//the range of possible id-s the total number of cards - double the amount of pairs.
randomid = Math.floor((Math.random()*pairs*2)+0);
if (id[randomid] === null){
id[randomid] = pair[i];
alert("ID " + randomid + "is " + id[randomid]);
}
else j--;
}
}
alert("This is called after the for loop!");
}
When I call newGame() through a button, I receive the "newGame() called!" and then "This is called after the for loop!" alerts, then nothing.
I've spent a while googling and poking around trying to figure this out, but I'm at the end of my wits, it seems.
Change newArray() to new Array() I believe that is what is causing your error sir.
Good luck!
EDIT: To fix the other error I found you have the following:
if (id[randomid] === null) {
with 3 = sign. Change it to just two:
if (id[randomid] == null) {
and it should work the way you expect it to.
Unless you are really trying to use the strict comparisson operator, then there is something else bugging your code.
In this piece of code:
if (id[randomid] === null){
id[randomid] = pair[i];
alert("ID " + randomid + "is " + id[randomid]);
}
else j--;
You can't mix the if/else shorthand:
if(something)
//Do X
else
//Do y
With it's bracket notation:
if(something){
//Do X
} else {
//Do y
}
So, put brackets around your else:
if (id[randomid] === null){
id[randomid] = pair[i];
alert("ID " + randomid + "is " + id[randomid]);
} else {
j--;
}
The for loop should read:
for (var i=0; i<pairs.length; i++) {
...
}
pairs is being coerced into a numeric value (zero in this case), so the first comparison (i<pairs) will be the same as 0<0 which will never true.
:-(