So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.
<html>
<style>
.numdiv{
height: 400px;
width: 200px;
border:solid 1px green;
float: left
}
</style>
<head>
<script>
function rollDice(){
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var number3 = document.getElementById("number3");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var d3 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2 + d3;
number1.innerHTML = d1;
number2.innerHTML = d2;
number3.innerHTML = d3;
status.innerHTML = "You rolled "+diceTotal+".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<div class="numdiv" id="number1">
0</div>
<div class="numdiv" id="number2">
0</div>
<div class="numdiv" id="number3">
0</div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td></tr>
</table>
</body>
</html>
You can use the setTimeout() method to delay execution of a function, so that the dice will be rolled one at a time:
function rollDice(){
var status = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal = 0;
var current;
for (current = 0; current < nums.length; current++) {
nums[current].innerHTML = "?";
}
current = 0;
status.innerHTML = "Rolling...";
function rollNext() {
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
current++;
if (current < nums.length) {
setTimeout(rollNext, 1000);
} else {
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
status.innerHTML += "You Win!!";
}
}
}
setTimeout(rollNext, 1000);
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td>
</tr>
</table>
Notice also that I've removed your separate number1, number2 and number3 variables, instead using a single variable num to refer to the list of all of the .numDiv div elements. That way you can easily change how many dice you want to use without changing the JS at all (you'd just add or remove .numDiv elements).
EDIT: As I was posting the above you clarified that you want the user to press the button for each die, not automatically roll all three with a delay. So I guess, maybe something like the following, keeping a counter and the total in variables declared outside the function:
var statusSpan = document.getElementById("status");
var nums = document.querySelectorAll(".numdiv");
var diceTotal;
var current = 0;
function rollDice(){
if (current === 0) { // reset display
for (var i = 0; i < nums.length; i++)
nums[i].innerHTML = "?";
diceTotal = 0;
}
currentRoll = Math.floor(Math.random() * 6) + 1;
nums[current].innerHTML = currentRoll;
diceTotal += currentRoll;
if (++current < nums.length) {
statusSpan.innerHTML = "Current total: " + diceTotal + ".";
} else {
statusSpan.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 15){
statusSpan.innerHTML += "You Win!!";
}
current = 0;
}
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px; text-align: center }
<table>
<tr>
<td>
<div class="numdiv" id="number1"></div>
<div class="numdiv" id="number2"></div>
<div class="numdiv" id="number3"></div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()">Roll next die</button></td></tr>
<tr>
<td><span id="status">Ready to roll?</span></td>
</tr>
</table>
Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:
var number = document.getElementById("number" + counter);
I think you know where to go from here. Let me know if you need more guidance!
Building on your existing logic, if you want to display 1 every time user clicks then an alternate approach....
var totalIter = 0;//global var which is set to increments on each click
var diceTotal = 0;
function rollDice() {
totalIter = totalIter + 1; //increment by 1
//Existing logic from your script
var ele = document.getElementById("number" + totalIter);
var d1 = Math.floor(Math.random() * 6) + 1;
var status = document.getElementById("status");
diceTotal = diceTotal + d1;
ele.innerHTML = d1;
status.innerHTML = "You rolled " + diceTotal + ".";
if (diceTotal == 15) {
status.innerHTML += "You Win!!";
}
}
Related
Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
Just did a simple game of checkers, got the logic done of jumping or moving the checker pieces.
Now having problems on the actual logic of when a checker piece moves over or jumps over the other checker piece. How do i automatically remove or delete the checker piece that was jumped over?
Thanks so much :)
<html>
<head>
<style>
body { background-color: #D1CDDF; }
p { font-family: Verdana, Geneva, sans-serif;
font-size: 30; }
img { width: 35px;
height: 35px; }
label { font-family: "Lucida Console", Monaco, monospace;
font-size: 15; }
.focused{ border: 2px solid yellow; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var moves = [];
function saveScore() {
// syntax: $.post(URL,data,callback);
$.post("scores.php",
{
TheFile: $("#filename").val(),
TheMessage: $("#winner").val() + "\r\n"
}
,function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
function openBoard()
{
$(document).ready(function()
{
var p1Name = document.getElementById("p1name").value;
var p2Name = document.getElementById("p2name").value;
var heading = "<center><p><font color=\"red\"><b>" + p1Name + "</b></font> vs <font color=\"blue\"><b>" + p2Name + "</b></font></p></center>";
var table = $('<table width=500px cellspacing=0px cellpadding=0px border=1px ></table>');
var rc;
var picName;
var picName2;
for( y = 1; y <= 8; y++ )
{
var row = $('<tr></tr>');
for ( var x = 1; x <= 8; x++)
{
rc = y + x;
// creating the images
picName = "p" + 1 + ".png" ;
var pic1 = $('<img>').attr('src',picName);
picName2 = "p" + 2 + ".png";
var pic2 = $('<img>').attr('src',picName2);
if(rc % 2 === 0)
{
if(y === 1 || y === 2 || y === 3)
{
var col1 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col1.html(pic1);
row.append(col1);
}
else if(y === 6 || y === 7 || y === 8)
{
var col2 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col2.html(pic2);
row.append(col2);
}
else
{
var col3 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
row.append(col3);
}
}
else
{
var col4 = $('<td align=center height=50px width=50px bgcolor=#C4C160 ></td>');
row.append(col4);
}
}
table.append(row);
}
document.getElementById("bBoard").style.visibility = "hidden";
$('#board').append(heading);
$('#board').append(table);
// setting the listener
$('td').click(function()
{
iAmtheClickListener(this.id);
});
});
}
function iAmtheClickListener(theID)
{
var r = $.inArray(theID,moves); // determine if the id is in the array
var content = $("#"+theID).html();
if( ((r < 0) && (content !== "")) || ((r<0) && (moves.length == 1)) )
{
moves.push(theID);
//change background color
changeBackground("#"+theID,"yellow");
}
else
{
moves.splice(r,1); // to remove
changeBackground("#"+theID,"#4E9660") ;
}
if (moves.length == 2)
{
var destId = moves[1] ;
var srcId = moves[0] ;
var srcImg = $("#" + srcId).html();
$("#" + destId).html(srcImg);
$("#" + srcId).html("");
moves = [] ; // remove all
changeBackground("#"+destId,"#4E9660") ;
changeBackground("#"+srcId,"#4E9660") ;
}
$('#result').html(theID);
}
function changeBackground(theIdUwant, theColor)
{
$(theIdUwant).css("background-color",theColor);
}
</script>
</head>
<body>
<center>
<p>~Checkers~</p>
<table border=1 cellpadding=25px>
<tr><td><label>Player 1: <input type=text id=p1name /></label><br/><br/>
<label>Player 2: <input type=text id=p2name /></label><br/><br/>
<button id="bBoard" onclick="openBoard();">Start Game</button><br/><br/></td>
<td><div class="b" id="board"></div></td>
<td>
<input type=hidden id=filename value="players.txt" />
<label>Register Winner: <input type=text id=winner /></label><br/><br/>
<button id="bReg" onclick="saveScore();">Submit</button><br/><br/>
<div id="result"></div>
</td>
</td></tr>
</table>
</center>
</body>
Suppose jumped piece is at board[row][col], you can assign a value of zero or empty at that particular cell after being jumped:
board[row][col] = EMPTY
I am creating a dice game. I am trying to make it so the user can re-click a button after the loop as gone through to reset the page to play again. My gut tells me an if statement is involved but after several attempts I cannot figure out how to set it up.
I was able to change the button value to show "play again" after pressed, I just need to get the page to reload after the user re-presses the button "play again." Any help would be appreciated thanks.
<script>
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
function rollDice() {
do {
count++;
var userInput = parseInt(document.getElementById("bet").value);
var wallet = userInput;
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
rolls.push(diceTotal);
rollCountMoney.push(wallet);
if(wallet > maxMoney){
maxMoney = wallet;
mostRoll = count - 1;
}
if(userInput > startingBet){
betStarter.push(userInput);
}
if (diceTotal === 7) {
document.getElementById("bet").value = wallet += 4;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You win $4 for a total of: " +wallet);
} else {
document.getElementById("bet").value = wallet -= 1;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You lose $1 for a total of: " +wallet);
}
} while (wallet > 0) {}
var displayMsg = count;
var highest = maxMoney;
var highestRoll = mostRoll;
document.getElementById("display").innerHTML = displayMsg;
document.getElementById("starter").innerHTML = betStarter[0];
document.getElementById("highPot").innerHTML = highest;
document.getElementById("rollPot").innerHTML = highestRoll;
var elem = document.getElementById("playAgain");
if (elem.value=="Play Again"){
elem.value = "Play";
}else {elem.value = "Play Again";
}
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="page-head">
<h1 align="center">Lucky Sevens</h1>
</div>
</div>
<div class="container" align="center">
<table class="table-responsive">
<tr>
<th><h3 align="center"><b>Lucky Sevens</b></h3></th>
</tr>
<tr>
<td>
<form>
Starting Bet:
<input id="bet" type="text"/>
</form>
</td>
</tr>
<tr>
<td align="center">
<form>
<input type="button" id="playAgain" onclick="rollDice()" value="Play"></input>
</form>
</td>
</tr>
</table>
<div class="jumbotron" style="width:400px; position: relative; top: 40px">
<table class="dicey" border="1" style="border-color: white">
<caption ALIGN="top">
<h3 align="center" style="color: black"><b><u>Results</u></b></h3>
</caption>
<tr>
<th style= "background-color: grey"><b>Starting Bet</b></th>
<th style= "background-color: grey" id="starter"></th>
</tr>
<tr>
<td>Total rolls before going broke </td>
<td id="display"></td>
</tr>
<tr>
<td>Highest amount won </td>
<td id="highPot"></td>
</tr>
<tr>
<td>Roll count at highest amount won </td>
<td id="rollPot"></td>
</tr>
</table>
</div>
</div>
If I understood your code correctly, you can either reload the page:
function rollDice(){
if (document.getElementById("playAgain").value=="Play Again")
location.reload();
...
or reset it to the initial state:
function rollDice() {
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
document.getElementById("display").innerHTML = "";
document.getElementById("starter").innerHTML = "";
document.getElementById("highPot").innerHTML = "";
document.getElementById("rollPot").innerHTML = "";
...
The simplest way would be to add a second button for play again like
<button id="play-again-button" style="display:none" onclick="location.reload()">play again</button >
Then show it when you need to via
document.getElementById("play-again-button').style.display = "block";
If you want to actually refresh the page. Or tie that button's onclick to a js function that resets things.
I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>
lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.
I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {
Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.