I am trying to add +1 to the win counter every time a win occurs but it doesn't work no matter what I try.
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="center">
<button onclick="myFunction1()">Play</button>
<p id="rolled">You rolled:</p>
<p id="test"></p>
<p id="rolled1">Your opponent rolled:</p>
<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<br><br><br>
<span>Wins:</span><span id="span1"></span><br>
<span>Losses:</span><span id="span2"></span><br>
<span>Draws:</span><span id="span3"></span>
</div>
</body>
</html>
Javascript:
var things = [ 'rock', 'paper', 'scissors'];
function myFunction1() {
var random1 = Math.floor((Math.random()*things.length));
var random2 = Math.floor((Math.random()*things.length));
document.getElementById("test").innerHTML=things[random1];
document.getElementById("test1").innerHTML=things[random2];
document.getElementById("test2").innerHTML='';
document.getElementById("test3").innerHTML='';
document.getElementById("span1").innerHTML=win;
document.getElementById("span2").innerHTML=loss;
document.getElementById("span3").innerHTML=draw;
if (random1 == random2) {
document.getElementById("test2").innerHTML="<h3>It's a draw.</h3>";
}
else if (random1 == 0 && random2 == 2) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 1 && random2 == 0) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 2 && random2 == 1) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 0 && random2 == 1) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 1 && random2 == 2) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 2 && random2 == 0) {
document.getElementById("test3").innerHTML="You lost!";
}
var test3 = document.getElementById("test3");
var win = 0;
var loss = 0;
var draw = 0;
Here is where I want to add +1 to the win counter every time a win occurs, but I can't get it to work. I have tried this:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win + 1;
}
This:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win++;
}
And this:
if (test3.innerHTML == "You win!") {
win = win + 1;
}
} //End of myFunction1
What am I doing wrong exactly?
You did not declare the variable outside the function, Declare the win variable outside the function with 0 default value. eg:-
var win = 0;
function myFunction1() {
if (test3.innerHTML == "You win!") {
win = win + 1;
....
UPDATE
Here is the fixed version DEMO
Define var win=0; outside of your function, as it is now your win variable is being created in the function and dying at the end of the function.
Another thing that you can do is: inside the function add this at the top:
var win=parseInt(document.getElementById('span1').innerText);
is test3 defined?
if (test3.innerHTML == "You win!") {
}
if not, use
if (document.getElementById("test3").innerHTML == "You win!") {
}
Related
this is my first question on stackoverflow.
I am learning about javascript and decided to start a project.
I'm making a scoreboard to keep track of the score during table tennis. I managed to make this work and decided to add some features like a match history and show which player has to serve.
However, I'm stuck with the ReferenceError. In most other questions about this, people just forgot to add the variable or it had something to do with jquery. I don't think that's my problem.
In table tennis the player with serve changes every 2 points. I decided to add scorePlayer1 and scorePlayer2 to make a totalScore. When this is divided by 2, I can check if this is an integer, and if it is, the player with serve changes. However, whatever I try, the variable totalScore is not defined.
I learned HTML/CSS first at w3schools.com and later used it to learn javascript.
I have pasted the code into multiple syntax checkers, but got no errors.
The button is there to pick the serve player. Then, I want to swith the right to serve to the opposite player after 2 points are scored. I tried this with function changeServePlayer. However, when I try this in Chrome and type in the console: totalScore, it returns the Uncaught ReferenceError. Why does this happen or is there a better way to achieve the goal?
Here's code I used:
var currentScorePlayerOne = 0;
var currentScorePlayerTwo = 0;
var currentServePlayer;
var totalScore;
window.addEventListener("keyup", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "90" && currentScorePlayerOne != 0) { //Z
document.getElementById('scorePlayerOne').innerHTML = --currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "88") { //X
document.getElementById('scorePlayerOne').innerHTML = ++currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "78" && currentScorePlayerTwo != 0) { //N
document.getElementById('scorePlayerTwo').innerHTML = --currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "77") { //M
document.getElementById('scorePlayerTwo').innerHTML = ++currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
updateSet();
}
function updateSet() {
if (currentScorePlayerOne > 10 && currentScorePlayerOne > currentScorePlayerTwo + 1) {
resetScores();
}
if (currentScorePlayerTwo > 10 && currentScorePlayerTwo > currentScorePlayerOne + 1) {
resetScores();
}
}
function resetScores() {
currentScorePlayerOne = 0;
currentScorePlayerTwo = 0;
document.getElementById('scorePlayerOne').innerHTML = currentScorePlayerOne;
document.getElementById('scorePlayerTwo').innerHTML = currentScorePlayerTwo;
}
function changeServePlayer() {
totalScore = currentScorePlayerOne + currentScorePlayerTwo;
Number.isInteger(totalScore / 2);
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 1) {
currentServePlayer = 2;
}
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 2) {
currentServePlayer = 1;
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
<!DOCTYPE html>
<html>
<head>
<script src="Scoreboard1javascript.js"></script>
</head>
<body>
<button type="button" onclick="chooseServingPlayer()">
Serve
</button>
<script>
var randomServeNumber;
function chooseServingPlayer() {
if (currentScorePlayerOne == 0 && currentScorePlayerTwo == 0) {
document.getElementById('serveP1').style.opacity = "0.2";
document.getElementById('serveP2').style.opacity = "0.2";
randomServeNumber = Math.floor(Math.random() * 10);
if (randomServeNumber > 5) {
currentServePlayer = 1;
changeServeIcon();
} else {
currentServePlayer = 2;
changeServeIcon();
}
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
</script>
<nav>
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP1"> Score P1
</nav>
<nav>
Score P2
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP2">
</nav>
<nav id="scorePlayerOne" style="font-size: 50px">
0
</nav>
<nav id="scorePlayerTwo" style="font-size: 50px">
0
</nav>
</body>
</html>
I forgot to check which file I was referencing in my html script. I was referencing an old version of the javascript, which made every change I made in javascript useless.
It can be really that stupid sometimes...
I am currently creating a dice game where you roll two dice and the javascript decides whether you won lost or tied with the computer. It is simple code, but I am unsure as to if I have made a syntax error or the code itself.
I have already tried looking over the code, but I am fairly new to this and some professional eyes would be useful.
<!DOCTYPE html>
<html>
<head>
<title> Game of dice </title>
<script>
var player;
var computer;
function randDice() {
var number = randNum(1,6);
return number;
}
function rollDice(){
player = randDice();
computer = randDice();
if (player == 1) {
document.getElementById("dieOne").src= "die1.png"
} else if (player == 2) {
document.getElementById("dieOne").src= "die2.png"
} else if (player == 3) {
document.getElementById("dieOne").src= "die3.png"
} else if (player == 4) {
document.getElementById("dieOne").src= "die4.png"
} else if (player == 5) {
document.getElementById("dieOne").src= "die5.png"
} else (player == 6) {
document.getElementById("dieOne").src= "die6.png"
if (computer == 1) {
document.getElementById("dieTwo").src= "die1.png"
} else if (computer == 2) {
document.getElementById("dieTwo").src= "die2.png"
} else if (computer == 3) {
document.getElementById("dieTwo").src= "die3.png"
} else if (computer == 4) {
document.getElementById("dieTwo").src= "die4.png"
} else if (computer == 5) {
document.getElementById("dieTwo").src= "die5.png"
} else (computer == 6) {
document.getElementById("dieTwo").src= "die6.png"
checkWin();
}
function checkWin(){
if (player == computer){
document.getElementById("winner").innerHTML = "You tied";
} else if (player > computer){
document.getElementById("winner").innerHTML = "You-won!";
} else (player < computer){
document.getElementById("winner").innerHTML = "You-lost";
}
}
</script>
</head>
<body>
<h1> Die roll </h1>
<img src="die1.png" id="dieOne"><image>
<img src="die2.png" id="dieTwo"><image>
<br>
<br>
<button onClick="rollDice();">Roll</button>
<br>
<p id="winner"></p>
</body>
</html>
There are some error in your source code:
Missing } in function rollDice
You wrong else if condition else (player == 6)
Put script tag in head, need move to close body tag.
Also check refer for randNum() method
You can F12 and see console tab for detail error message at what line of code.
<!DOCTYPE html>
<html>
<head>
<title> Game of dice </title>
</head>
<body>
<h1> Die roll </h1>
<img src="die1.png" id="dieOne"><image>
<img src="die2.png" id="dieTwo"><image>
<br>
<br>
<button onClick="rollDice();">Roll</button>
<br>
<p id="winner"></p>
<script>
var player;
var computer;
function randDice() {
var number = randNum(1,6);
return number;
}
function rollDice(){
player = randDice();
computer = randDice();
if (player == 1) {
document.getElementById("dieOne").src= "die1.png"
} else if (player == 2) {
document.getElementById("dieOne").src= "die2.png"
} else if (player == 3) {
document.getElementById("dieOne").src= "die3.png"
} else if (player == 4) {
document.getElementById("dieOne").src= "die4.png"
} else if (player == 5) {
document.getElementById("dieOne").src= "die5.png"
} else if(player == 6) {
document.getElementById("dieOne").src= "die6.png"
}
if (computer == 1) {
document.getElementById("dieTwo").src= "die1.png"
} else if (computer == 2) {
document.getElementById("dieTwo").src= "die2.png"
} else if (computer == 3) {
document.getElementById("dieTwo").src= "die3.png"
} else if (computer == 4) {
document.getElementById("dieTwo").src= "die4.png"
} else if (computer == 5) {
document.getElementById("dieTwo").src= "die5.png"
} else if(computer == 6) {
document.getElementById("dieTwo").src= "die6.png"
checkWin();
}
}
function checkWin(){
if (player == computer){
document.getElementById("winner").innerHTML = "You tied";
} else if (player > computer){
document.getElementById("winner").innerHTML = "You-won!";
} else if(player < computer){
document.getElementById("winner").innerHTML = "You-lost";
}
}
</script>
</body>
</html>
i've done this game before this was my code
<html>
<head>
<script>
var roll1;
var roll2;
function rollTheDice()
{
roll1 = Math.floor(Math.random() * 6) + 1;
document.getElementById('imgDice').src = roll1 + ".jpg";
return roll1;
}
function rollTheDice2()
{
roll2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('imgDice2').src = roll2 + "a.jpg";
return roll2;
}
function compareDice()
{
if (roll1 < roll2 ) {alert("You Loose")
;
} else if (roll1 > roll2 ) {
alert ("You Win")
;
} else {alert ("You Tie")
;
}
}
</script>
</head>
<body>
<input type="button"
onclick="rollTheDice();"
value="Get Your Die"/>
<img src="" id="imgDice"/>
<br>
<input type="button"
onclick="rollTheDice2();"
value="Choose Opponent's Die"/>
<img src="" id="imgDice2"/>
<br>
<input type="button"
onclick="compareDice();"
value="Who wins?"/>
<img src="" id="imgDice"/>
</body>
</html>
I have written a rock, paper, scissor game using javascript. I have got it to play 5 rounds and to keep track of the score every round. However, for some reason every now and then it will add 2 points to the score instead of 1. I am a beginner to javascript and have no idea where I am going wrong. I keep logically going through my loop and don't understand why it does this. How can I stop this from happening?
Help would be greatly appreciated!
let playerScore = 0;
let compScore = 0;
let draw;
/* Players Choice */
function round() {
let userInput = prompt('Rock, Paper, or Scissor?: ');
console.log(userInput);
if (userInput == 'rock'){
console.log(userInput = 1);
} else if (userInput == 'paper'){
console.log(userInput = 2);
} else if (userInput == 'scissor'){
console.log(userInput = 3);
}
/* Computers Choice */
let compMove = Math.floor(Math.random()*3) + 1;
console.log(compMove);
if (compMove == 1) {
alert('Rock!');
} else if (compMove == 2){
alert('Paper!');
} else if (compMove == 3){
alert('Scissor!');
}
return {
compMove,
userInput
};
};
/* Compare */
function result(compMove, userInput) {
if (compMove == 2 && userInput == 1) {
alert('You lose!');
compScore += 1;
} else if (compMove == 3 && userInput == 1){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 2){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 3){
alert('You Lose!')
compScore += 1;
} else if (compMove == userInput){
compScore;
playerScore;
}
return {
compScore,
playerScore
};
}
function game() {
for (let i=1; i <= 5; i++) {
let roundNumber = round();
result(roundNumber.compMove, roundNumber.userInput);
console.log(result(compScore, playerScore));
};
return {
compScore,
playerScore
};
};
console.log(game());
if (playerScore > compScore) {
alert('You Won the Best of 5!');
} else if (playerScore < compScore) {
alert('You Lost.')
} else {
alert('It is a Draw!');
}
You have made calls to result() twice in game(). Store the result() in a
const and put that in console.log.
Also, in the result function, you haven't really covered all the possibilities of outcomes by computer and the user. You should cover the cases where userInput is 2 and compMove is 3, also where userInput is 3 and compMove is 2.
I've written a javascript function with some variables, i've tried to test it to see if variables would show in my HTML document but they wont and i have no idea why. Specifically, i'm trying to insert variable currentScore which is set to 0 at the beginning, so it should show 0 in a textbox, but it doesnt appear there.
Here is my javascript :
var who = 0;
var decision = 0;
var diceOne = 0;
var diceTwo = 0;
var currentScore = 0;
player playerAI = new player;
player playerOne = new player;
document.getElementById('currentScore').value = currentScore;
function rollDice() {
diceOne = Math.round(6 * Math.Random() + 1);
diceTwo = Math.round(6 * Math.Random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
game();
}
}
function game() {
if (decision == 1) {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
decision = 0;
makeMove();
}
if (diceOne == 1 || diceTwo == 1){
currentScore = 0;
decision = 0;
who = 1 - who;
makeMove();
}
if (diceOne == 1 && diceTwo == 1) {
currentScore = 0;
if (who == 0) {
playerAI.totalScore = 0;
}
else {
playerOne.totalScore = 0;
}
decision = 0;
who = 1 - who;
makeMove();
}
}
if(decision == -1) {
if (who == 0){
playerAI.totalScore += currentScore;
playerAI.checkScore();
}
else {
playerOne.totalScore += currentScore;
playerOne.checkScore();
}
currentScore = 0;
decision = 0;
who = 1 - who;
}
}
function aiStrat() {
if (playerAI.totalScore < 60) {
if (currentScore < 30) {
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 60 && playerAI.totalScore < 80) {
if (currentScore < 20){
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 80){
if (currentScore < 10) {
decision = 1;
}
else {
decision = -1;
}
}
}
var player {
var totalScore = 0;
var playing = true;
function checkScore() {
if (totalScore >= 100) {
playing = false;
}
};
};
And my HTML document is this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="BigPig.css">
<script type="text/javascript" src="VorgurakendusedKD1\Vorgurakendused.js" ></script>
</head>
<body onload="javascript:mainFunction()">
<div class="centered" type="text/javascript">
<h1>BIG PIG</h1>
<button><input type="button" value="START FROM BEGINNING" onclick="mainFunction();">
<span></span></button>
<br>
<button><span>GREEN BUTTON</span></button>
<br>
<button><span>RED BUTTON</span></button>
<br>
<output class="textbox" type="text/javascript" id="currentScore">CURRENTSCORE:
</output>
<br>
<output class="textbox" type="text">CPU SCORE: </output>
<br>
<output class="textbox" type="text">PLAYER SCORE: </output>
<br>
<p>Player versus computer</p>
<br>
<p id="currentScore"></p>
</div>
</body>
</html>
Here: document.getElementById('currentScore').value = currentScore;you try to find an element before it has loaded, and that's why you can't assign a value to it.
Try putting document.getElementById('currentScore').value = currentScore; inside your onload-function, mainFunction()
When X,Y, and Z are equal to 3 then locationName should be equal to Sol, but this is not the case. I believe the problem is with my variable name not being updated but it could be something else.
<!DOCTYPE html>
<html>
<head>
<title>Jordan's Space Explorer </title>
</head>
<body>
<button onclick="goNorth()">Go North</button>
<button onclick="goSouth()">Go South</button>
<button onclick="goEast()">Go East</button>
<button onclick="goWest()">Go West</button>
<button onclick="goUp()">Go Up</button>
<button onclick="goDown()">Go Down</button>
<button onclick="locationQuery()">Where am I?</button>
<button onClick="quit"()>Quit</button>
</body>
<script>
// Confirm user wants to play.
confirm("Do you want to play Jordan's Space Explorer?");
alert("The game is working.");
// Declare start location.
var locationY = 0;
var locationX = 0;
var locationZ = 0;
var locationName = "in Space";
//Go directions
function goNorth(){
locationY ++;
console.log("You head North.");
}
function goSouth(){
locationY --;
console.log("You head South.");
}
function goEast(){
locationX ++;
console.log("You head East");
}
function goWest(){
locationX --;
console.log("You head West");
}
function goUp(){
locationZ ++;
console.log("You go up.");
}
function goDown(){
locationZ --;
console.log("You go down.");
}
function locationQuery(){
console.log("X" +locationX);
console.log("Y" +locationY);
console.log("Z" +locationZ);
console.log("You are " +locationName);
}
// Encounters
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
</script>
</html>
I am new to programming and would appreciate any help.
The problem is that you execute your // Encounters part only once, at initialization. You should put it in a function :
function encounters(){
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
}
and call that function every time you change the position :
function goDown(){
locationZ --;
console.log("You go down.");
encounters();
}
Try with,
function locationQuery(){
console.log("X" +locationX);
console.log("Y" +locationY);
console.log("Z" +locationZ);
// Encounters
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
console.log("You are " +locationName);
}
Update locationName against given condition by invoking locationQuery() function