<!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.
Related
I'm very new to JavaScript, but I have some knowledge of c, and a good amount of knowledge about HTML.
My issue in this project is that I want the second button (the one that onclick should run the firstx2 function) to become visible only after the points are 100 or more, and I'm not sure how to go about this. Also need the button to disappear after they click it. Thanks!
var points = 0;
var pointMulti = 1;
function addPoints() {
points = points + pointMulti;
document.getElementById("pointdisplay").innerHTML = "You have " + points
+ " points!";
}
function firstx2() {
pointMulti *= 2;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " +
pointMulti + "!"
}
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button onclick="firstx2">x2 Multiplier. Cost: 100</button>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
You did not call the function properly.
changed onclick="firstx2" to onclick="firstx2()"
Also Added few edits to the logic where the score reduces by 100 when you purchase x2 Multiplier.
But the main problem was calling the function.
var points = 0;
var pointMulti = 1;
function addPoints() {
points = points + pointMulti;
document.getElementById("pointdisplay").innerHTML = "You have " + points +
" points!";
}
function firstx2() {
if (points >= 10) {
pointMulti = pointMulti * 2;
points = points - 10;
document.getElementById("pointdisplay").innerHTML = "You have " + points +
" points!";
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " +
pointMulti + "!";
}
}
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button onclick="firstx2()">x2 Multiplier. Cost: 100</button>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
Ok, here's how you do it:
correct the onclick part of the second button, like others have mentioned
add an id to the second button and add styles to it: display:none; to hide it
make it appear in addPoints (set display:inline;)
regarding disappearing, you may set display:none; back again
the particular implementation below works like you described: the multiply button will appear after each click on the first button when you have >=100 points (I've set initial points to 98 for quicker testing):
var points = 98;
var pointMulti = 1;
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
pointMulti *= 2;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
If you'd like the second button to be displayed only once, you should make an extra variable, something like multiplier_got_available, set and check it accordingly. Also, it seems that you wanted to add points -= 100 to firstx2.
First, change
<button onclick="firstx2">x2 Multiplier. Cost: 100</button>
to
<button onclick="firstx2()">x2 Multiplier. Cost: 100</button>
You need the parenthesis.
Second, this should work (replace your firstx2 function with this)
function firstx2(){
if(points >= 100){
pointMulti *= 2;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti + "!";
document.getElementById("pointdisplay").innerHTML = "You have " + points;
points -= 100;
}
}
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 making an javaScript game - that in the end is going to be a battleship game with grid GUI and so forth.
Have started making a horizontal grid with tiles (that the user can define for himself(min. 4 tiles))
When clicked a tile turns from blue to red indicating if it has been hit or not - BUT it doesn't register that if it is hit 3 times then the stats and accuracy should pop-up:
etc. after 3 this it will pop-up with stats: "You took 3-4 guesses to sink my battleship and your accuracy is 30%"
Instead it gives me 0 guesses and my accuracy is infinity :)
I have posted my code below:
<html>
<head>
<title></title>
<style type="text/css">
td
{
width: 94px;
height: 94px;
background-color: blue;
}
.clicked
{
color: red;
}
</style>
</head>
<body>
<div id="board">
<div id="messageArea"></div>
<table>
<tr id="tblRow">
</tr>
</table>
</div>
<script type="text/javascript">
var boardLength;
do {
boardLength = prompt('Enter length of board length (min 4)')
}
while(boardLength <4);
var boardLengthCal = parseInt(boardLength)-2;
var randomLoc = Math.floor(Math.random() * boardLengthCal);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location1 + 2;
console.log(location1);
console.log(location2);
console.log(location3);
for (var i = 0; i < boardLength; i++){
document.getElementById('tblRow').innerHTML +="<td id='"+i+"'></td>"
};
var fields = document.getElementsByTagName('td');
for (var i =0; i < fields.length; i++){
fields[i].addEventListener('click', pickLocation)
};
function pickLocation(){
guess = this.id;
if (guess < 0 || guess > boardLength) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
changeColor(this, "red");
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3*100/guesses)+"%";
alert(stats);
function changeColor(element, color)
{
element.style.backgroundColor = color;
};
</script>
</body>
</html>
Your stats showing code is executing before the game even started. At that time value of your guesses is 0, so dividing by 0 is giving you infinity. You need to put your stats code in a function and call it when the game ends (3 hits)
function stats(){
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3*100/guesses)+"%";
alert(stats);
}
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
stats();
}
Now when the user hits three time, only then stats will pop up with correct values.
See the DMEO here
EDIT:
I made some improvements in your game and now really made it playable by introducing random numbers instead of three in a line and other minor errors removed.. you can check that version HERE.
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(){
...
}
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.