I have created a math game using Django and I use JavaScript in the backend to run the game without a page refresh. I need to update the score field after the game ends. I can't seem to get that to work. The score updates on the frontend but not in the database so when the detail form displays the score is always zero.
JavaScript:
let number1;
let number2;
operator = document.getElementById('operator').innerHTML;
max = Number(document.getElementById('max').innerHTML);
if (operator == '+') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
} else if (operator == '-') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
if (number2 > number1) {
number2 = number1
number1 = number2
}
} else if (operator == '*') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
} else {
number2 = Math.floor((Math.random() * max) + 1);
numberx = Math.floor((Math.random() * max) + 1);
number1 = number2 * numberx
}
document.getElementById('number1').innerHTML=number1;
document.getElementById('number2').innerHTML=number2;
document.getElementById('tbInput').focus();
window.addEventListener("keydown", function(e) {
if (e.key === 'Enter' || e.keycode === 13) {
if (operator == '+') {
answer = number1 + number2;
} else if (operator == '-') {
answer = number1 - number2;
} else if (operator == '*') {
answer = number1 * number2;
} else {
answer = number1 / number2;
}
const checkAnswer = document.getElementById('tbInput');
const value = checkAnswer.value;
let playerScore = + this.document.getElementById('playerScore').innerHTML;
if (value == answer) {
playerScore+=1;
document.getElementById('playerScore').innerHTML=playerScore;
} else {
alert('You are incorrect, the answer was ' + answer);
}
document.querySelector('input[type=text]').value = "";
document.getElementById('number1').innerHTML = "";
document.getElementById('number2').innerHTML = "";
if (operator == '+') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
} else if (operator == '-') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
if (number2 > number1) {
number2 = number1
number1 = number2
}
} else if (operator == '*') {
number1 = Math.floor((Math.random() * max) + 1);
number2 = Math.floor((Math.random() * max) + 1);
} else {
number2 = Math.floor((Math.random() * max) + 1);
numberx = Math.floor((Math.random() * max) + 1);
number1 = number2 * numberx
}
document.getElementById('number1').innerHTML = number1;
document.getElementById('number2').innerHTML = number2;
document.getElementById('tbInput').focus();
}
});
});
I tried using ajax but it didn't work. I am probably doing it wrong. I am new at this. Here is my ajax function:
function register(score) {
const csrfInput = document.querySelector("input[name='csrfmiddlewaretoken']");
const csrfToken = csrfInput.value;
const score = Number(document.getElementById('playerScore').innerHTML);
const data = {
'score': score,
}
fetch(ajaxURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify(data),
})
}
Related
I am working on a javascript code and I am learning it for the first time I want to create a calculator and it should keep asking user for numbers and providing output until the user enters a specific number instead of number 1
The code:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<script>
const operator = prompt('Enter operator ( either +, -, * or / ): ');
// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));
let result;
if(number1 == '-999'){
document.write('The program is terminated');
}
else if (operator == '+') {
result = number1 + number2;
}
else if (operator == '-') {
result = number1 - number2;
}
else if (operator == '*') {
result = number1 * number2;
}
else {
result = number1 / number2;
}
document.write(`${number1} ${operator} ${number2} = ${result}`);
</script>
</body>
</html>
Create a while True loop and break out of it if if -999 is entered.
while (true) {
const operator = prompt('Enter operator ( either +, -, * or / ): ');
// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));
let result;
if(number1 == '-999'){
document.write('The program is terminated');
break;
}
else if (operator == '+') {
result = number1 + number2;
}
else if (operator == '-') {
result = number1 - number2;
}
else if (operator == '*') {
result = number1 * number2;
}
else {
result = number1 / number2;
}
document.write(`${number1} ${operator} ${number2} = ${result}`);
document.write("<br>");
}
This is not a direct answer but more of a preview of the sort of thing you'll be writing when you start making user interfaces in HTML rather than using modal dialogs.
It does demonstrate how to use a while loop to handle multiple values (which translates to multiple prompts in the case of your current interface).
//Identifies DOM elements, and defines an array and an error string
const
operatorSelect = document.getElementById("operator-select"),
numberInput = document.getElementById("number-input"),
enterButton = document.getElementById("enter-button"),
calculateButton = document.getElementById("calculate-button"),
resultDiv = document.getElementById("result-div"),
numbersArray = [],
DIV0_ERR = "Can't divide by zero";
// Calls `enter` or `calculate` whenever corresponding button is clicked
enterButton.addEventListener("click", enter);
calculateButton.addEventListener("click", calculate);
function enter(){
// Adds number to array, resets input, and clears resultDiv if necessary
const number = parseFloat(numberInput.value);
numbersArray.push(number);
numberInput.value = 0;
resultDiv.textContent = "";
}
function calculate(){
// Returns early if no numbers have been entered
if(numbersArray.length === 0){
return;
}
// Gets operator and first number, and prepares to loop through array
let
operator = operatorSelect.value,
resultSoFar = numbersArray[0],
currentIndex = 0,
currentNumber;
// Each iteration: increments index, gets number, updates `resultSoFar`
while(++currentIndex < numbersArray.length){
currentNumber = numbersArray[currentIndex];
resultSoFar = doOperation(operator, resultSoFar, currentNumber);
}
// Clears numbers Array and resets input
numbersArray.length = 0;
numberInput.value = 0;
// Returns most recent result from `doOperation`
resultDiv.textContent = resultSoFar;
}
function doOperation(op, num1, num2){
// Performs operation based on operator (or returns error string)
if(num1 === DIV0_ERR){ return DIV0_ERR; }
if(op === "+"){ return num1 + num2; }
if(op === "-"){ return num1 - num2; }
if(op === "*"){ return num1 * num2; }
if(op === "/"){ return (num2 === 0) ? DIV0_ERR : (num1 / num2); }
}
select, input, button, div{ display: block; width: 8rem; }
#operator-select, #calculate-button{ margin: 1rem 0; }
#result-div{ text-align: center; font-size: 1.8rem; }
Select an operation, enter numbers, then click "CALCULATE"
<select id="operator-select">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="number" id="number-input" value = "0" />
<button id="enter-button">ENTER</button>
<button id="calculate-button">CALCULATE</button>
<div id="result-div"></div>
I have a random number generator and a pick of one of the numbers inside. I'm trying to get the position of the number, So I used index.of() but it always shows '-1'.
I thought this would be the most direct way of finding the location of a particular number within an array. Am I wrong?
const shuffle = arr => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
console.log(r);
}
var selected = shuffle(arr).slice(0, 1);
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected) + "</p>");
Array.prototype.slice returns an array:
var selected = shuffle(arr).slice(0, 1)
Here, selected is now an array with a single element. But objects are never === to anything besides themselves, and since indexOf uses === to determine indicies, it'll always return -1.
Extract the first value from the shuffled array instead:
var selected = shuffle(arr)[0]
const shuffle = arr => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
}
var selected = shuffle(arr).slice(0, 1)[0];
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected) + "</p>");
slice returns an array, so you'll have to grab the first element, something like:
const shuffle = (arr) => {
let a = arr.slice(0); // take a copy
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
var r = Math.floor(Math.random() * UserNumber) + 1;
if (arr.indexOf(r) === -1) {
arr.push(r);
}
console.log(r);
}
var selected = shuffle(arr).slice(0, 1);
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected[0]) + "</p>");
I'm having issues with my JavaScript code and understanding JavaScript entirely in combination with HTML and CSS. It appears similar to programming in Java or C++, but I can't seem to get an output so I know it's different. It doesn't help that code editors point out errors due to it being confused between HTML syntax and JavaScript syntax. Here is my code below:
var num1;
var num2;
var i;
var square;
var cube;
var min;
var max;
//prompts user to input 2 numbers and then converts the string into integers
//Returns those numbers
function prompt1() {
do {
num1 - window.prompt("Please enter a number between 1 and 20");
number1 = parseInt(num1);
}
while (number1 < 1 || number1 > 20);
return number1
}
function prompt2() {
do {
num2 - window.prompt("Please enter a number between 1 and 20");
number2 = parseInt(num2);
}
while (number2 < 1 || number2 > 20);
return number2;
}
//Compares the 2 numbers plugged in and then compares them to get range
function listRange() {
if (number1 > number2) {
max += number1;
min += number2;
} else {
max += number2;
min += number1;
}
return min, max;
}
//Creates a table and uses range to fill data
function myTable() {
var tableDiv = document.getElementById("myTableDiv");
table.Div.innerHTML = "<table>" +
"<thead><th>Number</th><th>Square</th>" +
"<th> Cube </th> </thead>" +
"<tbody>" +
for (i = min; i <= max; i++) {
"<tr>< td>"
number += i + "</td><td>" +
square += i * i + "</td><td>"
cube += i * i * i +
"</td></tr>";
} +
"</tbody></table>";
table,
td {
border: 1px solid black;
}
I think below is what you want. There are lots of error in your code.
1) A syntax error.
2) There is no div with id "myTableDiv"
3) you just defined functios but never call them.
4) in prompt1 and prompt2 you have syntex somthing like num - window.prompt("Please enter a number between 1 and 20"); which is wrong.
5) You are doing "" without assigning it to anyone in myTable() function.
And there are few mores(mostly syntex)
var num1;
var num2;
var i;
var square;
var cube;
var min;
var max;
//prompts user to input 2 numbers and then converts the string into integers
//Returns those numbers
function prompt1() {
do {
num1 = window.prompt("Please enter a number between 1 and 20");
number1 = parseInt(num1);
}
while (number1 < 1 || number1 > 20);
}
function prompt2() {
do {
num2 = window.prompt("Please enter a number between 1 and 20");
number2 = parseInt(num2);
}
while (number2 < 1 || number2 > 20);
}
//Compares the 2 numbers plugged in and then compares them to get range
function listRange() {
if (number1 > number2) {
max = number1;
min = number2;
} else {
max = number2;
min = number1;
}
}
//Creates a table and uses range to fill data
function myTable() {
var tableDiv = document.getElementById("myTableDiv");
x = "<table>" +
"<thead><th>Number</th><th>Square</th>" +
"<th> Cube </th> </thead>" +
"<tbody>";
for (i = min; i <= max; i++) {
x+="<tr><td>"+ i + "</td><td>" + i * i + "</td><td>" + i * i * i +
"</td></tr>";
}
x+= "</tbody></table>";
tableDiv.innerHTML=x;
}
function init(){
prompt1();
prompt2();
listRange();
myTable();
}
onload=init;
table,
td {
border: 1px solid black;
}
<div id="myTableDiv"></div>
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
var double = 0;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
var double = double++; //<---increment double count
//Now reroll the dice, but if you hit 3 doubles in a row, you get message go to jail.
}
};
I want to know if I am going to need some loop...Please help me. This is part of a monopoly game. What do i have to add in the code, to make it loop if there is a double.
You only need to make an recursive call:
var dbl = 0;
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
dbl++; //<---increment double count
if(dbl%3==0) $('.out').attr('id', "jail");
//Now reroll the dice, but if you hit 3 doubles in a row, you get message go to jail.
rolldice();
}
};
I think you need to create something like this:
var double = 0;
function rolldice(){
var x = Math.floor(Math.random() * ((6-1)+1) + 1);
var y = Math.floor(Math.random() * ((6-1)+1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" +y);
if(x==y) {
if (double < 3) {
double++; // increase dobule
rolldice(); // Call rolldice again...
} else {
// Here there is 3 in a row....
}
}
}
This has some complications. When there is a change of player, you need to reset the value of your variable for checking double rolls.
Do the following:
var dblRolls;
function userChange(){//call this on change of user
dblRolls=0;
rollDice();
}
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
var double = 0;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
dblRoll++; //<---increment double count
if(dblRoll==3)
//jail
else
rollDice();
}
};
Don't use a loop.
Instead add the doubles counter as a parameter for the rolldice() function and call the function from within itself:
function rolldice(doubleCount) {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
doubleCount++;
if (doubleCount == 3)
{
//go to jail
}
else
{
rolldice(doubleCount);
}
}
};
The initial call for a player's first roll would look like rolldice(0);
Ok, besides this is more than two hours old and has already 4 answers, I want to add my 2 cents.
You state you want to make a Monopoly game. After most, if not all, dice rolls the player has to make decisions. That means after each roll you wait for user input (e.g., some button presses).
All other answers postet suggest to use recursive calls in some way. Instead I suggest to store the number of doubles alongside with the current player in some global variable. You do not use a loop, but instead something like:
var doubleCount = 0;
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
doubleCount++; //<---increment double count
if (doubleCount > 2) {
// Got to Jail
}
}
// Proceed as usual and come back to this, when the user presses the "Roll" Button again
};
This script works:
function rollDice(){
var dice1 = document.getElementById("dice1");
var dice2 = document.getElementById("dice2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
dice1.innerHTML = d1;
dice2.innerHTML = d2;
status.innerHTML = "You rolled "+diceTotal+".";
if(d1 == d2){
status.innerHTML += "<br />DOUBLES! You get a free turn!!";
}
}
This is one possible solution.
function rolldice(dbl=0){
var x = Math.floor(Math.random()*((6-1)+1) + 1);
var y = Math.floor(Math.random()*((6-1)+1) + 1);
if(x===y){
if(dbl!==3){
dbl++;
rolldice(dbl);
}else{
//goto jail
}
}else{
//no double
dbl=0;
}
}
or
function rolldice(dbl=0){
var x = Math.floor(Math.random()*((6-1)+1) + 1);
var y = Math.floor(Math.random()*((6-1)+1) + 1);
if(x===y&&dbl!==3)
dbl++;
rolldice(dbl);
}else if(x===y&&dbl===3){
//goto jail
}else{
//no double
dbl=0;
}
}
I'm trying to assign three random numbers to three variables (random1, random2, random3), and then assign these random variables to three elements. But I don't want any of them to be equal to the variable Sum which is the addition of two numeric innerHTML values.
So I have done that using do...while loop, but unfortunately the do...while loop doesn't work as expected .
Here is my code :
setTimeout(function () {
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 1000);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1500);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 2000);
}, 2000);
Looking at the code above, it seems to be impossible for the ch2.innerHTML, ch3.innerHTML and ch4.innerHTML to be equal to Sum, but when I test it the reality says something else. Why is this?
First thing, as many people mentioned, the sum variable is local to ApplySum so the rest of your code is referencing a global Sum variable instead (and it is "undefined" by default)
Another problem is that right now your do-while loop runs immediately, without waiting the 500 ms timeout and before Sum is assigned to a value. You can fix this by putting your code inside the settimeout callbacks:
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 500);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1000);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 1500);
}, 500);
(I also decreased 500ms from the other settimeouts to compensate for them being moved inside the first timeout)
Another tiny change you could consider is doing a separate loop for each variable instead of a single one for all of them.
var random1, random2, random3;
do { random1 = Math.floor((Math.random() * 3) + 1); } while (random1 == Sum);
do { random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4; } while (random2 == Sum);
do { random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7; } while (random3 == Sum);
The comments about scope seem like they're on the right track. Here's the relevant part of your code:
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
// Outside of your applySum function, Sum has no meaning
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
// Outside of your loop body, random1, random2, and random3 have no meaning
// undefined == undefined => true
Perhaps if you changed it to this:
var Sum = 0;
setTimeout(function applySUM() {
Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
var random1 = random2 = random3 = undefined;
do {
random1 = Math.floor((Math.random() * 3) + 1);
random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
Then your variables might have scope in the appropriate spots. Just a hunch, there might be something else wrong with this.