I am wondering why i get the message: 'Uncaught ReferenceError: d1 is not defined' at the console
I want to add the dice rolls into an array.
this is my code:
<html>
<head>
<script>
var diceRolls = [];
diceRolls.push(d1);
if (diceRolls[diceRolls.length - 1] === d1) {
console.log("Je hebt 5 punten gewonnen!");
}
function rollDice() {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
}
</script>
</head>
<body>
<div id="die1" class="dice">0</div>
<button onclick="rollDice()"> Roll the dice </button>
<h2 id="status" style="clear:left":> </h2>
</body>
The second line of the script is trying to push d1 into diceRolls when you haven't initialized d1 yet. You'd have to declare rollDice() above the rest of the script, and then call it to push a value into diceRolls.
I think you might want to try something along these lines?
var diceRolls = [];
function rollDice() {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
}
if (diceRolls[diceRolls.length - 1] === d1) {
console.log("Je hebt 5 punten gewonnen!");
}
diceRolls.push(d1);
At the point the browser reaches this line, d1 hasn't been set yet. I think if you throw that into the rollDice function you will get what you're after. In other words:
function rollDice() {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
}
Edit: AVP beat me by about 30 seconds, he gets my vote.
Related
I'm just learning javascript and my project is to create a web page with the following elements: An h2 header, two img elements, an input box, and a button element. When the page loads, Dice.getURL is called twice to get the URL for the 1-dot die, and the jQuery.attr() function is used to display the images when the page loads: When the user enters a target number and clicks Roll 'em!, the images are updated die-namically and the results displayed in a div on the page.
I've got the basics down but I have no idea how to do the rest of this stuff. I've been looking online but haven't found what I needed. I hope you guys can be what I need:
The main issue that I have is that the numRolls variable is not keep track of how many times the do/while loop runs through. I am also confused on how to keep track of the dice rolls via images so it displays the correct output when the "solution is found"
Here is a link to my jsfiddle: https://jsfiddle.net/0088v6nt/3/
HTML
<!Doctype html>
<body>
<h2>Roll Number</h2>
<img id="dice1" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<img id="dice2" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<p>Enter target number:</p>
<input type="text" id="num"><br><br>
<button id="R">Roll 'em!</button>
<br><br>
<div id="time"></div>
</body>
JavaScript
//define a Dice object, properties and methods
var Dice = {
sides: 6,
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
},
rollDice: function() {
var diceTotal = 0;
diceTotal += this.rollDie($('#dice1'));
diceTotal += this.rollDie($('#dice2'));
return diceTotal;
},
URL_prefix: "http://dave-reed.com/book3e/Images/",
getURL: function(n) {
//return the URL for an n-dot die
return this.URL_prefix + "die" + n + ".gif";
}
};
//top-level function
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
var numRolls = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
function getRoll () {
var number = parseFloat($("#num").val());
var numRolls = roll_number(number);
$("#time").text( "You rolled " + number + " in " + numRolls + " rolls");
}
$(document).ready(function(){
$("#R").on("click", getRoll);
//$("#roll").on("click", Dice.getURL);
});
Thank you again!
-Kron
There's two issues with your code. First die1 and die2 are never set because Dice.rollDie doesn't return a value. Updating the function to return the value of the die fixes this:
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
return rolledValue;
},
Second, the while loop currently only set to keep running while the sum matches the total, instead it should keep running while it doesn't match the total. It should look like instead:
while(die1 + die2 !== n);
This can lead to infinite loops if you pass a bad value to n (such as null, or anything greater than 12), so be careful
https://jsfiddle.net/0088v6nt/4/
You're setting the counter to zero every time the roll_number function is called i fixed it by moving the counter variable outside the function scope so it's not being reset all the time..
var numRolls = 0;
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
https://jsfiddle.net/0088v6nt/5/
I am trying to make a children's math quiz and so far I have been able to do the following: Get two random numbers between 0 and 10 to appear; Make the + or - operator random; Give feedback if the answer is wrong or right; keep score;
There is one problem that I am facing though is that in some cases the operator will be - and the second random number will be greater than the first resulting in a - number answer. As can be seen inside the code below, I have tried using an if statement within an if statement and also a while statement within an if statement. Both do not produce the desired results.
I appreciate any advise on how to fix my problem.
Code:
document.getElementById("button1").addEventListener("click", question);
var plusMinus = document.getElementById("plusMinus");
var counter = 0;
function question(){
var startButton = document.getElementById("button1");
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var decider = Math.random();
counter ++;
if(decider<0.5){
plusMinus.textContent = "+"
}
else{plusMinus.textContent = "-"
};
button1.textContent = "Round" + counter;
number1.textContent = Math.floor(Math.random()*11);
number2.textContent = Math.floor(Math.random()*11)
/*Solution No.1 that failed:
if(plusMinus.textContent == "-"){
if(number2.textContent < number1.textContent){
Math.floor(Math.random()*11);
}
}
else{Math.floor(Math.random()*11);
}*/
/*Solution No.2 that also failed:
if(plusMinus.textContent == "-"){
while(number2.textContent < number1.textContent){
Math.floor(Math.random()*11);
}
}
else{Math.floor(Math.random()*11);
}*/
};
document.getElementById("button2").addEventListener("click", answer);
var totalScore = 0;
function answer(){
var num1 = parseInt(document.getElementById("number1").textContent, 10);
var num2 = parseInt(document.getElementById("number2").textContent, 10);
var answer = parseInt(document.getElementById("userAnswer").value, 10);
var feedBack = document.getElementById("feedBack");
var scoreReport = document.getElementById("score");
if (plusMinus.textContent == "+"){
if(answer == num1 + num2) {
feedBack.textContent = "Well Done!";
totalScore = totalScore + 10;
}
else {
feedBack.textContent = "Try again!";
}
}
else {
if(answer == num1 - num2){
feedBack.textContent = "Well Done!";
totalScore = totalScore +10;
}
else {feedBack.textContent = "Try again!"};
}
scoreReport.textContent = totalScore;
};
Here is a jsfiddle: http://jsfiddle.net/way81/r9vdLkzp/1/
You can check if its minus. Check if the number2 is bigger than the number1 then swap them.
Something like this:
if(plusMinus.textContent == '-' && number2.textContent > number1.textContent) {
var a = number2.textContent;
number2.textContent = number1.textContent;
number1.textContent = a;
}
When you call answer() you are getting the values again. So the fact that you swapped the order won't have any effects in the rest of your logic and you won't get any negative numbers.
Snippet:
document.getElementById("button1").addEventListener("click", question);
var plusMinus = document.getElementById("plusMinus");
function question(){
var startButton = document.getElementById("button1");
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var decider = Math.random();
button1.textContent = "Again";
number1.textContent = Math.floor(Math.random()*11);
number2.textContent = Math.floor(Math.random()*11);
if(decider<0.5){
plusMinus.textContent = "+"
}
else{plusMinus.textContent = "-"};
if(plusMinus.textContent == '-' && number2.textContent > number1.textContent) {
console.log('swapped')
var a = number2.textContent;
number2.textContent = number1.textContent;
number1.textContent = a;
}
};
document.getElementById("button2").addEventListener("click", answer);
function answer(){
var num1 = parseInt(document.getElementById("number1").textContent, 10);
var num2 = parseInt(document.getElementById("number2").textContent, 10);
var answer = parseInt(document.getElementById("userAnswer").value, 10);
var feedBack = document.getElementById("feedBack");
var scoreReport = document.getElementById("score");
var totalScore = 0;
if (plusMinus.textContent == "+"){
if(answer == num1 + num2) {
feedBack.textContent = "Well Done!";
} else {
feedBack.textContent = "Try again!";
}
}
else {
if(answer == num1 - num2){
feedBack.textContent = "Well Done!";
} else {feedBack.textContent = "Try again!"};
}
for(count=0; count <=10; count++){
if(plusMinus == "+" && answer == num1+num2){
totalScore +1;
}
else if(plusMinus == "-" && answer == num1-num2){
totalScore -1;
}
}
scoreReport.textContent = totalScore;
};
*{
border: 2pt solid black;
}
p {
height: 20px;
width: 50px;
font-family: impact;
size: 16pt;
text-align: center;
}
<body>
<div>
<button id = "button1">Start!</button>
<p id = "number1"></p>
<p id = "plusMinus">+</p>
<p id = "number2"></p>
<input id = "userAnswer" type=text>
<button id = "button2">Answer</button>
<p id = "feedBack"></p>
<p id = "score">Score: 0</p>
</div>
<script src="randomMathsTest.js"></script>
</body>
You could use the first random number as an argument in creating the second random number. For instance:
var num1 = Math.floor(Math.random()*11);
var num2 = num1+ Math.floor(Math.random()*(10-num1));
...or something similar. Just generate a random number between your first random number and 10 by creating a smaller range and adding the first number to the result.
Addendum
By following this method, you do skew the likelihood of larger numbers appearing in your problems. #Joel's answer would not suffer from this.
Here's a generalized solution you could use (it's not entirely adapted to your current code example, but I'm sure you'll be able to get it to work):
// create a random Boolean that determines whether it's minus
var isMinus = !Math.round(Math.random());
// create an array of two random numbers from 0-10
var numbers = [Math.floor(Math.random()*11), Math.floor(Math.random()*11)];
// if isMinus, sort numbers ascending, else keep as-is
numbers = isMinus ? numbers.sort().reverse() : numbers;
// assign the proper sign to the DOM element
plusMinus.textContent = isMinus ? '-' : '+';
// assign the proper array elements to the DOM elements
number1.textContent = numbers[0];
number2.textContent = numbers[1];
I'm having trouble creating a Blackjack program to display in an HTML page using an external Javascript file.
I don't need to label my cards, and I've created a dealer that will always be between 17-21 in score.
I'm unsure of what parts of my code is completely wrong and what needs a bit of tweaking. I believe I've done something that has broken the program.
EDIT: I've edited some of the fixes that many of you have helped with, an error I get when running the program is that if I do use an alert to display the score/outcome, the alert does not appear when running.
My goal is to display my the score/cards from my Javascript code into my HTML code which looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blackjack</title>
<link rel="stylesheet" type="text/css" href="CSSedit.css">
</head>
<body>
<script type="text/javascript" src="Blackjack.js">
</script>
<h1>Javascript Blackjack</h1>
<p>Player's Hand: </p>
<br>
<p>Dealer's Score: </p>
<p>Player's Score: </p>
<br>
<p>Game Results: </p>
</body>
</html>
My javascript code:
//function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
//function that returns dealers hand between 17-21
var dealerhand = function(x, y) {
cardDealer = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardDealer;
}
//declaring variables
var card1 = deal();
var card2 = deal();
var dealer = dealerhand();
var x = 17;
var y = 21;
//retrieving the value of the cards from the deal function
var getValue = function(card) {
if(card % 13 === 0 || card % 13 === 11 || card % 13 === 12){
return 10;
}
if(card % 13 === 1){
return 11;
}
else{
return card % 13;
}
}
//scoring the cards dealt and determining the outcome
//using the if and else if statements
function score() {
if ((getValue(card1) + getValue(card2)) > 22){
return "Busted!";
}
else if (getValue(cardDealer) > getValue(card1) + getValue(card2)){
return "You lose!";
}
else if (getValue(cardDealer) === getValue(card1) + getValue(card2)){
return "Draw!";
}
else{
return getValue(card1) + getValue(card2);
}
}
//Need to display results onto HTML page
//alert("You have card " + card1 + " / " + card2 +
// " Score: " + score(card1, card2);
You have a syntax error on your deal function
//function that returns dealers hand between 17-21
var dealerhand = function(17, 21) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD; //should be return card;
}
Use the console in your browser (accessible through dev tools) to help spot errors in your application, errors like this show up bright as day.
There is a syntax error on line 14:
var dealerhand = function(17, 21) {
...
You can only pass variables as arguments to a function and 17 and 21 are not variables. An easy fix would be:
var a = 17;
var b = 21;
var dealerhand = function(a, b) {
...
Hopefully ES6's argument defaults will clear some confusion in this area.
Edit:
You have another error on line 41:
if (getValue(card1) + getValue(card2) > 22{
Should be
if ((getValue(card1) + getValue(card2)) > 22) { ... }
Edit 2:
An another one. Functions should be declared before using references in the variables and thus these two functions should come before your declaring variables comment.
// function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
// function that returns dealers hand between 17-21
var dealerhand = function(a, b) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD;
}
I have been trying to do a simple game where you try to get the right number as the random number. If you win, you get 1 point. But I wasn't able to give that point. Here is what i have done :
<html>
<head>
<title>Luck Game</title>
<script>
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
var points = 0;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
</head>
<body>
<input id="input"></input>
<p id="Answer"></p>
<button onClick="onClick()"></button>
<p id="WIN?"></p>
<p id="points"></p>
</body>
But the "points = points + 1" is not working !
what is wrong ? please help me .
You should declare your var points outside click function. E.g :
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
So the counter will be saved somewhere else without being resetted everytime function procs.
The way you've written it, points is a variable local to the onClick() function so it will get reset to zero each time the function is called. If you pull the initialization of points out of onClick() then you will be able to safely increment its value:
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points++;
} else {
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
Declare var points outside function:
var points = 0;
function onClick(){
...
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div.dice {
float:left;
width:32px;
background:#F5F5F5;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
</style>
<script>
function rollDice() {
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var wins = documentgetElementById("doubles");
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal + ".";
if (d1 == d2) {
status.innerHTML += " DOUBLES! You get a free turn!!";
}
}
</script>
</head>
<body>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button onclick="rollDice()">Roll Dice</button>
<h2 id="status" style="clear:left;"></h2>
<br>Wins:
<h5 id="doubles" style="clear:left;"></h5>
<br>
</body>
</html>
I want to have it so the Wins is updated every time they roll doubles
I still noob at this i was thinking it would be a simple line of code added after the
status.innerHTML += " DOUBLES! You get a free turn!!";
doubles.innerHTML =+ Wins;
put var wins = document.getElementById("doubles"); ??? i know im doing something wrong any help would be awesome! Sincerely LM
http://jsfiddle.net/GkPEA/
var wins = documentgetElementById("doubles"); has a typo and should be var wins = document.getElementById("doubles");
As for updating the win counter, you need to convert the element's value to an int before adding 1. However, I'd suggest storing the win count in a global variable as opposed to text in a DOM element.
if (d1 == d2) {
status.innerHTML += " DOUBLES! You get a free turn!!";
var winsCount = parseInt(wins.innerHTML) || 0;
wins.innerHTML = winsCount + 1;
}
I see your problem. There is a typo on the line where you declare the variable wins, documentgetElementById() should be document.getElementById(). Start off with 0 in the wins h5 and then every time the player wins do this code:
var previouswins = document.getElementById("doubles").innerHTML;
var presentwins = parseInt(previouswins, 10) + 1;
document.getElementById("doubles").innerHTML = presentwins;
That code creates a variable called previouswins that is basically just everything that's inside the doubles h5. Then we parse that as an integer, which means that javascript can now do math functions with it and then we add one. All that's left to do after that is write the new variable to the doubles h5.
Note that when using parseInt, you should always specify a radix (the base of number), as this does not default to 10 like you might expect. You can read more about this on MDN.