showing variable value in <p> paragraph using getElementById.innerHTML in Javascript - javascript

I'm trying to write a Blackjack code using Javascript, and showing the result in an HTML page. I have written the logic already, but I can't get to show the results in paragraph by ID, using getElementById.innerHTML. I don't know how to make it right. Could you please help me with this? I'm running out of time :(. here's the code:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
</body>
</html>

As #nnnnnn has mentioned that your html tags are not even loaded when your JS has executed and hence the issue. Try something like below to correct the issue:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
<script>
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</body>
</html>

your script is loading before the document that has the elements in it. Enclose your script in:
window.onload=function() {
//all of your JavaScript code
}

Related

How can I modify my HTML file with node.js?

require('dotenv').config()
var ComfyJS = require("comfy.js");
var firstplayer = document.getElementById("firstcharactername");
var maxPlayer = 0;
var totalAmount = 0;
var playerOne = "player1";
var playerTwo = "player2";
var playerOneScore = 0;
var playerTwoScore = 0;
var playerOneHealth = 50;
var playerTwoHealth = 50;
var playerOneTurnNumber = 1;
var playerTwoTurnNumber = 0;
function randomFunc(min, max)
{
return Math.floor(Math.random() * max) + min;
}
ComfyJS.onCommand = ( user, command, message, flags, extra ) => {
function rpsPicker()
{
var randomnumberRPS = randomFunc(1,3);
if(randomnumberRPS === 1)
{
ComfyJS.Say("#" + user + " Rock");
}
else if(randomnumberRPS === 2)
{
ComfyJS.Say("#" + user + " Paper");
}
else if(randomnumberRPS === 3)
{
ComfyJS.Say("#" + user + " Scissors");
}
}
function headtailPicker()
{
var randomnumberHeadTail = randomFunc(1,2);
if(randomnumberHeadTail === 1)
{
ComfyJS.Say("#" + user + " Heads");
}
else
{
ComfyJS.Say("#" + user + " Tail");
}
}
///////////////////////////////////////////////COMMANDS/////////////////////////////////////////////////
if( command === "roll1" && user === playerOne)
{
var randomNumber1 = randomFunc(2,11);
ComfyJS.Say("#"+user + " You've rolled two dices equals to " + randomNumber1+".");
playerOneScore += randomNumber1;
ComfyJS.Say("#"+user + "'s total amount is "+ playerOneScore);
}
else if(command === "roll2" && user === playerTwo)
{
var randomNumber2 = randomFunc(2,11);
ComfyJS.Say("#"+user + " You've rolled two dices equals to " + randomNumber2+".");
playerTwoScore += randomNumber2;
ComfyJS.Say("#"+user + "'s total amount is "+ playerTwoScore);
}
else if(command === "compare")
{
if(playerOneScore > playerTwoScore)
{
ComfyJS.Say(playerOne+" won.")
}
else
{
ComfyJS.Say(playerTwo+" won.")
}
}
else if (command === "joingame")
{
maxPlayer += 1;
if(maxPlayer === 1)
{
playerOne = user;
ComfyJS.Say("#"+user + " has joined the game " + ".");
firstplayer.innerText = user;
}
else if(maxPlayer === 2)
{
playerTwo = user;
ComfyJS.Say("#"+user + " has joined the game " + ".");
}
else if(maxPlayer > 2)
{
ComfyJS.Say("Max player limit!")
}
}
else if(command === "resetgame" && flags.broadcaster == true)
{
totalAmount = 0;
maxPlayer = 0;
playerOne = "player1";
playerTwo = "player2";
playerOneScore = 0;
playerTwoScore = 0;
}
else if (command === "rps")
{
rpsPicker();
}
else if (command === "flipcoin")
{
headtailPicker();
}
///////////////////////////////////////////////COMBAT GAME//////////////////////////////////////////////////////
else if( command === "attack1" && user === playerOne)
{
if (playerOneTurnNumber > 0)
{
var randomNumberAttack1 = randomFunc(5,12);
ComfyJS.Say("/me " + "#"+user + " hits "+ randomNumberAttack1 + " damage to his opponent.");
playerTwoHealth -= randomNumberAttack1;
ComfyJS.Say("/me " + "#"+playerTwo + "'s remaining health is " + playerTwoHealth);
playerOneTurnNumber -= 1;
}
else
{
ComfyJS.Say("/me It's not your turn.");
}
}
else if( command === "attack2" && user === playerTwo)
{
if (playerTwoTurnNumber > 0)
{
var randomNumberAttack2 = randomFunc(5,12);
ComfyJS.Say("/me " + "#"+user + " hits "+ randomNumberAttack2 + " damage to his opponent.");
playerOneHealth -= randomNumberAttack2;
ComfyJS.Say("/me " + "#"+playerOne + "'s remaining health is " + playerOneHealth);
playerTwoTurnNumber -= 1;
}
else
{
ComfyJS.Say("/me It's not your turn.");
}
}
else if( command === "endturn1" && user === playerOne)
{
ComfyJS.Say("/me " + playerOne + " ends his turn.");
playerTwoTurnNumber += 1;
}
else if( command === "endturn2" && user === playerTwo)
{
ComfyJS.Say("/me " + playerTwo + " ends his turn.");
playerOneTurnNumber += 1;
}
}
///////////////////////////////////////////WELCOMER/////////////////////////////////////////////////
ComfyJS.onJoin = ( user, self, extra ) =>
{
console.log(user);
ComfyJS.Say("#"+user+" Welcome!");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
ComfyJS.onChat = ( user, message, flags, self, extra ) =>
{
console.log( user, message, extra.userColor, flags.broadcaster);
}
ComfyJS.Init( process.env.TWITCHUSER, process.env.OAUTH, "shiftyshifterr" );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/comfy.js#latest/dist/comfy.min.js"></script>
<h1>TEST GAME</h1>
<div class="character-container">
<div class="first-character-container">
<p id="firstcharactername" class="first-character-name"></p>
<img src="firstplayer.gif" alt="firstplayer">
</div>
<div>
<img src="secondplayer.gif" alt="secondplayer">
<p id="secondcharactername" class="second-character-name"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I'm using node.js to build a twitch bot.
But when I try to modify my HTML via that javascript file I get an error like:
ReferenceError: the document is not defined
I've searched for it and found out that node.js is server sided so I can not use document.getElementById with it.
But I want to modify my HTML file by using that node.js javascript file.
Is there any way to do that and how?
What i'my trying to do here is that when they type joingame command user name will be written in p tag in my HTML file.
I'm pretty new to developing so sorry if I messed up with a question.
As you have correctly identified, you cannot reach document from server-side, because that only exists in the browser. You will need to parse the HTML if you want to work with it on Node JS, server-side.
You will need to install it like
npm install --save node-html-parser
and then you will be able to do something like
import { parse } from 'node-html-parser';
//Some code
var document = parse(yourhtml);
In this example -
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
https://expressjs.com/en/starter/hello-world.html
if you notice the res.send - you are sending the html there
If you post your nodejs snippets, we can work further.
document.getElementById interacts with your "HTML document" on runtime. If you need to edit your "HTML file" contents you need something like this:
var fs = require('fs');
fs.readFile('index.txt', 'utf-8', function(err, data) {
if (err) throw err;
var newValue = 'new content';
fs.writeFile('index.txt', newValue, 'utf-8', function(err, data) {
if (err) throw err;
console.log('Done!');
})
})
Source

JS Game Results Not What I Expect

I'm fairly new to JS and I'm currently trying to make my first simple game. The premise is that the player must choose and submit a bet. They then chose one of three cups and win if the ball is in the chosen cup.
It's mostly functioning as I hoped to except the outcome for how much money they gain.
The player starts with $40 and when its a loss it correctly subtracts the bet amount. When the player wins however it does not add the bet amount but instead puts it beside the previous amount.
For example, if the player has $40 and bets $5 and wins it will change their total to $405.
I have noticed that this does not happen for the first bet if the player wins but then does not work again on subsequent guesses.
I can not figure what is causing this behavior and any help would be greatly appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Hobo Balls</title>
<link rel="stylesheet" href="hobo.css">
</head>
<body>
<div class="header">
<h1>Hobo Balls</h1>
<h2>Instructions</h2>
</div>
<div class="cups">
<div id="cup1-image">
<img src="/Cup1.png">
</div>
<div id="cup2-image">
<img src="/Cup2.png">
</div>
<div id="cup3-image">
<img src="/Cup3.png">
</div>
</div>
<br>
<div>
<label for="bet">Place Your Bet</label>
<input name="bet" id="bet" type="number" min="1" max="400" value="0"/>
<input id="enter-bet" type="submit"/>
<p id="show-bet"></p>
</div>
<div class="result">
<h3>You are a ???</h3>
<p id="win-or-lose"></p>
</div>
<p id="cash"></p>
<script type="text/javascript" src="/hoboscript.js"></script>
</body>
</html>
JS
let cup1;
let cup2;
let cup3;
let playerGuess;
let playerBet;
let playerCash = 40;
let outcome;
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
//Determine ball position
const ballPlacement = () => {
const ballResult = Math.floor(Math.random() * 3);
console.log(ballResult);
if (ballResult === 0) {
cup1 = 'ball';
cup2 = 'crab';
cup3 = 'hobo';
} else if (ballResult === 1) {
cup1 = 'crab';
cup2 = 'ball';
cup3 = 'hobo';
} else { (ballResult === 2); {
cup1 = 'hobo';
cup2 = 'crab';
cup3 = 'ball';
}
}
};
//Determine if guess iscorrect and display result
const playerWin = () => {
//correct Guess
if (playerGuess === 'cup1' && cup1 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup1-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup2-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup3-image').innerHTML = '<img src="/ball.jpg">';
//incorrect guess
} else if (playerGuess === 'cup1' && cup1 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup1' && cup1 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/hobo.jpg">';
}
};
//Player selects cup, previous functions are called
document.getElementById("cup1-image").addEventListener("click", function () {
playerGuess = 'cup1';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup2-image").addEventListener("click", function () {
playerGuess = 'cup2';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup3-image").addEventListener("click", function () {
playerGuess = 'cup3';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
Here in your code:
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
The variable playerBet is being assigned a string value, change the statement to:
playerBet = parseInt(document.getElementById("bet").value;
Use valueAsNumber instead of value for number inputs:
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").valueAsNumber;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
})

Difficulty assigning a Discount

As the title says, I'm having trouble assigning discounts to my products. When I load the page it says nan and undefined. Any help is appreciated. Thankyou!
This is my JavaScript code:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
document.write("<br>");
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
document.write("Type of Products:" + ProductType);
document.write("<br>");
document.write("Number of Products:" + ProductQty);
document.write("<br>");
var GrossAmount =(ProductPrice) * (ProductQty);
document.write("Gross Amount is:" + GrossAmount);
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = (GrossAmount) - (GrossAmount) * (DiscountPercent)
var TotalAmount = (GrossAmount) * (DiscountPercent)
document.write("<br>");
document.write("Discount Amount:" + DiscountAmount)
document.write("<br>");
document.write("Discount Percent:" + DiscountPercent)
document.write("<br>");
document.write("Total Amount:" + TotalAmount)
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
}
else {
document.write("<br>");
document.write("Invalid Product Type");
document.write("<br>");
}
if (ProductQty <1|| ProductQty >100) {
document.write("Invalid Quantity")
}
}
function discountAmt() {
if (GrossAmount <200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount<=399.99) {
DiscountPercent = '.05';
} else if (GrossAmount>=400 && GrossAmount<=599.99 ) {
DiscountPercent = '.075';
} else if (GrossAmount >=600)
DiscountPercent = '.1';
}
This is my HTML Code:
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
Sorry for the confusion. I was mistaken about the unclosed function. Instead, the problem is that GrossAmount was defined in the calculate function instead of in the outer scope. Therefor, it was not reachable in the discountAmt function.
Here is your fixed code, except with the document.writes removed so that it can run in the sandbox:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
var GrossAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
GrossAmount = ProductPrice * ProductQty;
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = GrossAmount - GrossAmount * DiscountPercent;
var TotalAmount = GrossAmount * DiscountPercent;
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
} else {}
if (ProductQty < 1|| ProductQty > 100) {}
console.log('ProductPrice: ', ProductPrice);
}
function discountAmt() {
if (GrossAmount < 200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount <= 399.99) {
DiscountPercent = '.05';
} else if (GrossAmount >= 400 && GrossAmount <= 599.99) {
DiscountPercent = '.075';
} else if (GrossAmount >= 600) {
DiscountPercent = '.1';
}
console.log('DiscountPercent: ', DiscountPercent);
}
calculate();
Obviously you are not closing the elsestatement function ie } is missing. and manage the code like this
change
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
to
<!DOCTYPE html>
<html>
<title>Product</title>
<script src="Product.js"> </script>
<body>
<h1>Product Calc</h1>
</body>
<script>
$(function(){
calculate();
});
</script>

Ignore user input after certain point

Is there a way I can kill / break out of user input on my tic tac toe board after a winner has been declared? I tried using break in the isFull() function after the alert was sent of who won but it still would accept user input in the table afterwords.
Here is a link to show you it running:
https://jsfiddle.net/n1kn1vLh/2/
function TicTacToe() {
this.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
this.showhtml = toHTML;
this.player2 = "O";
this.player1 = "X";
this.turn = "";
}
function toHTML() {
var player = '';
var displayplayer = document.getElementById("displayMessage");
var htmlStr = '';
var gametable = document.getElementById("tictable");
var cell = '';
for (var i = 0; i < this.board.length; i++) {
htmlStr += '<tr>';
for (var j = 0; j < this.board[i].length; j++) {
if (this.board[i][j] == 0) {
this.board[i][j] = cell;
htmlStr += ("<td data-i=\"" + i + "\" data-j=\"" + j + "\">" + this.board[i][j] + "</td>");
}
gametable.addEventListener("click", clickHandler, false);
}
htmlStr += '</tr>';
}
gametable.innerHTML = htmlStr;
if (this.turn == this.player1 || this.turn == "") {
player += ("<p>It is " + this.player1 + "'s turn.</p>");
displayplayer.innerHTML = player;
return this.turn = "X";
} else {
player += ("<p>It is " + this.player2 + "'s turn.</p>");
displayplayer.innerHTML = player;
return this.turn = "O";
}
function clickHandler(event)
{
if (tic.turn == tic.player1) {
if (event.target.innerHTML == ''){
event.target.innerHTML = tic.turn;
tic.board[event.target.dataset.i][event.target.dataset.j] = tic.turn;
tic.turn = tic.player2;
document.getElementById("displayMessage").innerHTML = "<p>It is " + tic.turn + "'s turn.</p>";
isFull();
return tic.turn;
} else {
alert('Invalid Move! Try again.');
}
} else {
if (event.target.innerHTML == '') {
event.target.innerHTML = tic.turn;
tic.board[event.target.dataset.i][event.target.dataset.j] = tic.turn;
tic.turn = tic.player1;
document.getElementById("displayMessage").innerHTML = "<p>It is " + tic.turn + "'s turn.</p>";
isFull();
return tic.turn;
} else {
alert('Invalid Move! Try again.');
}
}
}
function isFull() {
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[i][0] == tic.board[i][1] && tic.board[i][0]==tic.board[i][2] && tic.board[i][0]!=0){
alert(tic.board[i][0]+" Wins");
return;
}
}
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[0][i] == tic.board[1][i] && tic.board[0][i]==tic.board[2][i] && tic.board[0][i]!=0){
alert(tic.board[0][i]+" Wins");
return;
}
}
if(tic.board[0][0]==tic.board[1][1] && tic.board[0][0] == tic.board[2][2] && tic.board[0][0]!=0){
alert(tic.board[0][0]+" Wins");
return;
}
if(tic.board[0][2]==tic.board[1][1] && tic.board[0][2] == tic.board[2][0] && tic.board[2][0]!=0){
alert(tic.board[1][1]+" Wins");
return;
}
}
}
tic = new TicTacToe();
tic.showhtml();
You can remove the eventListener when someone wins:
function isFull() {
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[i][0] == tic.board[i][1] && tic.board[i][0]==tic.board[i][2] && tic.board[i][0]!=0){
alert(tic.board[i][0]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[0][i] == tic.board[1][i] && tic.board[0][i]==tic.board[2][i] && tic.board[0][i]!=0){
alert(tic.board[0][i]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
if(tic.board[0][0]==tic.board[1][1] && tic.board[0][0] == tic.board[2][2] && tic.board[0][0]!=0){
alert(tic.board[0][0]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
if(tic.board[0][2]==tic.board[1][1] && tic.board[0][2] == tic.board[2][0] && tic.board[2][0]!=0){
alert(tic.board[1][1]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
add the following in you isFull()
document.getElementById('user input').disabled = true;

Javascript Page Reset

Im trying to get my page to reset to its original layout once the popup goes away after 5 seconds. I've tried setTimeOut(fullReset(true), messageHIde, 5000) but that stops the pop up from working.I know how to get it back to its original layout if it was the case of using a button. Any tips about how to get it working? My java script is below for the popup and the fullReset.
if ((playerChoice == "higher") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
/* increase the score by 5 because the user won */
total = total + 5;
}
else if ((playerChoice == "higher") && (computerCard > playerCard))
{
document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;
}
else if ((playerChoice == "equal") && (playerCard > computerCard))
{ document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total +5 ; }
else if ((playerChoice == "equal") && (computerCard > playerCard))
{ document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
else if ((playerChoice == "lower") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total + 5;}
else if ((playerChoice =="lower") && (computerCard > playerCard))
{document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
/* display the new total */
alert(total + " " + playerChoice + " " + playerCard + " " +computerCard);
document.getElementById('score').innerHTML = total;
}
function messageHide(){
document.getElementById('popup').style.display = "none";
}
function fullReset(){
document.getElementById('img1').src = 'back.gif';
document.getElementById('img2').src = 'back.gif';
document.getElementById('higherButton').style.backgroundColor = "white";
document.getElementById('lowerButton').style.backgroundColor = "white";
document.getElementById('equalButton').style.backgroundColor = "white";
document.getElementById('drawButton').style.backgroundColor = "white";
document.getElementById('score').innerHTML = "0" +total;
startButton.disabled = false;
higherButton.disabled = true;
lowerButton.disabled = true;
equalButton.disabled = true;
drawButton.disabled = true;
}
Use
setTimeOut(function(){
messageHide();
fullReset();
}, 5000);

Categories

Resources