Try to create basic math game - javascript

I'm doing a math game. I have this HTML/JavaScript code. It generates a random number but when I input the correct answer, it still displays 'wrong'. I'm not sure what went wrong.
Here is HTML code:
<table width="400" border="1" align="center">
<tr>
<td><div id="number1">1</div></td>
<td><div>+</div></td>
<td><div id="number2">2</div></td>
<td><div>=</div></td>
<td><input type="text"></input></td>
<td><input type="button" value="Check"></input></td>
</tr>
</table>
Here is my JavaScript code:
//random number appear when start game
var number1;
var number2;
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById("number1").innerHTML=number1;
document.getElementById("number2").innerHTML=number2;
//Answer
var answer = number1 + number2;
//add click handler with check answer
var checkAnswer = document.querySelector('input[type=text]');
var value = checkAnswer.value;
var btn = document.querySelector('input[type=button][value=Check]');
btn.onclick = function()
{
if (value == answer)
{
alert('You are correct');
}
else{
alert('You are incorrect, the answer was ' + answer);
}
document.querySelector('input[type=text]').value = "";
document.getElementById('number1').innerHTML = "";
document.getElementById('number2').innerHTML = "";
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById('number1').innerHTML = number1;
document.getElementById('number2').innerHTML = number2;
answer = number1 + number2
};

Move following lines in .onclick method.
var checkAnswer = document.querySelector('input[type=text]'); //needn't be moved in method
var value = checkAnswer.value;
You can verify the result from JSFiddle.
The problem was the variable value is initialize with empty string when you load the page, as when page is loaded the value is empty.

Compare answer to value in checkAnswer:
if (checkAnswer.value == answer) {
//correct
}else{
//incorrect
}

You don't update the value.
In the button click event update the value. JSFiddle.
btn.onclick = function()
{
value = checkAnswer.value;
...

Related

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

Sharing random variables between functions

I'm trying to code a game and part of it has a combat system. I want the player to click a button as many times as they want to find an opponent, then to click the attack button when they find one they like and a timed event happens to slowly reveal the result.
The problems I'm coming against are:
- If the VAR are outside the functions, then you can only infiltrate once, but if it's inside the first function then the other ones can't use those values for the battle.
- The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Thank you very much for looking and I appreciate the help!
Javascript:
var titles = ["Peasant", "Knight"];
var first = ["Ada", "Adro", "Ama"];
var last = ["nija", "har", "nake"];
var random_name1 = titles[Math.floor(Math.random() * titles.length)] + ' ' + first[Math.floor(Math.random() * first.length)] + last[Math.floor(Math.random() * last.length)];
var random_acres1 = (max_acres * (Math.floor(Math.random() * (140 - 75)) + 75) / 100).toFixed(0);
var random_troops1 = (random_acres1 * (Math.floor(Math.random() * (1500 - 600)) + 600) / 100).toFixed(0);
var random_off1 = (random_troops1 * (Math.floor(Math.random() * (1200 - 400)) + 400) / 100).toFixed(0);
var combat_victory_acres1 = (random_acres1 * (((Math.random() * (35 - 11)) + 11) / 100)).toFixed(0);
var combat_defeat_acres1 = (random_acres1 * (Math.floor(Math.random() * (20 - 11)) + 11) / 100).toFixed(0);
var text_victory = 'You have been awarded with ';
var text_defeat = 'You have lost control of ';
var text_acres = ' acres.';
function infiltrate(){
var x = document.getElementById("Combat_table");
if (x.style.display === "none") {
x.style.display = "block";
}
document.getElementById('combat_army_strength').innerHTML = army_strength;
document.getElementById('combat_max_acres').innerHTML = max_acres;
document.getElementById('random_name1').innerHTML = random_name1;
document.getElementById('random_acres1').innerHTML = random_acres1;
document.getElementById('random_troops1').innerHTML = random_troops1;
document.getElementById('random_off1').innerHTML = random_off1;
};
function attack_random1(){
document.getElementById("attack_button1").style.display="none";
document.getElementById("infiltration").style.display="none";
var y = document.getElementById("Combat_Results");
if (y.style.display === "none") {
y.style.display = "block";
}
setTimeout(Combat_Text4, 5000)
var final_outcome1 = army_strength - random_off1;
if (final_outcome1 >= 0) {
setTimeout(Combat_Text_Victory1, 6000);
} else {
setTimeout(Combat_Text_Defeat1, 6000);
}
};
function Combat_Text4() {
document.getElementById("Combat_Results4").innerHTML = "The battle is over, a scout is dispatched to you with the results.";
}
function Combat_Text_Victory1() {
max_acres = max_acres + combat_victory_acres1;
var text_victory_1 = text_victory + combat_victory_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You achieved <b>Victory!</b>";
document.getElementById("Combat_Results6").innerHTML = text_victory_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
function Combat_Text_Defeat1() {
max_acres = max_acres - combat_defeat_acres1;
var text_defeat_1 = text_defeat + combat_defeat_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You have been <b>Defeated!</b>";
document.getElementById("Combat_Results6").innerHTML = text_defeat_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
HTML:
<div id="Combat" class="tabcontent">
Total Land: <span id="combat_max_acres">10</span><br>
Total Offense: <span id="combat_army_strength">0</span><p>
<button id="infiltration" onclick="infiltrate()">Infiltrate Kingdoms</button>
<div id="Combat_table" style="display: none">
<center><table>
<tr valign="center">
<th>Kingdom Name</th>
<th>Acres</th>
<th>Troop <br>Numbers</th>
<th>Total <br>Offense</th>
<th></th>
</tr>
<tr id="combat_row1">
<td><span id="random_name1"></span></td>
<td><span id="random_acres1"></span></td>
<td><span id="random_troops1"></span></td>
<td><span id="random_off1"></span></td>
<td><button onclick="attack_random1()" id="attack_button1">Attack!</button></td>
</tr>
</table>
</div>
<br>
<div id="Combat_Results" style="display: none">
<center><table><tr>
<td><center><span id="Combat_Results4"></span></td>
</tr><tr>
<td><center><span id="Combat_Results5"></span></td>
</tr><tr>
<td><center><span id="Combat_Results6"></span></td>
</tr>
</table>
</div>
The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Use Math.round instead of Number#toFixed, because for addition numerical values, you need both operands as number, not a string.
Use toFixed only for displaying a number.
For the other parts, I suggest to use an object with arrays for same items, like
{
name: [],
acres: [],
troops: [],
off: [],
victory_acres: [],
combat_defeat_acres: [],
// etc.
}

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

Counter wont increment by decimals

I'm taking the plunge into javascript and have thus far have been relatively successful in what I've been trying to do. Although I realize that most of what I'm doing is probably being done incorrectly, or inefficiently.
For my first "project" I was trying to make a basic game. Click on the pickaxe, and it adds +1 to your total rocks. After you hit 5 rocks you can buy a shovel which will start generating rocks for you at a rate of one per second. I've currently had to set this to 1 per second as nothing under 1 seems to work.
My code (It's still somewhat messy as I've been tweaking it a lot):
JSBIN DEMO
HTML:
Total Rocks: <input id="txtNumber" type="text" value="0" onfocus="this.blur()" style=" border:none; text-align:center; background-color:transparent;" />
<br>
<img style="border:0;" src="http://img2.wikia.nocookie.net/__cb20130308043142/minecraftpocketedition/images/6/6d/Pickaxe_1.jpeg" onclick="javascript:add()">
<br>
Rocks per second: <input id="perSec" type="text" value="0" onfocus="this.blur()" style="width:30px; border:none; text-align:center; background-color:transparent;" />
<br>
Shovel(<input id="shovelCount" type="text" value="0" onfocus="this.blur()" style="width:20px; border:none; text-align:center; background-color:transparent;" />): 5 rocks
<input id="shovelBuy" type="button" value="Buy" onclick="javascript:shovel()"/>
</body>
Javascript:
var totalRocks = 0;
var rocksPerSec = 0;
function increment() {
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseInt(txtNumber.value, 10) + rocksPerSec;
txtNumber.value = newNumber;
}
setInterval(function(){increment();}, 1000);
function add()
{
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseInt(txtNumber.value, 10) + 1;
txtNumber.value = newNumber;
}
function shovel()
{
var txtNumber = document.getElementById("txtNumber");
var value = parseInt(txtNumber.value, 10);
if(value >= 5){
var newNumber = parseInt(txtNumber.value, 10) - 5;
txtNumber.value = newNumber;
var shovelCount = document.getElementById("shovelCount");
var newCount = parseInt(shovelCount.value, 10) + 1;
shovelCount.value = newCount;
rocksPerSec = rocksPerSec +1;
return false;
}
}
My Question: Why can't I increment the counter (rockPerSec) by a decimal value?
I made this fiddle..You basically had to replace parseInt() with parseFloat() and if you're asking "Why?", the answer is because if you want to increment the numeber of rocks by 0.2 for example, parseInt(0.2) is always 0. So you would always add 0.2 to 0 and parse it back to 0..Hope it helps..
var totalRocks = 0;
var rocksPerSec = 0;
function increment() {
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseFloat(txtNumber.value, 10) + rocksPerSec;
txtNumber.value = newNumber;
}
setInterval(function(){increment();}, 1000);
function add()
{
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseFloat(txtNumber.value, 10) + 1;
txtNumber.value = newNumber;
}
function shovel()
{
var txtNumber = document.getElementById("txtNumber");
var value = parseFloat(txtNumber.value, 10);
if(value >= 5){
var newNumber = parseInt(txtNumber.value, 10) - 5;
txtNumber.value = newNumber;
var shovelCount = document.getElementById("shovelCount");
var newCount = parseFloat(shovelCount.value, 10) + 1;
shovelCount.value = newCount;
rocksPerSec = rocksPerSec + 0.2;
return false;
}
}
As a help for your first project, i thought i show a suggestion of structuring code
jsfiddle: http://jsfiddle.net/j8CJS/
where you can start the code by using
var miner = new Miner();
miner.start();
it also allows resetting and stopping (or rather pauze) your current game. Your html code changes when relative properties are changed, and added some functions which i would normally borrow from jquery :)

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

Categories

Resources