Blackjack Javascript problem dealer has 3 cards only needs to have 2 - javascript

This is my first post. I'm new to coding and one of my projects is to create a simple version of Blackjack using Javascript. I made a basic website for it here and I've encountered a problem. The dealer occasionally gets dealt 3 or more cards. The dealer should always have 2 cards. (unless you hit or stay.) Adding cards to the dealer like the player isn't required so I did not write code for it. I have the dealer sum limit set to 13 (I've tried lower/higher numbers, but that doesn't really "fix" the issue.") and also edited the for loops. I thought it could be an array problem. Perhaps I have the arrays too simplified and need to rename the cards?
Here is my code any help or tips would be appreciated!
var dealerSum = 0;
var yourSum = 0;
var dealerAceCount = 0;
var yourAceCount = 0;
var hidden;
var deck;
var canHit = true;
window.onload = function () {
buildDeck()
shuffleDeck()
startGame()
}
function buildDeck() {
let values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
let types = ["C", "D", "H", "S"]
deck = []
for (let i = 0; i < types.length; i++) {
for (let j = 0; j < values.length; j++) {
deck.push(values[j] + "-" + types[i]);
}
}
// console.log(deck);
}
function shuffleDeck() {
for (let i = 0; i < deck.length; i++) {
let j = Math.floor(Math.random() * deck.length);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
// console.log(deck);
}
function startGame() {
hidden = deck.pop();
dealerSum += getValue(hidden);
dealerAceCount += checkAce(hidden);
// console.log(hidden);
// console.log(dealerSum);
while (dealerSum < 13) {
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
dealerSum += getValue(card);
dealerAceCount += checkAce(card);
document.getElementById("dealer-cards").append(cardImg);
}
console.log(dealerSum)
for (let i = 0; i < 2; i++) {
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
yourSum += getValue(card);
yourAceCount += checkAce(card);
document.getElementById("your-cards").append(cardImg);
}
console.log(yourSum);
document.getElementById("refresh").addEventListener("click", refresh);
document.getElementById("hit").addEventListener("click", hit);
document.getElementById("stay").addEventListener("click", stay);
}
function hit() {
if (!canHit) {
return;
}
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
yourSum += getValue(card);
yourAceCount += checkAce(card);
document.getElementById("your-cards").append(cardImg);
if (reduceAce(yourSum, yourAceCount) > 21) {
canHit = false;
}
}
function stay() {
dealerSum = reduceAce(dealerSum, dealerAceCount);
yourSum = reduceAce(yourSum, yourAceCount);
canHit = false;
document.getElementById("hidden").src = "./cards/" + hidden + ".png";
let message = "";
if (yourSum > 21) {
message = "You lose! Better luck next time. Refresh to try again!"
}
else if (dealerSum > 21) {
message = "You win! Refresh to play again!"
}
else if (yourSum == dealerSum) {
message = "Tie! Refresh to play again!";
}
else if (yourSum > dealerSum) {
message = "You win! Refresh to play again!";
}
else if (yourSum < dealerSum) {
message = "You lose! Better luck next time. Refresh to play again!";
}
document.getElementById("dealer-sum").innerText = dealerSum;
document.getElementById("your-sum").innerText = yourSum;
document.getElementById("result").innerText = message;
}
function refresh() {
window.location.reload();
}
function getValue(card) {
let data = card.split("-");
let value = data[0];
if (isNaN(value)) {
if (value == "A") {
return 11;
}
return 10;
}
return parseInt(value);
}
function checkAce(card) {
if (card[0] == "A") {
return 1;
}
return 0;
}
function reduceAce(playerSum, playerAceCount) {
while (playerSum > 21 && playerAceCount > 0) {
playerSum -= 10;
playerAceCount -= 1;
}
return playerSum;
}

Related

calculate score based on array object using jquery

I’m beginner in JavaScript and I’m trying to make a quiz that calculates the score of object(type) in the array. So the total score should count how much the user get in each part(ex:2/2 in math, 1/2 in science. Total= 3/4).
Is there any possible way to do that using jquery ?
help me please, thank you
var all_questions = [{
type:"math",
question_string: "4 + 4",
choices: {
correct: "8",
wrong: ["2", "3", "9"]
}
}, {
type:"math",
question_string: "4 * 4",
choices: {
correct: "16",
wrong: ["24", "13", "4"]
}
}, {
type:"sience",
question_string: "What part of the body helps you move?",
choices: {
correct: "Muscles",
wrong: ["Eyes", "Pancreas", "Lungs"]
}
}, {
type:"sience",
question_string: 'What star shines in the day and provides light?',
choices: {
correct: "Sun",
wrong: ["Moon", "Venus", "Mars"]
}
}];
var Quiz = function(quiz_name) {
this.quiz_name = quiz_name;
this.questions = [];
}
Quiz.prototype.add_question = function(question) {
var index_to_add_question = Math.floor(Math.random() * this.questions.length);
this.questions.splice(index_to_add_question, 0, question);
}
Quiz.prototype.render = function(container) {
var self = this;
$('#quiz-results').hide();
$('#quiz-name').text(this.quiz_name);
var question_container = $('<div>').attr('id', 'question').insertAfter('#quiz-name');
function change_question() {
self.questions[current_question_index].render(question_container);
$('#prev-question-button').prop('disabled', current_question_index === 0);
$('#next-question-button').prop('disabled', current_question_index === self.questions.length - 1);
var all_questions_answered = true;
for (var i = 0; i < self.questions.length; i++) {
if (self.questions[i].user_choice_index === null) {
all_questions_answered = false;
break;
}
}
$('#submit-button').prop('disabled', !all_questions_answered);
}
var current_question_index = 0;
change_question();
$('#prev-question-button').click(function() {
if (current_question_index > 0) {
current_question_index--;
change_question();
}
});
$('#next-question-button').click(function() {
if (current_question_index < self.questions.length - 1) {
current_question_index++;
change_question();
}
});
$('#submit-button').click(function() {
var score = 0;
for (var i = 0; i < self.questions.length; i++) {
if (self.questions[i].user_choice_index === self.questions[i].correct_choice_index) {
score++;
}
}
var percentage = score / self.questions.length;
console.log(percentage);
var message;
if (percentage === 1) {
message = 'Great job!'
} else if (percentage >= .75) {
message = 'You did alright.'
} else if (percentage >= .5) {
message = 'Better luck next time.'
} else {
message = 'Maybe you should try a little harder.'
}
$('#quiz-results-message').text(message);
$('#quiz-results-score').html('You got <b>' + score + '/' + self.questions.length + '</b> questions correct.');
$('#quiz-results').slideDown();
$('#quiz button').slideUp();
});
question_container.bind('user-select-change', function() {
var all_questions_answered = true;
for (var i = 0; i < self.questions.length; i++) {
if (self.questions[i].user_choice_index === null) {
all_questions_answered = false;
break;
}
}
$('#submit-button').prop('disabled', !all_questions_answered);
});
}
var Question = function(question_string, correct_choice, wrong_choices) {
// Private fields for an instance of a Question object.
this.question_string = question_string;
this.choices = [];
this.user_choice_index = null; // Index of the user's choice selection
// Random assign the correct choice an index
this.correct_choice_index = Math.floor(Math.random() * wrong_choices.length + 1);
// Fill in this.choices with the choices
var number_of_choices = wrong_choices.length + 1;
for (var i = 0; i < number_of_choices; i++) {
if (i === this.correct_choice_index) {
this.choices[i] = correct_choice;
} else {
// Randomly pick a wrong choice to put in this index
var wrong_choice_index = Math.floor(Math.random(0, wrong_choices.length));
this.choices[i] = wrong_choices[wrong_choice_index];
// Remove the wrong choice from the wrong choice array so that we don't pick it again
wrong_choices.splice(wrong_choice_index, 1);
}
}
}
Question.prototype.render = function(container) {
var self = this;
var question_string_h2;
if (container.children('h2').length === 0) {
question_string_h2 = $('<h2>').appendTo(container);
} else {
question_string_h2 = container.children('h2').first();
}
question_string_h2.text(this.question_string);
if (container.children('input[type=radio]').length > 0) {
container.children('input[type=radio]').each(function() {
var radio_button_id = $(this).attr('id');
$(this).remove();
container.children('label[for=' + radio_button_id + ']').remove();
});
}
for (var i = 0; i < this.choices.length; i++) {
var choice_radio_button = $('<input>')
.attr('id', 'choices-' + i)
.attr('type', 'radio')
.attr('name', 'choices')
.attr('value', 'choices-' + i)
.attr('checked', i === this.user_choice_index)
.appendTo(container);
var choice_label = $('<label>')
.text(this.choices[i])
.attr('for', 'choices-' + i)
.appendTo(container);
}
$('input[name=choices]').change(function(index) {
var selected_radio_button_value = $('input[name=choices]:checked').val();
self.user_choice_index = parseInt(selected_radio_button_value.substr(selected_radio_button_value.length - 1, 1));
container.trigger('user-select-change');
});
}
$(document).ready(function() {
var quiz = new Quiz('');
for (var i = 0; i < all_questions.length; i++) {
var question = new Question(all_questions[i].question_string, all_questions[i].choices.correct, all_questions[i].choices.wrong);
quiz.add_question(question);
}
var quiz_container = $('#quiz');
quiz.render(quiz_container);
});
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Multiple Choice Quiz</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div id="quiz">
<h1 id="quiz-name"></h1>
<button id="submit-button">Submit</button>
<button id="next-question-button">Next</button>
<button id="prev-question-button">Back</button>
<div id="quiz-results">
<p id="quiz-results-message"></p>
<p id="quiz-results-score"></p>
</div>
</div>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script><script src="./script.js"></script>
</body>
</html>
Basically you're looking for a group by logic - you want to group the answers by the question type. In order to solve this:
Add question_type to Question (not mandatory, we can take it from the original array of question. I'll keep it for readability).
In order to implement the group by logic, we can reduce to filter the right answers and convert the Questions array into a score dictionary. The keys are the questions type, the value is the score.
For every right answer, we either adding plus one if the category already exists or initiating as 1 if not.
I'm using a shorter version yet does exactly the same:
acc.set(curr.question_type, (acc.get(curr.question_type) || 0) + 1);
// |-- add / update --| |- current score if exists -| 0 if not, plus one
Here is the full reduce
// global counter for total answers
let totalScore = 0;
const result = a.reduce((acc, curr) => {
// if it's the right answer
if (curr.user_choice_index === curr.correct_choice_index) {
// add / update the entity with 1 if's the first right answer in the category so far or add 1 if it exists
acc.set(curr.question_type, (acc.get(curr.question_type) || 0) + 1);
totalScore++;
}
return acc;
}, new Map());
The second part is to render the results:
// convert the Map back to array
const scoreText = Array.from(score.entries())
// render each type in a different line
.map(([type, scoreByType]) => `<b>${type}</b>: ${scoreByType}`)
.join('<br />');
Read more about
Map
Map.entries
Array.from
Array.reduce
Full working example:
var all_questions = [{
type:"math",
question_string: "4 + 4",
choices: {
correct: "8",
wrong: ["2", "3", "9"]
}
}, {
type:"math",
question_string: "4 * 4",
choices: {
correct: "16",
wrong: ["24", "13", "4"]
}
}, {
type:"sience",
question_string: "What part of the body helps you move?",
choices: {
correct: "Muscles",
wrong: ["Eyes", "Pancreas", "Lungs"]
}
}, {
type:"sience",
question_string: 'What star shines in the day and provides light?',
choices: {
correct: "Sun",
wrong: ["Moon", "Venus", "Mars"]
}
}];
var Quiz = function(quiz_name) {
this.quiz_name = quiz_name;
this.questions = [];
}
Quiz.prototype.add_question = function(question) {
var index_to_add_question = Math.floor(Math.random() * this.questions.length);
this.questions.splice(index_to_add_question, 0, question);
}
Quiz.prototype.render = function(container) {
var self = this;
$('#quiz-results').hide();
$('#quiz-name').text(this.quiz_name);
var question_container = $('<div>').attr('id', 'question').insertAfter('#quiz-name');
function change_question() {
self.questions[current_question_index].render(question_container);
$('#prev-question-button').prop('disabled', current_question_index === 0);
$('#next-question-button').prop('disabled', current_question_index === self.questions.length - 1);
var all_questions_answered = true;
for (var i = 0; i < self.questions.length; i++) {
if (self.questions[i].user_choice_index === null) {
all_questions_answered = false;
break;
}
}
$('#submit-button').prop('disabled', !all_questions_answered);
}
var current_question_index = 0;
change_question();
$('#prev-question-button').click(function() {
if (current_question_index > 0) {
current_question_index--;
change_question();
}
});
$('#next-question-button').click(function() {
if (current_question_index < self.questions.length - 1) {
current_question_index++;
change_question();
}
});
$('#submit-button').click(function() {
let totalScore = 0;
const score = self.questions.reduce((acc, curr) => {
if (curr.user_choice_index === curr.correct_choice_index) {
acc.set(curr.question_type, (acc.get(curr.question_type) || 0) + 1);
totalScore++;
}
return acc;
}, new Map());
var percentage = score / self.questions.length;
console.log(percentage);
var message;
if (percentage === 1) {
message = 'Great job!'
} else if (percentage >= .75) {
message = 'You did alright.'
} else if (percentage >= .5) {
message = 'Better luck next time.'
} else {
message = 'Maybe you should try a little harder.'
}
$('#quiz-results-message').text(message);
const scoreText = Array.from(score.entries())
.map(([type, scoreByType]) => `<b>${type}</b>: ${scoreByType}`)
.join('\n');
$('#quiz-results-score').html('You got <b>' + totalScore + '/' + self.questions.length + '</b> questions correct.\n' + scoreText);
$('#quiz-results').slideDown();
$('#quiz button').slideUp();
});
question_container.bind('user-select-change', function() {
var all_questions_answered = true;
for (var i = 0; i < self.questions.length; i++) {
if (self.questions[i].user_choice_index === null) {
all_questions_answered = false;
break;
}
}
$('#submit-button').prop('disabled', !all_questions_answered);
});
}
var Question = function(question_string, correct_choice, wrong_choices, question_type) {
// Private fields for an instance of a Question object.
this.question_string = question_string;
this.question_type = question_type;
this.choices = [];
this.user_choice_index = null; // Index of the user's choice selection
// Random assign the correct choice an index
this.correct_choice_index = Math.floor(Math.random() * wrong_choices.length + 1);
// Fill in this.choices with the choices
var number_of_choices = wrong_choices.length + 1;
for (var i = 0; i < number_of_choices; i++) {
if (i === this.correct_choice_index) {
this.choices[i] = correct_choice;
} else {
// Randomly pick a wrong choice to put in this index
var wrong_choice_index = Math.floor(Math.random(0, wrong_choices.length));
this.choices[i] = wrong_choices[wrong_choice_index];
// Remove the wrong choice from the wrong choice array so that we don't pick it again
wrong_choices.splice(wrong_choice_index, 1);
}
}
}
Question.prototype.render = function(container) {
var self = this;
var question_string_h2;
if (container.children('h2').length === 0) {
question_string_h2 = $('<h2>').appendTo(container);
} else {
question_string_h2 = container.children('h2').first();
}
question_string_h2.text(this.question_string);
if (container.children('input[type=radio]').length > 0) {
container.children('input[type=radio]').each(function() {
var radio_button_id = $(this).attr('id');
$(this).remove();
container.children('label[for=' + radio_button_id + ']').remove();
});
}
for (var i = 0; i < this.choices.length; i++) {
var choice_radio_button = $('<input>')
.attr('id', 'choices-' + i)
.attr('type', 'radio')
.attr('name', 'choices')
.attr('value', 'choices-' + i)
.attr('checked', i === this.user_choice_index)
.appendTo(container);
var choice_label = $('<label>')
.text(this.choices[i])
.attr('for', 'choices-' + i)
.appendTo(container);
}
$('input[name=choices]').change(function(index) {
var selected_radio_button_value = $('input[name=choices]:checked').val();
self.user_choice_index = parseInt(selected_radio_button_value.substr(selected_radio_button_value.length - 1, 1));
container.trigger('user-select-change');
});
}
$(document).ready(function() {
var quiz = new Quiz('');
for (var i = 0; i < all_questions.length; i++) {
var question = new Question(all_questions[i].question_string, all_questions[i].choices.correct, all_questions[i].choices.wrong, all_questions[i].type);
quiz.add_question(question);
}
var quiz_container = $('#quiz');
quiz.render(quiz_container);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodePen - Multiple Choice Quiz</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div id="quiz">
<h1 id="quiz-name"></h1>
<button id="submit-button">Submit</button>
<button id="next-question-button">Next</button>
<button id="prev-question-button">Back</button>
<div id="quiz-results">
<p id="quiz-results-message"></p>
<p id="quiz-results-score"></p>
</div>
</div>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="./script.js"></script>
</body>
</html>

how can I stop it from printing duplicate?

I'm I've created the below shopping cart, however, I'm trying to print the elements of the basket inside the HTML, but it's printing duplicated. If I add another element to the basket, it prints the new one + the previous one, even if the previous one is already printed.
Really appreciate the help, i'm new with JS, so struggling a bit.
thank you
//list of products
let products = [
{
name: "Logitech Pebble M350 Pink",
tag: "mouse",
price: 15.99,
count: ""
},
{
name: "Logitech K380 Multi-Device Bluetooth Keyboard",
tag: "keyboard",
price: 20.99,
count: ""
},
{
name: "Anker SoundCore min",
tag: "speaker",
price: 22.99,
count: ""
}
];
//ADD
function add() {
let quantity = document.getElementsByClassName("quantity");
let totalPrice = [];
let nameCount = 0;
let basket = [];
let basketSentence = document.getElementById("yourBasket");
for (let i = 0; i < quantity.length; i++) {
products[i].count = quantity[i].value;
}
for (var name in products) {
nameCount = nameCount + 1;
}
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
if (products[i].count != 0) {
basket.push(products[i]);
const newLi = document.createElement("li");
newLi.innerText = products[i].count + " " + products[i].name;
if (yourBasket.innerText != newLi.innerText) {
yourBasket.append(newLi);
console.log(yourBasket.innerText);
}
}
document.getElementById("total-value").innerHTML = sum;
}
}
//REMOVE
let removeBtn = document.querySelectorAll(".remove");
let quantity = document.querySelectorAll(".quantity");
removeBtn.forEach(function(check) {
check.addEventListener("click", checkIndex);
});
function checkIndex(event) {
let totalPrice = [];
let nameCount = 0;
var index = Array.from(removeBtn).indexOf(event.target);
console.log(index);
quantity[index].value = "";
products[index].count = quantity[index].value;
console.log(products[index].count);
for (var name in products) {
nameCount = nameCount + 1;
}
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
document.getElementById("total-value").innerHTML = sum;
}
}
Explanation
The solution is to reset the text of the basket before you start appending again.
Add the line yourBasket.innerHTML = ""; before the for loop.
The problem was that append was appending text. What you want is to actually clear the basket, and re-append all the totals of all the products.
Excerpt:
yourBasket.innerHTML = ""; //THIS IS THE LINE
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
Full code for Add:
//ADD
function add() {
let quantity = document.getElementsByClassName("quantity");
let totalPrice = [];
let nameCount = 0;
let basket = [];
let basketSentence = document.getElementById("yourBasket");
for (let i = 0; i < quantity.length; i++) {
products[i].count = quantity[i].value;
}
for (var name in products) {
nameCount = nameCount + 1;
}
yourBasket.innerHTML = ""; //(newLi);
for (let i = 0; i < nameCount; i++) {
totalPrice[i] = products[i].price * products[i].count;
var sum = totalPrice.reduce(function(a, b) {
return a + b;
}, 0);
if (products[i].count != 0) {
basket.push(products[i]);
const newLi = document.createElement("li");
newLi.innerText = products[i].count + " " + products[i].name;
if (yourBasket.innerText != newLi.innerText) {
yourBasket.append(newLi);
console.log(yourBasket.innerText);
}
}
document.getElementById("total-value").innerHTML = sum;
}
}
JSFiddle: https://jsfiddle.net/4zyd1sow/4/

Trouble preventing duplicate letter entry in pure JS hangman

So, I'm coding out a hangman style game as is the custom when learning how to user JS. I have it working pretty well, but I cannot seem to figure out how to properly identify and prevent duplicate wrong guesses.
Example: if you press "f" and it is not in the word, display and decrement the remaining scores once, and if you press "f" again, ignore the input. Here is my code thus far. I have my existing code in the function but it doesn't currently do anything. Any advice is appreciated.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
See how I'm ignoring duplicates in checkInput.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
// myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
if (wrongGuess.includes(letter)) { // <--- HERE
// do anything else you wanna do
return;
}
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
<div id="current-word"></div>
<div id="guesses-remaining"></div>
<div id="letters-guessed"></div>

iframe element returns undefined after onload event?

EDIT: Is there no one who can shed some light on this issue? Anything would be appreciated. :)
I have a script that is supposed to check to see if an elements html contains a given string..
When these elements do exist, my code throws this error: Uncaught TypeError: Cannot read property 'outerHTML' of null
This is the line: let check = document.querySelector("#iframe_${globalI}").contentWindow.document.querySelector(".Row"+inc).outerHTML
I then check to see if the string includes a check string.. IE: check.includes("Pre Trip")
If I run this line directly in the console it works and returns true... So what is going on here..?? How can I get this check to pass..?
I have this check executing after a setTimeout of 20 seconds, then wrapped again in another setTimeout for 500ms as I was trying to figure this out..
Also, I need to note that there are no XSS / CORS issues.
Here is my code..
function checkRowCount(x){
console.log("Row count called on "+x);
let rowCount = 0;
for(let i = 0; i < 30; i++){
if(typeof(document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i)) != 'undefined' && document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i) != null){
rowCount++;
}
}
console.log(rowCount);
return rowCount;
}
let globalCompiler = []; //globalCompiler[globalI] = {unit: unitNumber[globalI], data: ["X", " ", "NO POST TRIP]}
let unitNumber = [1031,1743,1744,1986,3239,3256,3257,4024,4062,4063,4064,4065,4247,4309,4315,4326,4327,4334,4335,4337,4350,4382,4385,7166,7380,7381,8765,8823,8945,8950,8988,10720,17045,17163,40014,40069,40122,40380,80129,80188,80700,80701,80702,80728,80831,80852,80875,"80876","81027","81038","401288","401306","402409","60099T","CH889","CH890","SR31077","T19","U5509","U6660","U6667","U6675","U8854","US1025T"];
let url = "http://winweb.cleanharbors.com/Vehicle/VehicleTDSearch.aspx?SearchType=DVIR";
function iframeLoaded(selector, unit, setDate, callback){
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtStartDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtEndDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtVhcleNo").value = unit;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#btnRetrieve").click();
}
let loadFinished = {};
for(let dec = 0; dec < unitNumber.length; dec++){
loadFinished[unitNumber[dec]] = false;
}
console.log(loadFinished);
for(let globalI = 0; globalI < 3; globalI++){
globalCompiler[globalI] = {unit: unitNumber[globalI], data: []};
let iframeObj = document.createElement('iframe');
iframeObj.id = `iframe_${globalI}`;
iframeObj.hidden = false;
iframeObj.src = url;
iframeObj.onload = () => {
if (loadFinished[unitNumber[globalI]] == false) {
loadFinished[unitNumber[globalI]] = true;
let setDate = "11/01/2019";
iframeLoaded(globalI, unitNumber[globalI], setDate);
console.log("iframeloaded called on " + globalI);
setTimeout(() => {
setTimeout(() => {
let dateCheckObject = {}, rowCount = checkRowCount(globalI), trackingArr = [];
if (rowCount == 0) {
globalCompiler[globalI].data.push(" ");
} else {
for (let inc = 1; inc <= rowCount; inc++) {
//let check = $('#iframe_'+globalI).contents().find(`.Row` + inc).html().includes("Pre Trip");
let check = document.querySelector(`#iframe_${globalI}`).contentWindow.document.querySelector(".Row"+inc).outerHTML
if (check.includes("Pre Trip")) {
dateCheckObject.pre = true;
} else {
dateCheckObject.post = true;
}
}
if(dateCheckObject.pre && dateCheckObject.post) {
console.log("X");
globalCompiler[globalI].data.push("X");
dateCheckObject = {};
} else if (dateCheckObject.pre == 'undefined') {
console.log("NO PRE");
globalCompiler[globalI].data.push("NO PRE TRIP");
dateCheckObject = {};
} else {
console.log("NO POST");
globalCompiler[globalI].data.push("NO POST TRIP");
dateCheckObject = {};
}
}
},500);
}, 20000);
}
};
document.body.appendChild(iframeObj);
console.log("Global Loop called");
}
```
A for loop ran one count too far...
e.g.: for (let inc = 1; inc <= rowCount; inc++)
Should have been for (let inc = 1; inc < rowCount; inc++)

How to detect joy-con input/motion controls in HTML5 JavaScript

I am trying to create an HTML5 JavaScript game that uses Nintendo Switch Joy-Cons and motion controls. The problem is, I don't know how to detect motion controls from Joy-Cons when they are connected to my PC.
I've managed to achieve button inputs with Xbox controllers, PS4, and Joy Con using Gamepad API, but is it possible to do so with Joy-Con motion controls?
Here is the code for Gamepad API if you want to see it(Again, I'm aiming for Joy-Con motion controls):
var haveEvents = 'ongamepadconnected' in window;
var controllers = {};
function connecthandler(e) {
addgamepad(e.gamepad);
}
function addgamepad(gamepad) {
controllers[gamepad.index] = gamepad;
var d = document.createElement("div");
d.setAttribute("id", "controller" + gamepad.index);
var t = document.createElement("h1");
t.appendChild(document.createTextNode("gamepad: " + gamepad.id));
d.appendChild(t);
var b = document.createElement("div");
b.className = "buttons";
for (var i = 0; i < gamepad.buttons.length; i++) {
var e = document.createElement("span");
e.className = "button";
//e.id = "b" + i;
e.innerHTML = i;
b.appendChild(e);
}
d.appendChild(b);
var a = document.createElement("div");
a.className = "axes";
for (var i = 0; i < gamepad.axes.length; i++) {
var p = document.createElement("progress");
p.className = "axis";
//p.id = "a" + i;
p.setAttribute("max", "2");
p.setAttribute("value", "1");
p.innerHTML = i;
a.appendChild(p);
}
d.appendChild(a);
var start = document.getElementById("start");
if (start) {
start.style.display = "none";
}
document.body.appendChild(d);
requestAnimationFrame(updateStatus);
}
function disconnecthandler(e) {
removegamepad(e.gamepad);
}
function removegamepad(gamepad) {
var d = document.getElementById("controller" + gamepad.index);
document.body.removeChild(d);
delete controllers[gamepad.index];
}
function updateStatus() {
if (!haveEvents) {
scangamepads();
}
var i = 0;
var j;
for (j in controllers) {
var controller = controllers[j];
var d = document.getElementById("controller" + j);
var buttons = d.getElementsByClassName("button");
for (i = 0; i < controller.buttons.length; i++) {
var b = buttons[i];
var val = controller.buttons[i];
var pressed = val == 1.0;
if (typeof(val) == "object") {
pressed = val.pressed;
val = val.value;
}
var pct = Math.round(val * 100) + "%";
b.style.backgroundSize = pct + " " + pct;
if (pressed) {
b.className = "button pressed";
//Pressed down code here
} else {
b.className = "button";
//Release button code here
}
}
var axes = d.getElementsByClassName("axis");
for (i = 0; i < controller.axes.length; i++) {
var a = axes[i];
a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
a.setAttribute("value", controller.axes[i] + 1);
}
}
requestAnimationFrame(updateStatus);
}
function scangamepads() {
var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
for (var i = 0; i < gamepads.length; i++) {
if (gamepads[i]) {
if (gamepads[i].index in controllers) {
controllers[gamepads[i].index] = gamepads[i];
} else {
addgamepad(gamepads[i]);
}
}
}
}
window.addEventListener("gamepadconnected", connecthandler);
window.addEventListener("gamepaddisconnected", disconnecthandler);
if (!haveEvents) {
setInterval(scangamepads, 500);
}
Using this link for reference
Wei Gao explained this in a React Knowledgeable meetup last week.
You can learn how she did it through her presentation or her slides.
You can visit the talk page for more information.

Categories

Resources