I need help fixing my script. Basically, I want it to flip a coin and update a <span> with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.
JavaSript:
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML:
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
That's simply because you need to attach the event handler:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
var prob1 = Math.floor(Math.random() * 2) +1;
var prob2 = Math.floor(Math.random() * 2) +1;
if( prob1 === prob2){
document.write('You Got TAIL');
}else{
document.write('You Got HEAD');
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button" onclick="click()">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
function flip(Throws) {
let coinArray = [];
for (var i = 0; i < Throws; i++) {
rndNo = Math.floor(Math.random() * 2 + 1);
if (rndNo === 1) {
Toss = 'H';
} else {
Toss = 'T'
} // if (rnd === 1)
coinArray.push(Toss);
}
return coinArray;
}
console.log(flip(10));
function flipHeadCoin() {
let coinArray = [];
let numHeads = 0;
do {
rndNo = Math.floor(Math.random() * 2 + 1);
// ternary operators
Toss = (rndNo === 1) ? 'H' : 'T';
numHeads += (Toss === 'H') ? 1: 0;
coinArray.push(Toss);
} while (numHeads < 6);
return coinArray;
}
console.log(flipHeadCoin());
const coinFlip = num_of_coin_flips => {
heads = 0;
tails = 0;
for(i = 0; i < num_of_coin_flips; i++){
randomNumber = Math.floor(Math.random() * 2);
roundNum = Math.round(randomNumber* 100) / 100;
roundNum === 0
? heads += 1
: tails += 1;
}
return `There are ${heads} heads and ${tails} tails. That's a ${((heads / num_of_coin_flips) * 100)} % / ${((tails / num_of_coin_flips) * 100)} % split`
}
console.log(coinFlip(3))
<!DOCTYPE html>
<html>
<body>
<p id="Another way"></p>
<script>
var x;
x = (Math.floor(Math.random() * 2) == 0);
if (x==1) {
x="Blue"
} else {
x="Red"
};
document.getElementById("Another way").innerHTML =
"The color of the pill is " + x + "!.";
</script>
</body>
</html>
And ofcourse this still needs an event handler ;) it's late guys :)
Related
I am creating a math game with javascript that asks the user to solve basic math problems based on their chosen select menu option. The user will enter their answer using an input field and when the enter key is pressed a function is called that checks wether or not the answer is correct.
I am having trouble creating a function that can check the different kinds of arithmetic when the enter key is pressed. So far I have only managed to create a check function that can check a single kind of arithmetic.
The basics of the game are this:
the user selects wether to do addition, subtraction, multiplication, or division, then presses the "start" button and the first question is generated of their chosen operation
when the enter key is pressed if the users input is correct, the score is incremented by 1, and a new question of the same kind of arithmetic is generated, if not they are asked to try again.
let gameMenu = document.getElementById('game-menu');
let gameCard = document.getElementById('game-card');
let x = document.getElementById("num1");
let y = document.getElementById("num2");
let displayOperator = document.getElementById('display-operator');
let score = 0;
let answer = document.getElementById('user-answer');
answer.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
check();
}
});
function start() {
let opt = document.getElementById('opt');
let selOpt = opt.options[opt.selectedIndex].value;
if (selOpt == "+") {
doAddition();
}
if (selOpt == "-") {
doSubtraction();
}
if (selOpt == "*") {
doMultiplication();
}
if (selOpt == "/") {
doDivision();
}
}
function doAddition() {
displayOperator.innerHTML = "+"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doSubtraction() {
displayOperator.innerHTML = "−"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doMultiplication() {
displayOperator.innerHTML = "×"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doDivision() {
displayOperator.innerHTML = "÷"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function check() {
let x = parseInt(document.getElementById("num1").innerHTML);
let y = parseInt(document.getElementById("num2").innerHTML);
let tryAgain = document.getElementById("try-again");
let answer = parseInt(document.getElementById("user-answer").value);
if (answer === x + y) {
score++;
document.getElementById("score").innerHTML = score;
} else {
tryAgain.innerHTML = "incorrect, try again";
preventDefault();
}
document.getElementById("user-answer").value = "";
doAddition();
}
#question {
display: flex;
flex-direction: row;
}
<!DOCTYPE html>
<head>
</head>
<body>
<div id="game-menu">
<p>game menu</p>
<select id="opt">
<option value="+">Addition</option>
<option value="-">Subtraction</option>
<option value="*">Multiplication</option>
<option value="/">Division</option>
</select>
<button onclick="start()">START</button>
</div>
<div id="game-card">
<div id="question">
<p id="num1"></p>
<p id="display-operator"></p>
<p id="num2"></p>
</div>
<p id="try-again"></p>
<input id="user-answer">
<p id="score">score</p>
</div>
</body>
This is the current code that I have.
I have separate functions for each type of arithmetic and plan on modifying the Math.floor(Math.random()*5+1) in the doSubtraction() and doDivision() functions to prevent negative answers and avoid division questions that aren't evenly divisible.
The problem I'm facing now is that I am not clear on how to make the check() function account for what the user chose from the select menu. I've included (answer === x + y) and doAddition() in the check() function to show how it works, but I cant figure out how to make it check for the proper arithmetic based on the select menu that was chosen, and then call back to the same type of function that was chosen.
I'm pretty new to javascript and appreciate the help and any constructive criticism too. Thanks.
Get the value of the dropdown the same way you do it in start(), then use similar if/else if statements to check the result.
At the end of check() call start() again to generate a new question using the same select option.
You need to clear tryAgain when the user enters a correct answer.
let gameMenu = document.getElementById('game-menu');
let gameCard = document.getElementById('game-card');
let x = document.getElementById("num1");
let y = document.getElementById("num2");
let displayOperator = document.getElementById('display-operator');
let score = 0;
let answer = document.getElementById('user-answer');
answer.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
check();
}
});
function start() {
let opt = document.getElementById('opt');
let selOpt = opt.options[opt.selectedIndex].value;
if (selOpt == "+") {
doAddition();
}
if (selOpt == "-") {
doSubtraction();
}
if (selOpt == "*") {
doMultiplication();
}
if (selOpt == "/") {
doDivision();
}
}
function doAddition() {
displayOperator.innerHTML = "+"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doSubtraction() {
displayOperator.innerHTML = "−"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doMultiplication() {
displayOperator.innerHTML = "×"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doDivision() {
displayOperator.innerHTML = "÷"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function check() {
let x = parseInt(document.getElementById("num1").innerHTML);
let y = parseInt(document.getElementById("num2").innerHTML);
let tryAgain = document.getElementById("try-again");
let answer = parseInt(document.getElementById("user-answer").value);
let selOpt = document.getElementById('opt').value;
let correctAnswer;
switch (selOpt) {
case '+': correctAnswer = x + y; break;
case '-': correctAnswer = x - y; break;
case '*': correctAnswer = x * y; break;
case '/': correctAnswer = Math.floor(x / y); break;
}
if (answer === correctAnswer) {
score++;
document.getElementById("score").innerHTML = score;
tryAgain.innerHTML = '';
} else {
tryAgain.innerHTML = "incorrect, try again";
}
document.getElementById("user-answer").value = "";
start();
}
#question {
display: flex;
flex-direction: row;
}
<!DOCTYPE html>
<head>
</head>
<body>
<div id="game-menu">
<p>game menu</p>
<select id="opt">
<option value="+">Addition</option>
<option value="-">Subtraction</option>
<option value="*">Multiplication</option>
<option value="/">Division</option>
</select>
<button onclick="start()">START</button>
</div>
<div id="game-card">
<div id="question">
<p id="num1"></p>
<p id="display-operator"></p>
<p id="num2"></p>
</div>
<p id="try-again"></p>
<input id="user-answer">
<p id="score">score</p>
</div>
</body>
You should probably already store the correct answer once you decide on which arithmetic you are going to ask, and pass it to the check function. Then you'll only have to check if the user's answer is the same as the correct one.
I wanna create a slot machine with 3 number by javascript - but I want to finish my function when three numbers are equal.
I think that if I write it with do/while it will be work, but I can't do it
this is my js code:
function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}
this function is set onclick attr of a button tag
Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts:
Added a reset button to reset the game.
var counter = 0;
function myF() {
if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}
function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>
<div id="slotLeft">
</div>
<div id="slotOne">
</div>
<div id="slotTwo">
</div>
<div id="slotThree">
</div>
<div id="winner">
</div>
function myF() {
var slotOneElem = document.getElementById("slotOne");
var slotTwoElem = document.getElementById("slotTwo");
var slotThreeElem = document.getElementById("slotThree");
var generateRand = function() {
return Math.floor(Math.random() * 3) + 1;
}
return (function () {
var slotOne = generateRand();
var slotTwo = generateRand();
var slotThree = generateRand();
slotOneElem.innerHTML = slotOne;
slotTwoElem.innerHTML = slotTwo;
slotThreeElem.innerHTML = slotThree;
if (slotOne === slotTwo && slotTwo === slotThree) {
slotOneElem.style.backgroundColor = "#48bd48";
slotTwoElem.style.backgroundColor = "#48bd48";
slotThreeElem.style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
// Here is the win
return true;
}
return false;
})();
}
var finished = myF();
while (!finished) {
finished = myF();
}
I'm trying to store two random numbers between 0 and 10, in two different variables play1 and play2.
The maximum value for play2 will be 10 minus play1 value, ie, if play1 gets 6, maximum value for play2 will be 4.
how can I trigger play2 to store the second value? I need it to be triggered with a second click.
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
max = 10 - play1
document.getElementById("result").innerHTML = play1;
if (play1 < 10 ) {
//trigger play2
}
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
You can simply calculate the value of play2 the same way you calculated the value of play1 by using - play2 = Math.floor(Math.random()*(max-min+1)) + min;. I have updated your code below-
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
max = 10 - play1
document.getElementById("result").innerHTML = play1;
if (play1 < 10 ) {
play2 = Math.floor(Math.random()*(max-min+1)) + min;
} else {
play2 = 0;
}
document.getElementById("result2").innerHTML = play2;
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
<p id="result2"></p>
Don't repeat yourself. That's what functions are for:
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = r(min, max);
play2 = r(min, max - (play1-min));
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
i need the second value to be triggered with a second click.
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
var nthClick = 0;
function myFunction() {
++nthClick;
if(nthClick & 1){
//odd
play1 = r(min, max);
play2 = null;
}else{
//even
play2 = r(min, max - (play1-min));
}
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
like this?
Perhaps this
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
var target = document.getElementById("result");
var firstNum = parseInt(target.innerHTML);
if (isNaN(firstNum)) { // first click
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
target.innerHTML = play1;
} else {
play2 = Math.floor(Math.random() * ((10 - firstNum) - min + 1)) + min;
// do what with it????? you haven't shown!
document.getElementById("result2").innerHTML = play2;
}
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
<p id="result2"></p>
Try adding a control to the click count. Code copied and modified from Thomas' answer
var controlVariable = 1;
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
if (controlVariable == 1) {
play1 = r(min, max);
controlVariable++;
}
else if (controlVariable == 2) {
play2 = r(min, max - (play1-min));
controlVariable = 1;
}
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<td><button type="button" onclick="onClick()" >0.1</td>
<p>Ball Count: <a id="clicks">0.0</a></p>
Hi I am trying to create customized click counter, when every 6th click it should go to the next whole number( Example: 0.1,0.2,0.3,0.4,0.5,1.0 (6th click),1.1,1.2,1.3,1.4,1.5,2.0(12th click) like wise) and how to decrease the same way... Kindly help me.....
Your requirement have some similarities to the time calculation. You can use the following.
jQuery version
var clicks = 0;
$('#plusClick, #minusClick').on('click', function () {
if( this.id == 'plusClick' )
clicks += 10;
else if( clicks > 0 )
clicks -= 10;
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="clicks">0.0</div>
<button id="minusClick">-</button>
<button id="plusClick">+</button>
JS version
var clicks = 0;
function onClick(operation) {
if( operation ){
clicks += 10;
} else if(clicks > 0){
clicks -= 10;
}
var first = Math.floor((clicks) / 60);
var second = clicks - (first * 60);
if (first < 10) {first = "0" + first;}
if (second < 10) {second = "0" + second;}
var value = first + '.' + second;
document.getElementById("clicks").innerHTML = parseFloat(value).toFixed(1);
}
<div id="clicks">0.0</div>
<button id="minusClick" onclick="onClick(false)">-</button>
<button id="plusClick" onclick="onClick(true)">+</button>
May be you are looking for something like this:
var a = 0;
function increase() {
if (a % 10 == 5)
a += 5;
else
a++;
return a / 10;
}
function decrease() {
if (a % 10 == 0)
a -= 5;
else
a--;
return a / 10;
}
Note that I have used a Global Variable for this, which is not recommended.
Snippet, without global values.
var counter = {
currentValue: 0
};
function increase() {
var a = counter.currentValue;
if (a % 10 == 5)
a += 5;
else
a++;
counter.currentValue = a;
return a / 10;
}
function decrease() {
var a = counter.currentValue;
if (a % 10 == 0)
a -= 5;
else
a--;
counter.currentValue = a;
return a / 10;
}
input {border: 1px solid #999; padding: 5px; width: 15px; height: 15px; text-align: center; font-family: 'Segoe UI'; line-height: 1; width: 50px;}
input[type=button] {padding: 0; vertical-align: top; width: 35px; height: 27px;}
<input type="button" value="-" onclick="currentCount.value = decrease();" />
<input type="text" id="currentCount" value="0" />
<input type="button" value="+" onclick="currentCount.value = increase();" />
Just change onclick() with
function onClick(){
clicks += 1;
var a = Math.floor(clicks/6);
var b = (clicks%6);
document.getElementById("clicks").innerHTML = a + '.' + b;
}
Try to make use of mathematics not some school boy logic,
function increment(val) {
++val;
$("button").data("count", val);
return (val + (Math.floor((val / 6)) * 4)) / 10;
}
$("button").click(function () {
$('input').val(increment(parseFloat($(this).data("count"))));
});
DEMO