Javascript based game - javascript

So i've been trying make a game where you bet money and if you win you get a profit, to win you must guess the correct outcome of the dice (6 sided) if you do you get your money + profit, i have been kind of successful but it dosen't pay you.
if you could help me fix this thanks. WEBSITE: http://csgodice.net16.net/dice.php
EDIT : Added the whole code!
EDIT: Things still broken with a new error: game is not defined.
CSGODice.net
<div id="header">
<div id="navbar">
<a class="nav1" href="/"><bold>HOME</bold></a>
<a class="nav2" href="dice.php"><bold>DICE</bold></a>
<a class="nav3" href="support.php">SUPPORT</a>
<a class="balance" href="#">Gems: 0</a>
<div id="steamLogon">
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
loginbutton("small"); //login button
} else {
include ('steamauth/userInfo.php'); //To access the $steamprofile array
//Protected content
logoutbutton(); //Logout Button
}
?>
</div>
</div>
<div id="dicelogo">
<a href="/">
<img src="img/logo.png" alt="logo" id="logo"/>
</a>
</div>
</div>
<div id="dicegame">
<div id="diceholder">
<h1>
<div id="diceroller">
<span id="value" class="lable_value">0</span>
<script>
var m = document.getElementsByClassName("balance");
var o = document.getElementsById("diceroller");
var w = document.getElementsByClassName("winchance");
var uc = document.getElementsByClassName("userchoice").value;
var b = document.getElementsById("bet").value;
var p = document.getElementsById("profit");
function game(event){
var wn = Math.floor((Math.random() * 6) + 1);
o.innerText = wn;
if(uc.value == wn) {
m.innerText = m.innerText + profit.innerText + b;
} else {
m.innerText = m.innerText - b;
}
}
</script>
</div>
</h1>
<h3>
<div class="winchance">1 - 6</div>
</h3>
</div>
<div id="inputholder">
<div id="input">
<div class="betamount">
<b>Gems to bet:</b>
</div>
<form class="input-money">
<b><input id="bet" oninput="edValueKeyPress()" type="number" name="bet" style="color: #404040;" class="form-control" min="0.10" step="any" max="1000.00" value="1.00"></b>
</form>
<div class="profitamount">
<b>Profit:</b>
</div>
<div id="profit">
</div>
<div id="userchoicetext"><b>Prediction:</b></div>
<form>
<input id="userchoice" oninput="edValueKeyPress()" type="number" name="choice" style="color: #404040" class="form-choice" min="1" step="any" max="6" value="1"/>
</form>
<button id="playgame" onclick="game()">Throw!</button>
</div>
</div>
</div>
<script>
var input = document.getElementsByClassName("form-control");
function edValueKeyPress(event)
{
var input = document.getElementById("bet").value;
var x = document.getElementById("profit"); // Find the elements
x.innerText= input * 0.68; // Change the content
var n = event.toFixed(2);
}
</script>
</div>
</div>
</div>

You have several errors here:
First a simple typo:
You define a variable here
var b = document.getElementsById("bet").value;
an try to access it as bet
m.innerText = m.innerText + profit.innerText + bet;
Next misstake:
getElementsById must be getElementById
next:
getElementsByClassName returns an array of Nodes, not only the first node it finds, so var uc = document.getElementsByClassName("userchoice").value; is an error.
Your debugged code:
var m = document.getElementsByClassName("balance")[0];
var o = document.getElementById("diceroller");
var w = document.getElementsByClassName("winchance")[0];
var uc = document.getElementsByClassName("userchoice")[0].value;
var bet = document.getElementById("bet").value;
var p = document.getElementById("profit");
function game(event){
var wn = Math.floor((Math.random() * 6) + 1);
o.innerText = wn;
if(uc.value == wn) {
m.innerText = m.innerText + profit.innerText + bet;
} else {
m.innerText = m.innerText - b;
}
}
I'd highly recommend to give those specific elements an ID and find them via that, rather than a classname.
All these errors are shown in the console - one after each other. Use that to debug your code yourself in the future!

Related

I want to use a slider component in html to get input from the user record it and use it to calculate a result

I am using Google App Script. I am trying to connect my HTML doc to my JS doc. So I can get the input from the user and use it to record the info to a Google Sheet and return an on-screen result. I have tried so many things and have come up short.
<div class="card carousel-item">
<div class="card-image">
<img src="https://i.postimg.cc/htb6hMf4/Solution-Builder-Tech-Savvy.png" />
<div class="row">
<div class="range-field">
<div id="min" class="col s1 rangeMinMaxText" style="display: inline">1</div>
<div class="col s10">
<input type="range" id="qt1" min="1" max="5" oninput="updateSliderValue()" />
</div>
<div id="max" class="col s1 rangeMinMaxText" style="display: inline">5</div>
</div>
</div>
<!--CLOSE ROW-->
</div>
<!--CLOSE CARD-->
</div>
document.getElementById("btn").addEventListener("click", doStuff);
function updateSliderValue() {
var sliderValue = document.getElementById("qt1").value;
// document.getElementById("sliderValue").innerHTML = sliderValue;
surveyData.questionOne = sliderValue;
console.log("Slider Value: " + sliderValue);
surveyData = list.map(function (r) {
Logger.log(r[0]);
});
}
function doStuff() {
var qt1 = document.getElementById("qt1");
var qt2 = document.getElementById("qt2");
var qt3 = document.getElementById("qt3");
var qt4 = document.getElementById("qt4");
var qt5 = document.getElementById("qt5");
var qt6 = document.getElementById("qt6");
var qt7 = document.getElementById("qt7");
var qt8 = document.getElementById("qt8");
var qt9 = document.getElementById("qt9");
var qt10 = document.getElementById("qt10");
var qt11 = document.getElementById("qt11");
var qt12 = document.getElementById("qt12");
surveyData.questionOne = qt1.value;
surveyData.questionTwo = qt2.value;
surveyData.questionThree = qt3.value;
surveyData.questionFour = qt4.value;
surveyData.questionFive = qt5.value;
surveyData.questionSix = qt6.value;
surveyData.questionSeven = qt7.value;
surveyData.questionEight = qt8.value;
surveyData.questionNine = qt9.value;
surveyData.questionTen = qt10.value;
surveyData.questionNine = qt11.value;
surveyData.questionTen = qt12.value;
Logger.log(surveyData);
google.script.run.withSuccessHandler(updateResult).userResults(surveyData);
google.script.run.userClicked(surveyData);
function updateResult(result) {
document.getElementById("result").value = result;
M.textareaAutoResize($("result"));
M.updateTextFields("result");
$("result").val("result");
Logger.log(surveyData);
}
}
I tried using all kinds of event listeners. I am able to log the input but having trouble getting it added to an array.
Try something like this.
<input type="range" min="0" max="10" value="0" oninput="rangeOnInput(this)">
<script>
function rangeOnInput(input) {
alert(input.value);
}
</script>

I want the enter key press to work as submit button and run the js function

I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.
HTML
<body>
<div class="container-fluid">
<div class="row inpdip">
<div class="col diptext">
<label for="dip">Dip</label>
</div>
<div class="col">
<input type="number" class="inpbox" id="dip">
</div>
</div>
<div class="row">
<div class="col">
</div>
<div class="col">
<button class="btn btn-dark" id="myBtn" type="submit" onclick="calvol()">Submit</button>
</div>
</div>
<div class="row outputvol">
<div class="col diptext ">
Volume :
</div>
<div class="col">
<span class="" id="result"></span>
</div>
</div>
</body>
JavaScript
function calvol() {
var R = 10.5;
var L = 62.5;
var inputh = document.getElementById('dip').value;
if (inputh>210){
document.getElementById('result').innerHTML = "Dip is over the tank limit." ;
} else if (inputh<= 0) {
document.getElementById('result').innerHTML = "Enter a higher number" ;
} else {
var h = inputh/10;
let TankVolume = L * (R * R * Math.acos((R - h)/ R) - (R - h) * Math.sqrt(2 * R * h - h * h));
let volume = Math.round(TankVolume);
console.log(volume)
document.getElementById('result').innerHTML = volume +" Liter" ;
}
}
var input = document.getElementById("dip");
input.onkeyup = function(e){
if(e.keyCode == 13){
calvol();
}
}
I want if user enter the value and press enter key instead of submit button. The function calvol() should run and give the result.

Is there a way to edit a javascript function to live update in a html form output?

I've written a working absence calculator using a HTML form and a javascript function. Unfortunately I need this to update to the output in real time and I cannot figure out how to do it without firing the function multiple times.
HTML
<form id="absence-form">
<div class="input">
<div id="title">Absence Calculator</div>
<div id="firstCell">
<div id="instruct">
Enter number of employees:
</div>
<input id="employees" type="text" name="employees">
<div id="secondCell">
<div id="instruct">
Enter average salary:
</div>
</div>
<input id="salary" type="text" name="salary">
<div id="thirdCell">
<div id="instruct">
Enter absence %:
</div>
</div>
<input id="absence" type="text" name="absence">
</div>
<div id="instruct">
<div id="output">Total salary (£):
<div id="totalSalary">
</div></div>
<div id="output">Monthly absence cost (£):
<span id="monthlyAbsence">
</span></div>
<div id="output">Annual absence cost (£):
<span id="absenceCost">
</span></div>
</div>
</div>
</form>
Javascript Function
function multiply() {
var employees = document.getElementById('employees').value;
var salary = document.getElementById('salary').value;
var totalSalary = parseInt(employees) * parseInt(salary);
var result1 = document.getElementById('totalSalary');
result1.innerHTML += totalSalary;
var absence = document.getElementById('absence').value;
var absenceCost = parseInt(totalSalary) / 100 * parseInt(absence);
var result2 = document.getElementById('absenceCost');
result2.innerHTML += absenceCost;
var monthlyAbsence = parseInt(absenceCost) / 12;
var result3 = document.getElementById('monthlyAbsence');
result3.innerHTML += monthlyAbsence;
}
});
Any pointers would be greatly appreciated.
You'll need to bind your function to the change event for the input elements.
This can be done a couple of ways:
Obtrusively (not recommended) with the element's onChange attribute (JSFiddle)
Non-obtrusively (preferred) with .on('change', function() {} }) (JSFiddle)
I'm assuming from the tag that you're using jQuery but you can achieve the same thing with vanilla JS using .addEventListener('change', callback, false) (JSFiddle)

Trouble concatenating strings

I'm having an issue concatenating strings. Where I initially declare the 'output' variable in my last function, I'm able to get the number of questions correct printed to my modal window.
However, my concatenation of strings 2 lines down from that won't work and I've tried so many things. I'm sure it's something simple but any help would be appreciated!
I'm not sure how much code is relevant to the solution so I apologize for the wall of code.
I'm new to JS and my first post on Stackoverflow so any tips or advice is appreciated. Thanks in advance!
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = document.getElementById("quizResults").innerHTML = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script
(Disclaimer: This answer might not actually solve your problem, as noted in the comments. I can't delete it, though, because it was accepted.)
(Please see the other answer)
The line
var output = document.getElementById("quizResults").innerHTML = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
does not have the effect you think it does, because javascript does not interpret a statement like var a = b = c the way you think it does. Instead, it is better to use var a = c; var b = c;, like so:
var output = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
document.getElementById("quizResults").innerHTML = output;
For more information on how javascript interprets var a = b = c;, please see this question: Javascript a=b=c statements
The problem is that you're updating the output variable after you've already put it into the quizResults DIV. Assigning the string to .innerHTML makes a copy of it, it's not a reference to the variable, so updating the variable doesn't change the DIV contents. You need to assign to .innerHTML after you've performed the concatenation.
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
document.getElementById("quizResults").innerHTML = output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script

How to "shrink" repetitive virtually identical javascript/jQuery lines?

I'm quite new in programming with javascript/jQuery and managed to have the following work but I'm sure there is a way to "shrink" it in a few lines of code. I've tried with each. but didn't manage to work.
What this piece of code does is:
1) You have some divs with "labels" in them.
2) You save a custom title with localStorage through the inputs
3) The titles are updated
Here is jsFiddle for this too
Code:
<div id="theater-1" class="theater">theater 1</div>
<div id="theater-2" class="theater">theater 2</div>
<div id="theater-3" class="theater">theater 3</div>
<div id="theater-4" class="theater">theater 4</div>
<div id="theater-5" class="theater">theater 5</div>
1
<input type="text" id="theater_name_1" class="input-for-theater-title">
<button id="save-title-1">Save</button>
<br> 2
<input type="text" id="theater_name_2" class="input-for-theater-title">
<button id="save-title-2">Save</button>
<br> 3
<input type="text" id="theater_name_3" class="input-for-theater-title">
<button id="save-title-3">Save</button>
<br> 4
<input type="text" id="theater_name_4" class="input-for-theater-title">
<button id="save-title-4">Save</button>
<br> 5
<input type="text" id="theater_name_5" class="input-for-theater-title">
<button id="save-title-5">Save</button>
<button id="clear">Clear</button>
<script>
var theater_1_saved_name = localStorage.getItem("theater_1_name");
var theater_2_saved_name = localStorage.getItem("theater_2_name");
var theater_3_saved_name = localStorage.getItem("theater_3_name");
var theater_4_saved_name = localStorage.getItem("theater_4_name");
var theater_5_saved_name = localStorage.getItem("theater_5_name");
if (theater_1_saved_name !== null) {
document.getElementById("theater-1").innerHTML = theater_1_saved_name;
document.getElementById("theater_name_1").value = theater_1_saved_name;
};
if (theater_2_saved_name !== null) {
document.getElementById("theater-2").innerHTML = theater_2_saved_name;
document.getElementById("theater_name_2").value = theater_2_saved_name;
};
if (theater_3_saved_name !== null) {
document.getElementById("theater-3").innerHTML = theater_3_saved_name;
document.getElementById("theater_name_3").value = theater_3_saved_name;
};
if (theater_4_saved_name !== null) {
document.getElementById("theater-4").innerHTML = theater_4_saved_name;
document.getElementById("theater_name_4").value = theater_4_saved_name;
};
if (theater_5_saved_name !== null) {
document.getElementById("theater-5").innerHTML = theater_5_saved_name;
document.getElementById("theater_name_5").value = theater_5_saved_name;
};
$("#save-title-1").click(function () {
var title_of_1 = $('#theater_name_1').val();
localStorage.setItem("theater_1_name", title_of_1);
$("#theater-1").text(title_of_1);
});
$("#save-title-2").click(function () {
var title_of_2 = $('#theater_name_2').val();
localStorage.setItem("theater_2_name", title_of_2);
$("#theater-2").text(title_of_2);
});
$("#save-title-3").click(function () {
var title_of_3 = $('#theater_name_3').val();
localStorage.setItem("theater_3_name", title_of_3);
$("#theater-3").text(title_of_3);
});
$("#save-title-4").click(function () {
var title_of_4 = $('#theater_name_4').val();
localStorage.setItem("theater_4_name", title_of_4);
$("#theater-4").text(title_of_4);
});
$("#save-title-5").click(function () {
var title_of_5 = $('#theater_name_5').val();
localStorage.setItem("theater_5_name", title_of_5);
$("#theater-5").text(title_of_5);
});
$("#clear").click(function () {
localStorage.clear();
});
</script>
Loops and string concatenation, look for n in the below for the changes:
var n;
for (n = 1; n <= 5; ++n) {
var theater_saved_name = localStorage.getItem("theater_" + n + "_name");
if (theater_saved_name !== null) {
document.getElementById("theater-" + n).innerHTML = theater_saved_name;
document.getElementById("theater_name_" + n).value = theater_saved_name;
}
$("#save-title-" + n).click(function () {
var title = $('#theater_name_' + n).val();
localStorage.setItem("theater_" + n + "_name", title);
$("#theater-" + n).text(title);
});
}
That changes only your JavaScript, not your HTML or the way you store things in local storage. You could change those as well, for instance using a common class for the elements and getting collections of the relevant elements you could index into, but the above is the JavaScript-only change.
Here's an example that changes your HTML (you already mostly had common classes) and local storage; the key is the index argument/variable:
On jsFiddle (Stack Snippets don't support local storage, grrr)
HTML:
<div class="theater">theater 1</div>
<div class="theater">theater 2</div>
<div class="theater">theater 3</div>
<div class="theater">theater 4</div>
<div class="theater">theater 5</div>
1
<input type="text" class="input-for-theater-title">
<button class="save-title">Save</button>
<br>2
<input type="text" class="input-for-theater-title">
<button class="save-title">Save</button>
<br>3
<input type="text" class="input-for-theater-title">
<button class="save-title">Save</button>
<br>4
<input type="text" class="input-for-theater-title">
<button class="save-title">Save</button>
<br>5
<input type="text" class="input-for-theater-title">
<button class="save-title">Save</button>
<button id="clear">Clear</button>
JavaScript:
var theaters = $(".theater");
var inputs = $(".input-for-theater-title");
var buttons = $(".save-title");
theaters.each(function(index) {
var name = localStorage.getItem("theater_" + index + "_name") || "";
$(this).html(name);
inputs.eq(index).val(name);
});
$(document.body).on("click", ".save-title", function() {
var index = buttons.index(this);
var title = inputs.eq(index).val();
localStorage.setItem("theater_" + index + "_name", title);
theaters.eq(index).text(title);
});

Categories