I am using the code.org javascript library. I'm trying to have it so it changes team based on the two selected once 3 outs are reached. I tried to declare team1 and team2 and setting them equal to the check box that is selected but that doesnt work correctly.
The team name doesn't change on the label like it does when you first select a team. I'm not quite sure how to do it but the main goal is to get the team name to change when the current team gets 3 outs. There is a label that is being used in the player selection function that displays the 1st team selected.
var outs = 0;
var team1 = "";
var team2 = "";
var strikes = 0;
var balls = 0;
var fouls = 0;
var inning = 0;
var hit = 0;
var currentPlayer = team1, team2;
//Player Selection
onEvent("btnStart","click", function() {
var chkBoxs = ["Yankees", "Boston", "Astros"];
var selected = [];
for (var index = 0; selected.length < 2 && index < chkBoxs.length; index++) {
if (getChecked(chkBoxs[index])) { selected.push(index); }
}
setScreen("game");
if (selected.length == 2) {
console.log("The Teams are: " + chkBoxs[selected[0]] + " and " + chkBoxs[selected[1]]);
}
if (chkBoxs[selected[0]]) {
setText("lblTeamGame",chkBoxs[selected[0]]);
team1 = chkBoxs[selected[0]];
team2 = chkBoxs[selected[1]];
} else {
setText("lblTeamGame",chkBoxs[selected[1]]);
}
});
//Pitching Rules
function Count() {
if (balls == 4)
{
console.log("Walk");
setText("lblBallCount", 0);
setText("lblStrikeCount", 0);
balls = 0;
strikes = 0;
}
if (strikes == 3)
{
console.log("Strike Out");
outs++;
setText("lblStrikeCount", 0);
setText("lblOutCount", outs);
setText("lblBallCount", 0);
strikes = 0;
balls = 0;
}
if (outs == 3)
{
inning++;
setText("lblInningCount", inning);
switchPlayer();
}
if(hit)
{
setText("lblStrikeCount", 0);
setText("lblBallCount", 0);
strikes = 0;
balls = 0;
}
}
//Switch Teams
function switchPlayer() {
if(currentPlayer == team1) {
currentPlayer = team2;
showElement("player2_highlight");
hideElement("player1_highlight");
} else {
showElement("player1_highlight");
hideElement("player2_highlight");
currentPlayer = 1;
}
console.log("current player is: " + currentPlayer);
}
This could be your problem:
function switchPlayer(){
if(currentPlayer==team1){
currentPlayer=team2;
showElement("player2_highlight");
hideElement("player1_highlight");
} else {
showElement("player1_highlight");
hideElement("player2_highlight");
currentPlayer=team1; // Specify team1 instead of just 1
}
console.log("current player is: "+currentPlayer);
}
Also, after switching teams, you need to reset the number of outs.
if(outs==3)
{
inning++;
setText("lblInningCount",inning);
switchPlayer();
outs=0;
}
Related
I want to allow the user to select the difficulty of the game. Easy is words length 3-5, Medium is length 6-9, Hard is 10-15. The word is being pulled from an AJAX API. Also, I've consulted this example but am still struggling to apply it to my own. I included extra code because I'm not sure if I could add radio buttons that store the level and word.length that then updates the word retrieved from the api to be the correct length.
var api = 'https://hangman-api.lively.software';
//add alphabet to div
alphabet.forEach((i) => {
$('.hangman-letters').append(`<div id="letter-${i}">${i}</div>`);
});
//set up initial puzzle
newPuzzle();
//set up new puzzle when user clicks "start over"
$('#game-over-replay').click(function(){
newPuzzle();
});
//trigger game on clicking letter button
$('.hangman-letters div').click(function(){
submitLetter(this.innerHTML, this);
});
//trigger game on keypress
$(window).keypress(function(e){
var thisKey = String.fromCharCode(e.which);
if(alpha.indexOf(thisKey) > -1) {
submitLetter(thisKey, document.getElementById(`letter-${thisKey}`));
}
})
//functions
//handle clicked letter or keyboard input
function submitLetter(letter, thisLetterButton) {
var isCorrect = letterChosen(letter);
if(isCorrect) $(thisLetterButton).addClass('disabled correct');
else $(thisLetterButton).addClass('disabled');
if(remainingBlanks < 1) {
gameOver(true);
}
if(totalIncorrect >= hangmanParts.length + 1) {
gameOver(false);
}
}
//wipe variables and containers and set up new game
//now called after api call is complete
function setUp(){
$('.game-over').hide();
puzzleLetterContainers = [];
previouslyChosen = '';
totalIncorrect = 0;
remainingBlanks = puzzle.length;
$('.hangman-puzzle').html('');
$('#added-parts').html('');
$('.hangman-letters div').each(function(){
this.classList = '';
})
puzzle.split('').forEach((i) => {
var thisClass = "hangman-puzzle-letters",
placeholder = " ";
if(i == ' ' || i == '-') {
thisClass += ' space';
remainingBlanks--;
placeholder = i;
}
$('.hangman-puzzle').append(`<div class="${thisClass}">${placeholder}</div>`);
});
//var difficulty[] = new difficulty;
//var difficulty[1] = Easy;
//var difficulty[2] = Medium;
//var difficulty[3] = Hard;
puzzleLetterContainers = document.getElementsByClassName('hangman-puzzle-letters');
}
Building a dice game and you get 3 rolls. Once you finish your turn i'm trying to have a "reset" button that will reset the values back to the original spot so the "next person" can play. The values reset as I expected but when I "roll" none of the functions are taking place and i'm pretty new in js so i'm not sure what the problem is.
var playerScore = document.getElementById('firstPlayerScore');
var rollButton = document.getElementById('roll_button');
var dice1 = new dice(1);
var dice2 = new dice(2);
var dice3 = new dice(3);
var dice4 = new dice(4);
var dice5 = new dice(5);
var diceArray = [dice1, dice2, dice3, dice4, dice5];
var cargo = 0;
var numOfRolls = 0;
var cargoButton = document.getElementById('cargo');
var canHaveCargo = false;
function restart(){
dice1 = new dice(1);
dice2 = new dice(2);
dice3 = new dice(3);
dice4 = new dice(4);
dice5 = new dice(5);
diceArray = [dice1, dice2, dice3, dice4, dice5];
cargo = 0;
numOfRolls = 0;
canHaveCargo = false;
addGlow();
updateDiceImageUrl();
document.getElementById("dice1").classList.remove('glowing');
document.getElementById("dice2").classList.remove('glowing');
document.getElementById("dice3").classList.remove('glowing');
document.getElementById("dice4").classList.remove('glowing');
document.getElementById("dice5").classList.remove('glowing');
}
//dice object
function dice(id){
this.id = id;
this.currentRoll = 1;
this.previousRoll = 1;
this.isSelected = false;
this.diceImageUrl = "img/dice/dice1.png";
this.roll = function(){
this.previousRoll = this.currentRoll;
this.currentRoll = getRandomRoll(1, 6);
}
}
//returns an array of all dice that are not currently selected so they can be rolled.
function getRollableDiceList(){
var tempDiceList = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempDiceList.push(diceArray[i]);
}
}
return tempDiceList;
}
// gets a random number between min and max (including min and max)
function getRandomRoll(min,max){
return Math.floor(Math.random() * (max-min + 1) + min);
}
// calls the roll function on each dice
function rollDice(rollableDiceList){
for(var i = 0; i < rollableDiceList.length; i++){
rollableDiceList[i].roll();
}
}
// updates each dice with the new url for the image that corresponds to what their current roll is
function updateDiceImageUrl(){
for(var i = 0; i < diceArray.length; i++){
var currentDice = diceArray[i];
currentDice.diceImageUrl = "http://boomersplayground.com/img/dice/dice" + currentDice.currentRoll + ".png";
//update div image with img that cooresponds to their current roll
updateDiceDivImage(currentDice);
}
}
//Displays the image that matches the roll on each dice
function updateDiceDivImage(currentDice) {
document.getElementById("dice"+currentDice.id).style.backgroundImage = "url('" + currentDice.diceImageUrl +"')";
}
// returns an array of all
function getNonSelectedDice(){
var tempArray = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempArray.push(diceArray[i]);
}
tempArray.sort(function(a, b){
return b.currentRoll - a.currentRoll;
});
}
return tempArray;
}
function getSelectedDice(){
var selectedDice = [];
for(var i = 0; i < diceArray.length; i++){
if(diceArray[i].isSelected){
selectedDice.push(diceArray[i]);
}
}
return selectedDice;
}
//boolean variables
var shipExist = false;
var captExist = false;
var crewExist = false;
//checks each dice for ship captain and crew. Auto select the first 6, 5 , 4.
function checkForShipCaptCrew(){
//array of dice that are not marked selected
var nonSelectedDice = getNonSelectedDice();
for(var i = 0; i < nonSelectedDice.length; i++){
//temp variable that represents the current dice in the list
currentDice = nonSelectedDice[i];
if (!shipExist) {
if (currentDice.currentRoll == 6) {
shipExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && !captExist) {
if (currentDice.currentRoll == 5) {
captExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && captExist && !crewExist) {
if (currentDice.currentRoll == 4) {
crewExist = true;
currentDice.isSelected = true;
canHaveCargo = true;
}
}
}
}
function addGlow(){
var selectedDice = getSelectedDice();
for (var i = 0; i < selectedDice.length; i++){
var addGlowDice = selectedDice[i];
var element = document.getElementById('dice' + addGlowDice.id);
element.className = element.className + " glowing";
}
}
function getCargo(){
var cargo = 0;
var moreDice = getNonSelectedDice();
if (canHaveCargo){
for(var i=0; i < moreDice.length; i++){
cargo += moreDice[i].currentRoll;
playerScore.innerHTML = 'You have got ' + cargo + ' in ' + numOfRolls + ' rolls!';
}
} else {
alert("You don't have Ship Captain and the Crew yet!");
}
}
rollButton.addEventListener('click', function(){
//generate rollable dice list
if (numOfRolls < 3) {
var rollableDiceList = getRollableDiceList();
//roll each dice
rollDice(rollableDiceList);
//update dice images
updateDiceImageUrl();
getNonSelectedDice();
// //auto select first 6, 5, 4 (in that order)
checkForShipCaptCrew();
addGlow();
// //adds a red glow to each dice that is selected
numOfRolls++;
}
});
cargoButton.addEventListener('click', getCargo);
var startButton = document.getElementById('restart');
startButton.addEventListener('click', restart);
http://boomer1204.github.io/shipCaptainCrew/
Here is a link to the live game since it's the only way I can describe the problem since I don't know what's not working. If you roll the dice a couple times the dice will get a blue border and be "saved" according to the rules. Now after you hit th restart button that doesn't happen anymore.
Thanks for the help in advance guys
Just add this to your restart()
function restart(){
...
shipExist = false;
capExist = false;
crewExist = false;
...
}
It's hard to replicate without a fiddle, but it seems that you are adding and removing the 'glowing' class using separate processes. Have you tried adding the glowing class the same way you are removing it?
element.classList.add("glowing")
See an example within a fiddle: https://jsfiddle.net/5tstf2f8/
function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>
making a simple game using javascript, once the start button is selected a country will appear and three cities. One of the three cities matches the country and the other two are false. For example, Ireland will appear and London, Paris, Dublin. The player has to select the correct city to match the country, once they select a city a pop up box will appear saying if they won or lost, if the won, they go onto the next round where another country will appear..
this is the code i have at the moment, there is bits missing, i just don't know where to go from here?
any help is much appreciated, thanks
//all my countries
var countries = ["england", "france", "germany", "hungary", "ireland", `"italy"`, "norway", "spain", "wales"]
//gets the screen height and width for the game
var scnWid,scnHei;
if (self.innerHeight) // works for all except Internet Explorer
{
scnWid = self.innerWidth;
scnHei = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// internet explorer 6 fix
{
scnWid = document.documentElement.clientWidth;
scnHei = document.documentElement.clientHeight;
}
else if (document.body) // Other versions of ie
{
scnWid = document.body.clientWidth;
scnHei = document.body.clientHeight;
}
//shuffles the country array
function shuffleArray(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex ;
//array hasnt stopped
while (0 !== currentIndex)
//find a random element
randomIndex =Math.floor(Math.random() * currentIndex);
//swap it with current element
temporaryValue = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = temporaryValue;
//returns the shuffle array
return arr;
}
//variables for the functionality of the game
var randomCountry;
var score;
var count;
var cityClicked;
var winningscore;
//will be passed when the function is called
function gameInit(){
//calculate the number of correct
winningscore = Math.round(3*2)
//the score variable
score = 0;
//is the city clicked yes or no
cityClicked = false;
var gameCountries = [];
var gameCountryCities =[];
//shuffles the existing countries array
gameCountries = shuffleArray(countries)
//loops throught the countries and attached names
for (i = 0; i<gameCountries.length; i++)
{
document.getElementById('gameCountry').innerHTML += "div class='countryName' id= '" + gameCountries[i] + "' onclick='CountryClick'(this.id)'><img src='countries/" + gameCountries[i] + ".gif'></div>" ;}
}
//reshufflies the cities
gameCountryCities = shuffleArray(gameCountries)
//loops through the countries and displays the attached cities
for (j = 0; j<gameCountryCities.length; j++ )
{ document.getElementById('gameCity').innerHTML += "<div class='countrycity' id='country-" + gameCountryCities[j] + "' onclick='cityClick(this.id)'><img src= 'cities/" + gameCountryCities[j] + ".gif'></div>" ;
}
}
//when a city is clicked
function cityClick(cityClickedId)
{
if (cityClicked == true)
{
//does the city and country match
if "country-" + selectedCity == cityClickedId)
{
//add one to the the score
score = score +1;
//show the pop up and score
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.top = scnHei+150;
//GAME
//if the score is less than the winning score the player loses
if (score <winningscore){
gameMessage = "You Lose"
}
//otherwise they win
else {gameMessage = "You Win"}
//Show the game over pop up within the score
document.getElementById("popupBox").innerHTML =
"<div>Game Over</div<div>" + gameMessage +
"</div><div>Your Score is : " + score
+ "</div>";
//show the game over pop up with the score
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//After 5 seconds redirect the user to the level select menu
setTimeout(function(){
window.location = "level.html";
}, 5000);
}
make an object out of the country with the correct city`s in them:
var country = {
"Netherlands": {
capital: "Amsterdam"
},
"Belgium": {
capital: "Brussel"
}
};
country["Belgium"].capital //returns brussel
Check if the result is the same as the given answer and return true or false based on that
var capitals = ['Amsterdam', 'Brussel', 'Barcelona', 'Berlin', 'Rome'];
var generateQuestion = function(country) {
var question = {
1: capitals[Randomizer(1, 5),
2: capitals[Randomizer(1, 5),
3: country[country].capital
}
return question
}
var Randomizer = function(min, max) {
return Math.random() * (max - min) + min;
}
Now you only need to randomize the ID`s for your question and build it from there
I'm newbie with JavaScript, so I decided to develop a little application which is supposed to show the schedule of the streetcar of the place I live, because of the lack of the information on the official webpage.
I have several arrays with the starting time of the line, and as the time to reach each station it's the same, I only have to add the total minutes to the first hour.
There's a form for the user to set a range of hours. So, my main problem is that the "adder();" function is supposed to iterate and print all the values from an array. Instead of doing that, it takes always the same index, 24, so if the array returned has less than 24 indexes, it does not work.
Here's the HTML:
< input type="button" class="submit" value="Enviar" onclick="caller()"/>
JavaScript:
function cropHours(i){
if (i.substr(0,2) >= hora1user_recortada && i.substr(0,2) <= hora2user_recortada) {
horas.push(i);
}
return horas;
}
function adder() {
minInicio1 = horas[i].substr(0,2);
minInicio2 = horas[i].substr(3,2);
document.getElementById("test4").innerHTML = "---" + minInicio1+"_"+minInicio2;
y = parseInt(total) + parseInt(minInicio2);
document.getElementById("test5").innerHTML = "total vale "+total+"minInicio1 vale "+minInicio1+"... minInicio2 vale "+minInicio2+"...Y vale "+y;
html += "<td>"+y+"</td>";
document.getElementById("horario").innerHTML = html;
}
This is a part of another function:
if (platform == 1) {
for (var j = 0; j <= indexorigen; j++) {
total += mins1[j];
}
for (var j = 0; j <= indexdestino; j++) {
total2 += mins1[j];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral1) {
cropHours(i);
//adder(horainiciolaboral1);
}
} else {
for each (var i in horainiciofinde1) {
cropHours(i);
}
}
} else {
for (var x = 0; x <= indexorigen; x++) {
total += mins2[x];
}
for (var x = 0; x <= indexdestino; x++) {
total2 += mins2[x];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral2) {
cropHours(i);
}
} else {
for each (var i in horainiciofinde2) {
cropHours(i);
}
}
}
/*for (var i = 0; i <= horainiciolaboral1.length; i++) {
adder(horainiciolaboral1);
}*/
//horario = horas.slice(11);
for each (var i in horas) {
adder();
}
document.getElementById("test6").innerHTML = horas;
document.getElementById("test3").innerHTML = total + "----" + total2;
// ******************************************
// ** FUNCTION WHICH CALLS EVERY FUNCTION **
// ******************************************
// STARTS
function caller() {
cleaner();
retrieve_origen();
retrieve_destino();
getIndex();
sumMinutes();
getHours();
}
This is the problem:
for each (var i in horas) {
adder();
}
Thank you in advance.
Pass i to adder() as an argument:
adder(i);
...and define it as a parameter in the function:
function adder( i ) {
//...