How to add an animation gif to a javascript program - javascript

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.

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

2 players Javascript hangman game problem with prompt

I am currently making a hangman game, 1st player need to enter a word the player 2 need to guess via a prompt. When i enter the word via the prompt it's in the console log but it's not showing in the page. It is suppose to be show in underslash like: '_ _ _ _ _' depending on the length of the word. How do I get to show the word in underslash form?
Here is what I have so far.
Thanks!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hangman</title>
</head>
<body>
<div class="container">
<h1>Hangman</h1>
<div>Wrong Guesses: <span id='mistakes'>0</span> of <span id='maxWrong'></span></div>
<div>
<img id='hangmanPic' src="./images/0.jpg" alt="">
<p>Guess the word:</p>
<p id="wordSpotlight">The word to be guessed goes here</p>
<div id="keyboard"></div>
<button class="btn btn-info" onClick="reset()">Reset</button>
</div>
</div>
</body>
</html>
Script:
<script>
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
function randomWord() {
var secretWord = prompt("Player 1, enter a word to guess", "");
secretWord = secretWord.toUpperCase();
console.log("Word to guess: " + secretWord);
var secretWordArray = Array.from(secretWord);
console.log("Word to guess (array): " + secretWordArray);
var wordArray = [];
for (var i = 0; i < secretWordArray.length; i++) {
motArray[i] = " _ ";
}
return wordArray;
}
function generateButtons() {
let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
`<button class="btn btn-lg btn-primary m-2" id='` + letter + `'onClick="chooseLetter('` + letter + `')">` + letter + `</button>`).join('');
document.getElementById('keyboard').innerHTML = buttonsHTML;
}
function chooseLetter(chosenLetter) {
guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;
document.getElementById(chosenLetter).setAttribute('disabled', true);
if (answer.indexOf(chosenLetter) >= 0) {
guessedWord();
checkIfGameWon();
} else if (answer.indexOf(chosenLetter) === -1) {
mistakes++;
updateMistakes();
checkIfGameLost();
updateHangmanPicture();
}
}
function updateHangmanPicture() {
document.getElementById('hangmanPic').src = './images/' + mistakes + '.jpg';
}
function checkIfGameWon() {
if (wordStatus === answer) {
document.getElementById('keyboard').innerHTML = 'You Won!!!';
}
}
function checkIfGameLost() {
if (mistakes === maxWrong) {
document.getElementById('wordSpotlight').innerHTML = 'The answer was: ' + answer;
document.getElementById('keyboard').innerHTML = 'You Lost!!!';
}
}
function guessedWord() {
wordStatus = answer.split('').map(letter => (guessed.indexOf(letter) >= 0 ? letter : " _ ")).join('');
document.getElementById('wordSpotlight').innerHTML = wordStatus;
}
function updateMistakes() {
document.getElementById('mistakes').innerHTML = mistakes;
}
function reset() {
mistakes = 0;
guessed = [];
document.getElementById('hangmanPic').src = './images/0.jpg';
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
document.getElementById('maxWrong').innerHTML = maxWrong;
randomWord();
generateButtons();
guessedWord();
</script>
Using a for loop, iterate over the secret word character by character, and check if it's in the guessed array. If it is, output the character followed by a space. If not, output an underscore followed by a space.
If there are no guessed letters this will output a row of underscores.
Watch for issues with upper and lower case.
let output = '';
let secret = "secret";
let guessed = ['e', 't'];
for (let char of secret) {
output += ((guessed.indexOf(char) === -1)?'_':char)+" ";
}
output = output.trim();
console.log(output); // _ e _ _ e t

How to I get an image to show a certain amount of times for Val in HTML

This question in HTML asks for the user to enter a number 1-5 and then it will show the amount of numbers entered as a picture of a dice with question marks on them. No matter what number I put in I will always get 6 dice to show with question marks. How do I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
</style>
</head>
<body>
<h1>Click the button to see the roll of a die randomly selected</h1>
<script>
Val = window.prompt("Enter the number of dice to play with (1-5)");
<!--if user enters a number <= 1 val ==1-->
if(Val == 1 || Val <= 1){
Val = 1;
}
else if(Val == 2){
Val = 2;
}
else if(Val == 3){
Val = 3;
}
else if(Val == 4){
Val = 4;
}
<!--if user enters anything thats not 1-4 val = 5-->
else Val = 5;
function roll() {
var randomDie = Math.floor(Val*Math.random()) + 1;
var RandomNum = Math.floor(6*Math.random()) + 1;
document.getElementById('dieImg' + randomDie).setAttribute("src","dieImages/die" + RandomNum + ".jpg");
document.getElementById('dieImg' + randomDie).style.display="inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
</script>
<!--Show question mark die-->
<img id="dieImg1" src="dieImages/question-mark-dice.jpg">
<img id="dieImg2" src="dieImages/question-mark-dice.jpg">
<img id="dieImg3" src="dieImages/question-mark-dice.jpg">
<img id="dieImg4" src="dieImages/question-mark-dice.jpg">
<img id="dieImg5" src="dieImages/question-mark-dice.jpg">
<hr>
<button type="button" onclick="roll()">Click to Roll</button>
<p id="display">--</p>
</body>
</html>
This is what the application shows when I put in 3,
This is what I want the output to be,
First of all you do not need to re-assign every value
if(Val == 1 || Val <= 1){
Val = 1;
}
else if(Val == 2){
Val = 2;
}
else if(Val == 3){
Val = 3;
}
else if(Val == 4){
Val = 4;
}
this works same as above
//if user enters a number <= 1 val ==1
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
Second,
it's showing the 5 images everytime because you have mentioned that in the HTML, you need to create the img element dynamically using createElement using a loop.
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
let dices = document.getElementById("dices");
dices.appendChild(img);
I re-wrote your example, which is working as you are expecting.
Val = window.prompt("Enter the number of dice to play with (1-5)");
//if user enters a number <= 1 val ==1
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
for (i = 1; i <= Val; i++) {
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
let dices = document.getElementById("dices");
dices.appendChild(img);
}
function roll() {
var randomDie = Math.floor(Val * Math.random()) + 1;
var RandomNum = Math.floor(6 * Math.random()) + 1;
var diceElement = document.getElementById('dieImg' + randomDie);
diceElement.setAttribute("src", "dieImages/die" + RandomNum + ".jpg");
diceElement.style.display = "inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
</style>
</head>
<body>
<h1>Click the button to see the roll of a die randomly selected</h1>
<!--Show question mark die-->
<div id="dices">
</div>
<hr>
<button type="button" onclick="roll()">Click to Roll</button>
<p id="display">--</p>
</body>
</html>

Why is `pieceOfText` undefined?

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?
You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

Javascript Guessing Game

I'm brand new to javascript and html so I was hoping someone could peek at my code and tell me why certain syntax isn't working. In the code below I use document.getElementById to retreive the element I'd like to work with each time. I do declare them as local variables within gameTime() and use it throughout the function.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
function gameTime()
{
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
document.getElementById("guess").value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
document.getElementById("guess").value = "";
document.getElementById("status").value = "";
}
function quit()
{
document.getElementById("status").value += ("The correct number was " + randNum + "!\r")
}
Then I tried it by globally declaring the two elements and use it in every function which does not seem to work at all and I just don't understand why.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
function gameTime()
{
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
guess.value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
guess.value = "";
status.value = "";
}
function quit()
{
status.value += ("The correct number was " + randNum + "!\r")
}
And here's the html file that accompanies these js files guess.js is the first code block, guessAgain.js is the second code block.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" src="guessAgain.js"></script>
</head>
<body>
<label for = "guess"> Your Guess: </label>
<input type = "text" id = "guess" value = "" />
<input type = "button" onclick = "gameTime()" value = "Submit" />
<input type = "button" onclick = "reset()" value = "New Game" />
<input type = "button" onclick = "quit()" value = "Quit" />
<br>
<textarea id = "status" rows = "10" cols = "52"></textarea>
</body>
</html>
Thanks for any insight you can give me.
Issue 1:
You are calling the following before the body loads and hence, they return undefined.
var guess = document.getElementById("guess");
var status = document.getElementById("status");
You should do these only after the body loads on the onload() event.
Issue 2:
Also, when you assign the value itself to a variable, it isn't updated as the textbox is. var guess = document.getElementById("guess").value, then guess's value does not get updated if you change the textbox.
If you refer to var guess = document.getElementById("guess"), then, repeatedly calling
guess.value will return the latest value of the input field.
(Working Example)
The following is not wrong by unnecessarily complicated.
numGuesses++;
if(guess.value == "")
{
alert("You did not guess a number!")
numGuesses--;
}
...
Instead, you could increment numGuesses once it is deemed a valid guess, i.e. at the end.
You're setting guess to element.value
It should be
var guess = document.getElementById("guess");
Problem is that you're using guess as an element here:
guess.value = "";
You'll also need to modify places where you use guess as a string into guess.value.

Categories

Resources