This code is breaking really bad if i remove the bold line - javascript

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="message-el">Want to play?</h1>
<p id="cards-el"></p>
<p id="sum-el"></p>
<button onclick="startGame()">Start Game</button>
<button onclick="newCard()">New Card</button>
<script src="abc.js" defer></script>
</body>
</html>
let firstCard = 10
let secondCard = 4
let cards = [firstCard,secondCard]
let sum = firstCard + secondCard
let isAlive = true;
let blackJack = false;
let msg = ''
let showMsg = document.getElementById('message-el')
let showCards = document.getElementById('cards-el')
let showSum = document.getElementById('sum-el')
function startGame(){
renderGame()
}
function renderGame(){
showCards.textContent = 'Cards: ' it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why
for (let i = 0; i<cards.length; i++){
showCards.textContent += cards[i] + " "
}
showSum.innerText = "Sum:" + sum;
if(sum <= 20){
msg = 'Draw a new card?'
}else if(sum === 21){
msg = 'BlackJack!'
blackJack= true
}else{
msg='Lose'
isAlive = false
}
showMsg.innerText = msg;
}
function newCard(){
let card = 1;
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
sorry for this quantity of code,but i really want to make it clear and understand the logic

it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why
The initialisation of showCards.textContent = 'Cards: ' is important, as it removes the previously displayed cards.
This is needed because the loop that follows will iterate over all dealt cards and add them to the showCards.textContent output -- all of them. So if that textContent already had some cards from the previous turn, they will be duplicated.

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

I was practicing a way to loop numbers to create a times table but the loop only runs one time

I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>

How to add an animation gif to a javascript program

I am very new to the world of coding and I am in a coding bootcamp learning about JavaScript. We created a number guessing game and I am trying to add an animation that will run after the correct answer is entered. I have googled a few times trying to find the answer, but I was looking to see if there is an easier way. I have included a copy of the program below. If I wanted an animation to appear after the correct answer is entered, how could I do that?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
To be able do that you need to learn DOM Manipulation.
Here is a simple example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
// add your gif to the dom
// create an img element
const img = document.createElement("img")
// set the source of the gif
img.src = "https://i0.wp.com/badbooksgoodtimes.com/wp-content/uploads/2017/12/plankton-correct-gif.gif?fit=400%2C287"
// add the img element to the dom
// in this case we are gonna add it after the 'start game' button, so
// select the button element
const btn = document.querySelector("button")
// insert the img element after the button
btn.parentNode.insertBefore(img, btn.nextSibling);
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
keep going and good luck.

How to push score into an array, then display it

I'm trying to make a dice game where the goal for each of participants is to collect points as fast as possible to pass 100. Each participant can throw the die as many times as they want and add the points, but achieved points within a certain game fall away if a one is rolled. For example, if you have 15 points in a game and have stopped in time, these points can be taken further to round two. These points cannot be lost in a later round and thus become included in the summary.
I've managed to:
write the code that shows images of dice and sums up the current score (images = 1.png, 2.png etc).
Resets the current score to 0 when the player rolls a one.
What I need help with is how to write the code that activates the button "done for now" and takes that value and pushes it into an array(????) then clears the score for the next round -> then displaying the score on the site while the other rounds keep on going. It should also sum up the score and throws from each round (first to 100).
Here is my code:
var points = 0;
var start, dice, print;
window.onload = run;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button>Done for now</button>
<div id="dice" class="dice"></div>
<h2 id="print"></h2>
<p id="print2"></p>
</div>
Basically you just have to add another click event listener to the 'Done for now' button whose callback function
pushes the current points to an array
resets the points to 0
updates the text elements on screen
Something like:
var points = 0;
var pointsArray = new Array();
var start, dice, print;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
done = $("done");
done.onclick = stopRound;
}
function stopRound() {
pointsArray.push(points);
points = 0;
$("print").innerHTML = points;
$("print3").innerHTML = pointsArray;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
run();
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button id="done">Done for now</button>
<div id="dice" class="dice"></div>
<p id="print3" style="float:right;"></p>
<h2 id="print"></h2>
<p id="print2"></p>
</div>

How can I display a Javascript function in a DIV Tag? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've created a FizzBuzz Program and now I just want to display that in a div when a button is clicked.
I've created a function which will show the div when the button is clicked. (fizzbuzzButton)
All I want it to do is display the result of the FizzBuzz Function in the Div.
Is there not a simple way to display the result of a function in a div?
Or despite that, show the result of a function after clicking a button?
I can get it to display when clicking a button using:
<button onclick="FizzBuzz()">Show FizzBuzz</button>
But when using document.write, this removes the rest of the HTML.
<!DocType html>
<html>
<body>
<script type= text/javascript>
var max = 100;
var fizz = "Fizz!";
var buzz = "Buzz!";
var fizzbuzz = "FizzBuzz!";
function FizzBuzz() {
for(var x = (1); x <= max; x++) {
if(x % 5 == 0 && x % 3 == 0){
document.write(fizzbuzz, "</br>" )
}
else if(x % 3 == 0) {
document.write(fizz, "</br>")
}
else if(x % 5 == 0) {
document.write(buzz, "</br>")
}
else {
document.write(x, "</br>")
}
}
}
function fizzbuzzButton() {
document.getElementById('resultDIV').innerHTML = FizzBuzz;
}
</script>
<h1>FIZZ BUZZ!</h1>
<button onclick="fizzbuzzButton()">Show FizzBuzz</button>
<div id="resultDIV">
</div>
</body>
</html>
Two significant problems:
Avoid document.write in general; it's only useful during initial page render (which in modern workflows is basically never). Instead have your function concatenate its output into a string, and return that string; put content into the DOM using e.g. innerHTML instead of document.write.
document.getElementById('resultDIV').innerHTML = FizzBuzz will fill the div with the function itself. You want to call the function and get its output, so use FizzBuzz() instead.
var max = 100;
var fizz = "Fizz!";
var buzz = "Buzz!";
var fizzbuzz = "FizzBuzz!";
function FizzBuzz() {
var output = "";
for (var x = (1); x <= max; x++) {
if (x % 5 == 0 && x % 3 == 0) {
output += fizzbuzz + "<br>"
} else if (x % 3 == 0) {
output += fizz + "<br>"
} else if (x % 5 == 0) {
output += buzz + "<br>"
} else {
output += x + "<br>"
}
}
return output;
}
function fizzbuzzButton() {
document.getElementById('resultDIV').innerHTML = FizzBuzz();
}
<h1>FIZZ BUZZ!</h1>
<button onclick="fizzbuzzButton()">Show FizzBuzz</button>
<div id="resultDIV">
</div>
(A less significant issue also changed above: </br> is harmless but incorrect, use <br> instead.)
i found issue in your code and fixed for you, created one jsfiddle, have a look
This will help you
https://jsfiddle.net/wnx50hfr/
<!DocType html>
<html>
<body>
<script type= text/javascript>
var max = 100;
var fizz = "Fizz!";
var buzz = "Buzz!";
var fizzbuzz = "FizzBuzz!";
function FizzBuzz() {
for(var x = (1); x <= max; x++) {
if(x % 5 == 0 && x % 3 == 0){
document.write(fizzbuzz, "</br>" )
}
else if(x % 3 == 0) {
document.write(fizz, "</br>")
}
else if(x % 5 == 0) {
document.write(buzz, "</br>")
}
else {
document.write(x, "</br>")
}
}
}
function fizzbuzzButton() {
document.getElementById('resultDIV').innerHTML = FizzBuzz;
}
</script>
<h1>FIZZ BUZZ!</h1>
<button onClick="fizzbuzzButton()">Show FizzBuzz</button>
<div id="resultDIV">
</div>
</body>
</html>
Only function fuzzbuzzButton is declared, and there is no fizzbuzzButton function.
If you want to run the function, you should use FizzBuzz() and not FizzBuzz.
Replace the function with
function fizzbuzzButton() {
document.getElementById('resultDIV').innerHTML = FizzBuzz;
}
If you want to write to the div with id 'resultDIV' through your approach, you should rather get the result as a string, and assign it to document.getElementById('resultDIV').innerHTML.

Categories

Resources