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

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

Related

Discord.js Bot getting offline without any errors

i've created bot for analyze PUBG stats and set up specific role based on stats.
Last time i added check for casual mode, bot is checking last 25games of player and check if there were more than 85% bots. On small group of players it worked good but know i'm caching up around 200players and bot just going offline without any errors. Im using premium account on replit.com to keep him 24h up, stoping and starting again fixes the problem till next loop. Im not running out the session limits from disocrd
Discord.js debug don't show errors.
image
Dicord_Bot.on("debug", (e) => console.log(e))
exports.run = async (bot, message, args) => {
var membersArray = message.guild.members.cache;
const insertInto = bot.dbsql2.prepare('INSERT INTO testo(nickname, pubg_id, match_id , assists, damageDealt, headshotKills, kills, win) VALUES (?,?,?,?,?,?,?,?)');
for (let [snowflake, guildMember] of membersArray) {
if (guildMember.user.bot) {
continue;
}
var nickname = guildMember.nickname;
if (!nickname)
nickname = guildMember.user.username;
console.log("Sprawdzam " + nickname);
var matchesList = bot.pubgAPI.getPlayerMatchesList(bot, nickname);
var pubgID = bot.pubgAPI.getPlayerID(bot, nickname);
if(pubgID === 0 || pubgID === -1) {
continue;
}
for (let i = 0; i <= 25; i++) {
var participants = 0;
var bots = 0;
var players = 0;
var lastStats = [0, 0, 0, 0, 0, 0, 0];
if (matchesList[i] === undefined) {
console.log("Brak meczu");
continue;
}
var matchStats = bot.pubgAPI.getMatchStats(bot, matchesList[i].id)
if (matchStats === undefined) {
console.log("Brak stat");
continue;
}
if (matchStats.data === undefined) {
console.log("Brak daty");
continue;
}
if (matchStats.data.attributes === undefined) {
console.log("Brak atrybutow");
continue;
}
if (matchStats.data.attributes.stats === undefined) {
console.log("Brak statow");
continue;
}
if (matchStats.data.attributes.gameMode === "squad" && matchStats.data.attributes.matchType === "official") {
for (let j = 0; j < matchStats.included.length; j++) {
if (matchStats.included[j] === undefined) {
continue;
}
if (matchStats.included[j].attributes === undefined) {
continue;
}
if (matchStats.included[j].attributes.stats === undefined) {
continue;
}
if (matchStats.included[j].type === "participant") {
participants++;
if (matchStats.included[j].attributes.stats.playerId.includes("ai.")) {
bots++;
}
else {
players++;
}
}
if (matchStats.included[j].attributes.stats.playerId === pubgID) {
lastStats[0] += matchStats.included[j].attributes.stats.assists
lastStats[1] += matchStats.included[j].attributes.stats.damageDealt
lastStats[2] += matchStats.included[j].attributes.stats.headshotKills
lastStats[3] += matchStats.included[j].attributes.stats.kills
if (matchStats.included[j].attributes.stats.winPlace === 1) {
lastStats[6] += 1
}
else {
lastStats[4] += 1
}
lastStats[5] += 1
}
}
if (((bots / participants) >= 0.50)){
var returnMessage = "**" + nickname + "**" + " miał " + ((bots / participants) * 100).toFixed(2) + "% botów.";
returnMessage += "\n**Usuwamy ze statystyk:**";
returnMessage += "\nDamage:" + lastStats[1].toFixed(2)
returnMessage += "\nAsysty:" + lastStats[0]
returnMessage += "\nHeadshoty:" + lastStats[2]
returnMessage += "\nKille:" + lastStats[3]
if (lastStats[6] != 0) {
returnMessage += "\nWin:1"
}
bot.channels.cache.get("952186890499530792").send(returnMessage);
insertInto.run(nickname,pubgID,matchesList[i].id,lastStats[0],lastStats[1],lastStats[2],lastStats[3],lastStats[6])
}
}
var sleep1 = await bot.sleepFor(10);
}
var sleep = await bot.sleepFor(1000)
}
}
exports.help = {
name: "test",
channel: "952186890499530792",
members: ["248165905119313948"]
}

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;
})

Use While Loop With setTimeout

I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:
function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
var ibumped = i + 1;
console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
var weaponChoice = prompt("Which weapon do you choose?");
switch (weaponChoice) {
case 1:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
break;
case 2:
weaponChosen = userWeapons[1];
console.log(userWeapons[1].name + " chosen.");
break;
default:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
};
}, 1000);
setTimeout(function() {
if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
enemy.shields = enemy.shields - weaponChosen.damage;
weaponChosen.fire(enemy);
if (enemy.shields < 0) {
enemy.health = enemy.health + enemy.shields;
console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
} else {
console.log("Enemy shields have been reduced to " + enemy.shields + ".");
}
} else {
enemy.health = enemy.health - weaponChosen.damage;
weaponChosen.fire(enemy);
console.log("Enemy takes " + weaponChosen.damage + " damage!");
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
}
}, 3000);
setTimeout(function() {
if (enemy.health > 0 && battleOver === false) {
if (enemy.weapons != null) {
console.log(enemy.weapons.name + " fired at you.");
health = health - enemy.weapons.damage;
console.log("You have " + health + " health left.");
if (health <= 0) {
console.log("Game over... You were destroyed");
battleOver = true;
}
} else {
console.log("The enemy did nothing...");
}
};
}, 5000);
}
}
All help is appreciated!
Things start getting very tricky when you use setTimeout. Most games will have a "main game loop" that runs 60 times a second.
Try using a main game loop and cooldowns.
Here's an example of how you could restructure the program.
var timeForOneFrame = 1000/60 // 60 Frames per second
var enemy;
var battleOver;
function initGame() {
/*
Initialize the enemy etc.
*/
}
function gameLoop() {
battle(enemy);
}
function battle(enemy) {
/*
Do all the battle stuff, this function is called 60 times a second-
there's no need for setTimeout!
*/
// If you want an enemy to only be able to attack every 2 seconds, give them
// a cooldown...
if (enemy.cooldown <= 0) {
// Attack!
enemy.cooldown += 2000
} else {
enemy.cooldown -= timeForOneFrame
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
clearInterval(gameLoopInterval)
}
}
initGame();
var gameLoopInterval = setInterval(gameLoop, timeForOneFrame);
A while loop blocks the whole page until it ends, and as your loop never exits its infinite. You may replace it with a high speed interval:
const loop = setInterval( function(){
if( battleOver ) return clearInterval(loop);
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
console.log("Press " + (i + 1) + " to fire the " + userWeapons[i].name + ".");
}
},10);
I would take that loop out and use a recursive call on the end of the interactions.
Let's say:
function battle(enemy) {
//All your code here
if (HeroAlive) {
battle(enemy);
}
}

showing variable value in <p> paragraph using getElementById.innerHTML in 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
}

Javascript code broken

This is my first attempt at a little more complex code structure. The thing is my IDE says it technically works , jsfiddle says it doesn't, it actually initializes only the two confirm functions that I declared "confirmUserName();" and "confirmFullName();"
Can someone explain why i did such a horrible job.
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList); v
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if(list.length == 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = usrName;
return list;
} else if(i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery; /
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm == true) {
return startRide;
} else {
return fullnameQuery;
}
}
if(username == undefined) {
usernameQuery = function() {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function() {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if(fullname == undefined) {
fullnameQuery = function() {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function() {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();
There is a lot wrong with the code you posted -- I'll just take one chunk:
function confirmUserName() {
// The return value of `confirm` is ignored.
confirm("Is " + username + " your first choice?");
// confirmUserName is the name of your function.
// You sould be using `===` instead of `==`
// Or, not comparing against true at all.
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
Fixed function:
function confirmUserName() {
var res = confirm("Is " + username + " your first choice?");
if (res) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
It does not throw Errors with this, but I dont know in which situation you want your code to be implemented and what it should do, I hope this is what you need:
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList);
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if (list.length === 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if (list[i] === undefined) {
list[i] = usrName;
return list;
} else if (i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName === true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery;
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm === true) {
return startRide;
} else {
return fullnameQuery;
}
}
if (username === undefined) {
usernameQuery = function () {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function () {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if (fullname === undefined) {
fullnameQuery = function () {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function () {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

Categories

Resources