I'm more or less new to JavaScript and am going to attempt a very basic version of Hangman to get me going.
I'm starting out with trying to display a number of lives when the user first enters the page, this will decrement with every letter they choose that doesn't feature in the word.
My JavaScript in an external file is as follows:
var lives = 5;
//Display the number of lives the user has remaining
var showLives = function(){
document.getElementById("livesLeft").innerHTML = lives;
}
//Will decrease lives each time incorrect letter is chosen
function decrementLives(){
lives--;
showLives();
}
The problem is when I initially load the HTML page, there is no value displayed for number of lives remaining, I expect it to say 5.
When I click anywhere on the body though(currently hard coded to call decrementLives() for testing purposes) it works exactly how I'd like. Displaying 4, 3, n-1 with every click.
Any ideas as to why this first isn't initially showing up like 5 like I expect. I've been thinking it might be possibly something to do with the lives variable scope?
You have to actually call the function on page load. For example in onload event:
window.onload = showLives;
Related
I'm working on a project that plays a game of rock paper scissors
the game works fine but i want to add something into it. a pointing system where it will add 1 each time a player win but i can't seem to make this work i've been trying to find workarounds for almost 2 day now but i can't seem to find any solution. The thing is the code works but after i log the function that adds 1 to a variable but after that it returns to it's original value which is 0.
const one = 1
function addone(test){
test += 1
}
addone(one)
console.log(one)
This print the original value like the function did not do anything to it. im so confused.
I see two problems in your code:
one is a const variable. That means that you can't modify its initial value.
test is a local variable inside your function, that means function won't modify the values of the variable that you pass as parameter (one).
There is an operator(++) that add a unit, I highly recommend you to use it instead of make a function:
var one = 1
one++;
console.log(one)
If you want to use a function you have to do like this:
var one = 1
function addone(test){
return test+1;
}
one = addone(one);
console.log(one)
In terms to store permanent data into a javascript variable, that's not possible. Variable are stored in RAM, that means that when you stop the program, al data of your program are wiped. Permanent store are made in database and other complex data structures.
If you want to play multiple games, you should consider to allow the players to play more games before the program finish.
thank you very much i never think that i could get more dumb so i cant manipulate it because it's just a copy of that variable that im inputing as parameter? so it means that the function did not touch the variable at all. I wish i could go back to my mother's womb.
and the const it's just a typo very sorry for this.
i did not know this website is very active i thought i would wait days just to get a response thank you very much and have a nice day
I'm having a really hard time understanding what I did wrong in my code in order to have a value saved in local storage.
I have a pretty big code project so I'll try to summarize what the program is tryin to do overall.
I am pulling news articles from the news API and displaying the articles; each article (depending on the publication it came from) pushes a different numeric value into an array allSource2.
I then take the sum of this array to arrive to a "score" (variable is called sum)
I basically want that score to be locally stored, so that it is available even after a page refresh.
I think something wrong might be happening because of where I put the localStorage function. Currently I put it under the click event that also pushes the numeric value in the array (when you click the article title).
I am super confused at where else it could be, so that it truly updates the sum every time that sum changes.
Also, it does work to store it (I checked localStorage on the console, after a refresh it still works, but after refreshing and then clicking on another article, it resets to whatever the value of this article is)
I didn't put the entire code, as it's insanely long. everything else is working fine, it's just that.
Also, the all of this is contained within one big function
I define let sum =0; at the beginning of the code.
Then, this is the click event.
document.getElementsByClassName('article-rating')[i]
.addEventListener('click', function(event) {
sum = allSource2.reduce((tempSum, val) => tempSum + val);
console.log("article score is now" + " " + sum);
var lastname = localStorage.getItem("overallsum");
localStorage.setItem("overallsum", sum);
});
I also tried to put the var lastname = localStorage.getItem("overallsum"); at the beginning of the code, when the first function but no luck.
Thanks a lot for your help!
and apologies for any formatting issues, I'm super new to this.
Each time you click the event the overallsum is getting set and that is the problem. If the overallsum is a one time store to the local storage then you can check if the value of overallsum is null, and if so store the value for the first time.
Example:
if (localStorage.getItem("overallsum") === null) {
localStorage.setItem("overallsum", sum);
}
Otherwise, if the overallsum is something, then for every individual article you could 2D array and then set the value with the same conditional check.
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.
So I'm basically trying to implement an online trading card game in php and (maybe minimal) javascript, and so far I have a GUI set up in php, a database with the required tables (so far) to hold the decks, fields, and other various data. I've got it to the point where i have a function that initializes the fields for both players and populates their fields and hands with cards from their deck. I also got it to the point where a player on another computer or device can take the room number of the game and join the game so the see the exact initialized field.
my next objective was to be able to set up the turn logic, and allow the screen to update for one player while the other is making plays during their turn. My problem is I'm not sure what the minimum viable solution will be for this, because I have long intricate functions that display the current field based off of values that come from a field table. So my ideal logic is set up like this:
//find game form
//host game form
//if host is set (post){
//call insert field function (a long function that creates a table for the current game being played and initializes the field and hand with random cards from the deck table)
//link game to host for future field printing
// populate host function (a function that prints a table of every card on the field with the most up to date variables to represent each spot)
}
//if find is set (post){
//call insert field function
//link game to host for future field printing
//a button form to start the game which begins by calling heads or tails
// populate find function (same as host but for find player side)
}
//if start game is set (post){
// do game logic such as coin flip which will be notified to opponent in a message field in the game table upon the refresh
}
I was wrapping the populate host function in a refreshable div like this:
print "<div><meta http-equiv='refresh' content='5' />"; //host populate just disapears
populatehost($roomnumber); //populates self and opponents in hosts perspsective
print "</div>";
so that the function would be called every 5 seconds or so, but this just causes the field to disappear after 5 seconds. So...
Why is it disappearing?
How can i get it to refresh the page and just display one instance of the field using the populate field function?
Is this approach viable? if not, what's the easiest approach I could take and how?
I also tried a solution where the function was called every 5 seconds and gotten rid of, but i'm not sure if I was doing it right, the PHP manual didn't explain it very clearly, and after lots of trial and error i think i crashed my server. It was something like this:
//loop
ob_start();
populatehost($_SESSION['gamenumber']);
sleep(5);
ob_end_clean();
I kept playing around with that logic but it either printed infinitely, didn't print at all, or crashed my server. I'm afraid to play around even more for fear of crashing the server again. Maybe someone can explain the correct way to do it or why it is not viable if it isn't?
I'm sorry if these are dumb questions, I've spent days and days researching approaches to this problem, I wasn't sure if I could implement it using javascript or ajax along with my field printing function, I tried some and they weren't working, and I'm not sure if it's because my approach is viable or not.
You can take javascript or Ajax help for div you can assign id to the div and call id in javascript:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
check this fiddle:
http://jsfiddle.net/arunpjohny/asTBL/
Thanks
So I am making a hacking type game coded with HTML and JavaScript, and I made a Store.html file for my store to purchase upgrades for your hacking system. I have several variables that I want to view and change from a different file than the one that I originally have it inside of.
Variable 1
var tutorialDone = false
Variable 2
var jobBoolean
Variable 3
var bitCoins = 30
var currentBit = bitCoins
I want this to be false because when the tutorial mission is finished, then I want to change the jobBoolean variable to "true" because when the tutorial mission is completed, then I want a new list of missions/jobs to show up on thee screen. The first mission is a seperate page. At the end of the mission when it is completed, then "tutorialDone" I want to be equal to "true", so that when I am back at the homepage, I can change the jobBoolean to true. Because the "tutorialDone" variable is dependent on the "jobBoolean" variable. When "tutorialDone" equals "true" so does "jobBoolean". I don't know how to make "tutorialDone" change along with the "jobBoolean".
I have for the third variable, there is two. That is because they are similar. I have a function inside the "Store.html" document that when an item is purchased, it grabs a variable which in this case is "currentBit". "currentBit" is equal to "bitCoins" because I thought that if I made a new variable, "currentBit", then set it equal to "bitCoins", it would connect with "bitCoins" from a seperate file. This was my only "solution" I could think of, but it doesn't work.
Also, as a bonus answer for you guys, how can I make an "if" statement in JavaScript, and then have it check if the variable I give it is equal to something, and if it is, run some code. Because whenever I try it, the function the if statement is in, it will run through the if part of the statement no matter if the statement is true or false.
Sorry if this question doesn't make much sense. This is just the first big problem I have encountered with JavaScript, that I couldn't fix myself.