How can I count up by a random integer / variable (onclick)? - javascript

I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that?
Here's what I have:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dot Race</title>
<link href="dotrace.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
function TakeAStep() {
var x, y, redcount, bluecount, distance;
x = Math.floor(Math.random() * 3) + 1;
y = Math.floor(Math.random() * 3) + 1;
redcount = document.getElementById("reddotspan").innerHTML++;
bluecount = document.getElementById("bluedotspan").innerHTML++;
distance = parseFloat(document.getElementById("DistanceBox").value);
if (redcount >= distance && bluecount >= distance) {
alert("They tied!");
} else if (redcount >= distance) {
alert("Red wins!");
} else if (bluecount >= distance) {
alert("Blue wins!");
}
}
</script>
</head>
<body>
<h2>Dot Race</h2>
<p>
Race distance: <input type="text" id="DistanceBox" placeholder="0" />
<br>
<span class="red">Red dot location:</span> <span id="reddotspan">0</span>
<br>
<span class="blue">Blue dot location:</span>
<span id="bluedotspan">0</span>
<hr>
<input type="button" value="Take a step!" onclick="TakeAStep();" />
</p>
<div id="OutputDiv"></div>
</body>
</html>

You are incrementing the value of redcount and bluecount but that has nothing to do with x and y.
I added these lines after x= and y=. Seems to fix the root cause.
document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x;
redcount = document.getElementById("reddotspan").innerHTML;
document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y;
bluecount = document.getElementById("bluedotspan").innerHTML;
distance = parseFloat(document.getElementById("DistanceBox").value);

<!doctype html>
<html lang="en">
<head>
<title>Dot Race</title>
<link href="dotrace.css" type="text/css" rel="stylesheet"></link>
<script type="text/javascript">
function TakeAStep()
{
var x, y, redcount, bluecount, distance;
x = Math.floor(Math.random() * 3) + 1 ;
y = Math.floor(Math.random() * 3) + 1;
current_red = +document.getElementById('reddotspan').innerText;
current_blue = +document.getElementById('bluedotspan').innerText;
redcount = current_red + x;
bluecount = current_blue + y;
document.getElementById('reddotspan').innerText = redcount;
document.getElementById('bluedotspan').innerText = bluecount;
distance = parseFloat(document.getElementById('DistanceBox').value);
if (redcount >= distance && bluecount >= distance) {
alert('They tied!');
} else if (redcount >= distance) {
alert('Red wins!');
} else if (bluecount >= distance) {
alert('Blue wins!')
}
}
</script>
</head>
<body>
<h2>Dot Race</h2>
<p>
Race distance:
<input type="text"
id="DistanceBox"
placeholder="0">
<br>
<span class="red">Red dot location:</span> <span
id="reddotspan">0</span>
<br>
<span class="blue">Blue dot location:</span>
<span id="bluedotspan">0</span>
<hr>
<input type="button"
value="Take a step!"
onclick="TakeAStep();">
</p>
<div id="OutputDiv"></div>
</body>
</html>

You were almost there. When you were using the ++ operator, you were modifying the current state of the innerHTML to just add one. Instead, you need to set it equal to the new value.
You should also use Number.parseInt so it parses it to a number explicitly. Otherwise, if you do "0" + 1, it will result in "01".
<html lang="en">
<head>
<title>Dot Race</title>
<link href="dotrace.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
function TakeAStep() {
var x, y, newRedNumber, newBlueNumber, distance;
x = Math.ceil(Math.random() * 3);
y = Math.ceil(Math.random() * 3);
newRedNumber = Number.parseInt(document.getElementById('reddotspan').innerHTML) + x;
newBlueNumber = Number.parseInt(document.getElementById('bluedotspan').innerHTML) + y;
document.getElementById('reddotspan').innerHTML = newRedNumber;
document.getElementById('bluedotspan').innerHTML = newBlueNumber;
distance = parseFloat(document.getElementById('DistanceBox').value);
var outputText = "";
if (newRedNumber >= distance && newBlueNumber >= distance) {
outputText = 'They tied!';
} else if (newRedNumber >= distance) {
outputText = 'Red wins!';
} else if (newBlueNumber >= distance) {
outputText = 'Blue wins!';
}
document.getElementById('OutputDiv').innerHTML = outputText;
}
</script>
</head>
<body>
<h2>Dot Race</h2>
<p>
Race distance:
<input type="text" id="DistanceBox" placeholder="0">
<br>
<span class="red">Red dot location:</span> <span id="reddotspan">0</span>
<br>
<span class="blue">Blue dot location:</span>
<span id="bluedotspan">0</span>
<hr>
<input type="button" value="Take a step!" onclick="TakeAStep();" />
<div id="OutputDiv"></div>
</body>
</html>

You can use:
Math.round(Math.random()*3);
Math.random() returns a random number between 0 and 1.
Multiply by 3 to get 3 as highest number.
Round.

Related

Number Guesser game displays “-1 guesses left” just before the game refreshes and restarts

The game works fine, but for some reason it displays “-1 guesses left” when the game is over right after I click on the “play again” button and the game refreshes. The user only gets three guesses and the game should stop notifying guesses left after the remaining guesses are 0.
// guess btn handler
guessBtn.addEventListener("click", function() {
// guess value
let guess = parseInt(guessInput.value);
// guess validator
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, "red");
} else if (guess === winningNum) {
gameOver(true, `Winner! ${winningNum} is correct`);
playAgain();
} else {
guessesLeft -= 1;
if (guessesLeft === 0) {
gameOver(false, `Game Over! ${winningNum} was the number`);
playAgain();
} else
<!-- begin snippet: js hide: false console: true babel: false -->
<!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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
{
setMessage(${guessesLeft} guesses left, "red");
}
}
});
// play again
function playAgain() {
guessBtn.value = "Play Again";
guessBtn.className += "play-again";
}
// game over
function gameOver(won, msgOutput) {
let color;
won === true ? color = "green" : color = "red";
guessInput.disabled = true;
guessInput.style.borderColor = color;
setMessage(msgOutput, color);
}
// generate random winning number
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// message box
function setMessage(msgOutput, color) {
msg.style.color = color;
msg.textContent = msgOutput;
}
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Have a look at the below code. Here I've added some more code on play again button
min=10;
max = 20;
winningNum = 13;
guessesLeft = 3;
// guess btn handler
const guessBtn = document.getElementById("guess-btn");
guessInput = document.getElementById("guess-input");
const msg = document.getElementsByClassName("message")[0];
guessBtn.addEventListener("click", function(e) {
if(e.target.value === "submit"){
// guess value
let guess = parseInt(guessInput.value);
// guess validator
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, "red");
} else if (guess === winningNum) {
gameOver(true, `Winner! ${winningNum} is correct`);
playAgain();
} else {
guessesLeft -= 1;
if (guessesLeft === 0) {
gameOver(false, `Game Over! ${winningNum} was the number`);
playAgain();
} else {
setMessage(`${guessesLeft} guesses left`, "red");
}
}
}else{
guessBtn.value = "submit";
guessInput.value="";
guessInput.disabled = false;
guessInput.style.borderColor = "";
setMessage("");
}
});
// play again
function playAgain() {
guessBtn.value = "Play Again";
guessBtn.className += "play-again";
guessesLeft = 3;
}
// game over
function gameOver(won, msgOutput) {
let color;
won === true ? color = "green" : color = "red";
guessInput.disabled = true;
guessInput.style.borderColor = color;
setMessage(msgOutput, color);
}
// generate random winning number
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// message box
function setMessage(msgOutput, color) {
msg.style.color = color;
msg.textContent = msgOutput;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>React Boilerplate</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter guess">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
</body>
</html>

Simple guessing game

I am trying to make a simple guessing number game. I cannot get the function to operate correctly, or display my messages to the user. Am I not using the innerHTML correctly? I also want the game to reload when the number is guessed correctly, I am not sure if it works because the game will not operate.
var number = 0;
var output = document.getElementById("output").innerHTML;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
function checkGuess() {
"use strict";
var guess = document.getElementById("guess").value;
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number); {
output = "The number I am thinking of is higher than" + guess;
} else if (guess > number); {
output = "The number I am thinking of is lower than" + guess;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
<link rel="stylesheet" href="css/Lab6.css" />
<script type="text/javascript" src="script/Lab6.js"></script>
</head>
<body onload="pickInteger()">
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="button" name="mybutton" value=" Guess " onclick="checkGuess()">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
you had a semicolon if (guess < number); and else if (guess > number); which is wrong just remove it and it will start working, see below your code
var number = 0;
var output = document.getElementById("output").innerHTML;
var consolecounter = 0;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
$(document).ready(function() {
pickInteger();
$("form[name='AForm']").on('submit', function(e) {
"use strict";
e.preventDefault();
var guess = parseInt(document.getElementById("guess").value);
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number) {
console.log("The number I am thinking of is higher than " + guess);
consolecounter++;
} else if (guess > number) {
console.log("The number I am thinking of is lower than " + guess);
consolecounter++;
}
clearConsole(consolecounter);
})
})
function clearConsole(consolecounter) {
(consolecounter == 3) && (setTimeout(function() {
console.clear();
consolecounter = 0;
}, 2000));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="submit" name="mybutton" value=" Guess ">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>

How do I use a double click event in Javascript simplified in a JS external file

I can't seem to figure out how to clear the textbox rate in my JS code from an external file and would love some help to figure out how to do it.
Can someone help me with the code and the why and how it works so that I can learn it and understand it so that I can code it effectively and efficiently?
I have included all of the original code down below.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="future_value.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<script src="future_value.js"></script>
</head>
<body>
<section>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
JavaScript
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
if (isNaN(investment) || investment < 100 || investment > 100000) {
alert("Investment must be an integer from 100 - 100,000.");
}
else if(isNaN(annualRate) || annualRate < .1 || annualRate > 12) {
alert("Annual rate must be a value from .1 - 12.");
}
else if(isNaN(years) || years < 1 || years > 50) {
alert("Years must be an integer from 1 - 50.");
}
// if all entries are valid, calulate future value
else {
futureValue = investment;
for ( i = 1; i <= years; i++ ) {
futureValue += futureValue * annualRate / 100;
}
$("future_value").value = futureValue.toFixed();
}
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("investment").focus();
}
rate = document.getElementById("rate");
rate.dblclick = "";
To add an "ondblclick" attribute to your "rate" element in JS, it world look like this:
$('rate').ondblclick = clearRate();
And then add that "clearRate()" function:
function clearRate() {
$('rate').value = ''
}
This means that when the "rate" element is double-clicked, it will trigger the function "clearRate()", which sets the value of "rate" to an empty string.

HTML does not run function on click

I'm trying to use the distance formula to find the difference between two castle on a game. The game stores the castle coordinates in the following format
"l+k://coordinates?16321,16520&146" the coordinates of this castle would be 16321 & 16520. I have written a function to extract this information from two castle links and then use the distance formula to return the answer. However for some reason when this function is called in the website it does not return the expected result. Does anyone know why this might be happening. Please find my code below. I have also attached a JSFiddle.
https://jsfiddle.net/ajdxetod/
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Lords & Knights - Distance Calculator</title>
<script type="text/javascript" src="distanceScript.js"></script>
</head>
<body>
<h1 class="heading">Distance Calculator</h1>
<div>
<fieldset>
<legend>Castle Link One</legend>
<input type="text" id="castle_one">
</fieldset>
</div>
<div>
<fieldset>
<legend>Castle Link Two</legend>
<input type="text" id="castle_two">
</fieldset>
</div>
<div class="map_of_areadiv">
<fieldset>
<legend>Is Map Of Area Researched</legend>
<input type="checkbox" id="moa_checkbox" checked="true"><label for="moa_checkbox">Is "Map Of Area Researched in the Libary?</label>
</fieldset>
</div>
<div class="calculate_button">
<button id="calculate" onclick="distanceCastles()">Calculate Distance</button>
</div>
<div class="distance_output">
<fieldset id="castle_distance">
<legend>Distance (in fields)</legend>
<input type="text" id="output" placeholder="Click the Calculate Distance Button">
</fieldset>
<textarea id="troop_times"></textarea>
</div>
</body>
distanceScript.js
var castleone;
var castletwo;
var x1;
var x2;
var y1;
var y2;
var distance = 0;
function distanceCastles() {
castleone = document.getElementById("castle_one") ;
castletwo = document.getElementById("castle_two") ;
if (typeof castleone === "string" && castleone.length === 33) {
x1 = castleone.substring(18, 23);
y1 = castleone.substring(24, 29);
x2 = castletwo.substring(18, 23);
y2 = castletwo.substring(24, 29);
distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
document.getElementById("output").innerHTML = distance;
}
else if (typeof castleone !== "string" || castleone.length !== 33) {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
else {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
}
You are declaring a variable
var distance = 0;
And then you create a function with the same name
function distance () {
// code...
}
and you wonder why you get an error. Rename either.
Some issues
As what first answer stated the distance was declared as a variable first
You are comparing an html object with a string..You don't need to do this (See how I attempted it)
You are trying to insert out message without using using the property innerHTML OR textContent..
You can get the value of each input distance using .value property of input box
See snippet below
<!DOCTYPE html>
<html>
<head>
<title>Lords & Knights - Distance Calculator</title>
<script type="text/javascript" src="distanceScript.js"></script>
</head>
<body>
<script>
var castleone;
var castletwo;
var x1;
var x2;
var y1;
var y2;
function distance() {
castleone = document.getElementById("castle_one");
castletwo = document.getElementById("castle_two");
if (castleone.value.length === 33) {
x1 = castleone.value.substring(18, 23);
y1 = castleone.value.substring(24, 29);
x2 = castletwo.value.substring(18, 23);
y2 = castletwo.value.substring(24, 29);
distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
console.log(distance);
document.getElementById("output").value = distance;
} else if (castleone.value.length !== 33) {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
} else {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
}
</script>
<h1 class="heading">Distance Calculator</h1>
<div>
<fieldset>
<legend>Castle Link One</legend>
<input type="text" id="castle_one">
</fieldset>
</div>
<div>
<fieldset>
<legend>Castle Link Two</legend>
<input type="text" id="castle_two">
</fieldset>
</div>
<div class="map_of_areadiv">
<fieldset>
<legend>Is Map Of Area Researched</legend>
<input type="checkbox" id="moa_checkbox" checked="true">
<label for="moa_checkbox">Is "Map Of Area Researched in the Libary?</label>
</fieldset>
</div>
<div class="calculate_button">
<button id="calculate" onclick="distance()">Calculate Distance</button>
</div>
<div class="distance_output">
<fieldset id="castle_distance">
<legend>Distance (in fields)</legend>
<input type="text" id="output" placehodler="Click the Calculate Distance Button">
</fieldset>
<textarea id="troop_times"></textarea>
</div>
</body>
</html>

How do I initialize JavaScript using the form?

I want to initialize my var from HTML to my JavaScript file but my form is not working.if i initialize by myself the function is working but when initialize from HTML not working.
i test any thing comes to my mind but it is not working.
function DDA() {
var x1, x2, y1, y2 ,m;
x1=document.getElementById('x1').value;
x2=document.getElementById('x2').value;
y1=document.getElementById('y1').value;
y2=document.getElementById('y2').value;
if(x1==null||x1==""||x2==null||x2==""||y1==null||y1==""||y2==null||y2==""){
console.log('enter number');
return false;
}
m = (y2 - y1) / (x2 - x1);
console.log(`(${x1},${y1})`);
if (m > 1) {
for (var i = y1 + 1; i <= y2; i++) {
x1 = (x1 + (1 / m));
console.log(`(${Math.round(x1)},${i})`);
}
} else {
for (var i = x1 + 1; i <= x2; i++) {
y1 = (y1 + m);
console.log(`(${i},${Math.round(y1)})`);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name="myform" onsubmit=" return (DDA())" action="index.html" method="POST">
<input type="text" id="x1" placeholder="x1"><br>
<input type="text" id="x2" placeholder="x2"><br>
<input type="text" id="y1" placeholder="y1"><br>
<input type="text" id="y2" placeholder="y1"><br>
<input type="submit" id="submitform" >
</form>
<script src="tamrin.js">
</script>
</body>
</html>
I think your code run perfectly If you fill all the text box it prints in the console if any filed not filled it show the message as "enter the number" because of your validation.

Categories

Resources