How can I show one alert when ever a var == 0? - javascript

I am currently trying to make one easy card comparison game but I am having some problems. When ever the var playerLife or computerLife == 0 I want to show a alert message and refresh the page for a new game. If you scroll down you can see that I am trying to do this using the if statment but it does not seem to work. I am quite new at this so all the help and tips are welcome. Also if this code that I have at the moment can be better I should love to hear it. Thanks for your time.
var cards = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,8, 9, 9, 10, 10];
var shuffledCards = shuffle(cards);
var playerDeck = shuffledCards.slice(0,20);
var computerDeck = shuffledCards.slice(20);
var playerlife = 25;
var computerLife = 25;
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function getTopCard(deck) {
return deck[0];
}
function dealCards() {
var playerTopCard = getTopCard(playerDeck);
var computerTopCard = getTopCard(computerDeck);
var cardImage = "<img src='http://i1194.photobucket.com/albums/aa365/Sarah_Dunlap/card_back.png'/>";
whoWon();
console.log('--------------------');
document.getElementById("card1").innerHTML = "<div class='cardNumber'>" + playerTopCard + '</div>' + cardImage;
document.getElementById("card2").innerHTML = "<div class='cardNumber'>" + computerTopCard + '</div>' + cardImage;
document.getElementById("scoreComputer").innerHTML = computerLife;
document.getElementById("scorePlayer").innerHTML = playerlife;
}
function whoWon() {
var playerTopCard = getTopCard(playerDeck);
var computerTopCard = getTopCard(computerDeck);
if (playerTopCard > computerTopCard) {
console.log('Player Won! ' + playerTopCard + '/' + computerTopCard);
computerLife = computerLife - (playerTopCard - computerTopCard);
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
} else if (playerTopCard < computerTopCard) {
console.log('Computer Won! ' + playerTopCard + '/' + computerTopCard);
playerlife = playerlife - (computerTopCard - playerTopCard);
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
} else {
console.log('Tie! ' + playerTopCard + '/' + computerTopCard);
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
}
}
shuffle(cards);
console.log('playerDeck - ' + playerDeck);
console.log('computerDeck - ' + computerDeck);
document.getElementById("click").addEventListener("click", dealCards);
(function gameEnd () {
if (playerlife <=0 || computerLife <=0) {
alert('DONE');
}
}());

You should considering changing your code like this:
// new function
function checkIsGameOver () {
if (playerlife <=0 || computerLife <=0) {
alert('DONE');
}
}
function whoWon() {
var playerTopCard = getTopCard(playerDeck);
var computerTopCard = getTopCard(computerDeck);
if (playerTopCard > computerTopCard) {
console.log('Player Won! ' + playerTopCard + '/' + computerTopCard);
computerLife = computerLife - (playerTopCard - computerTopCard);
// added code here...
checkIsGameOver();
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
} else if (playerTopCard < computerTopCard) {
console.log('Computer Won! ' + playerTopCard + '/' + computerTopCard);
playerlife = playerlife - (computerTopCard - playerTopCard);
// added code here...
checkIsGameOver();
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
} else {
console.log('Tie! ' + playerTopCard + '/' + computerTopCard);
playerDeck.shift();
computerDeck.shift();
console.log('Player Life - ' + playerlife);
console.log('Computer Life - ' + computerLife);
}
}

Related

Can't get a simple text-based fighting game function called from my html file to work properly (loops and if... else-statements)

I'm new to JavaScript (and programming in general). I was just playing around with this script that checks how many combat rounds it takes for fighter1 to knock out fighter2 and writes out all the combat events to the page.
When I call the fightClub(); function from my HTML-file, all that gets printed is "Test". How can I get this to work? Is my logic flawed?
Any help would be much appreciated! <3
const fighter1 = array ("Jimmy", 10, 2);
const fighter2 = array ("Chet", 10, 2);
function fightClub(fighter1, fighter2){
document.write('Test');
let hitcheck = math.ceil(math.random() * 10);
while (fighter2[1] > 0){
let roundNumber = 1;
roundNumber++;
if(hitcheck >= 5){
fighter2[1] = fighter2[1] - fighter1[2];
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' deals ' + fighter1[2] + ' damage to ' + fighter2[0]);
}else {
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' swung in the air and... missed ' + fighter2[0]);
}
if(fighter2[1] <= 0){
document.write(fighter2[0] + ' was knocked out.');
break;
}
}
}
You have several syntax errors in your code. Fix them and you'll see the result.
Here it is:
const fighter1 = ["Jimmy", 10, 2];
const fighter2 = ["Chet", 10, 2];
function fightClub(fighter1, fighter2){
document.write('Test');
let hitcheck = Math.ceil(Math.random() * 10); // use 'Math' not math
while (fighter2[1] > 0){
let roundNumber = 1;
roundNumber++;
if(hitcheck >= 5){
fighter2[1] = fighter2[1] - fighter1[2];
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' deals ' + fighter1[2] + ' damage to ' + fighter2[0]);
}else {
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' swung in the air and... missed ' + fighter2[0]);
}
if(fighter2[1] <= 0){
document.write(fighter2[0] + ' was knocked out.');
break;
}
}
}
fightClub(fighter1, fighter2);

How can I make an if else statement in JavaScript prompt a user to hit a button to continue the statement?

I have built a little project game and there is a combat system. The problem is if you hit attack it runs the if else statement all the way through but doesn't show everything. It also gives me a Not a Number error if you lose, and I can't figure out what to do. Do I need to change the order of statements or something like that?
setFightEvent: function() {
let getArena = document.querySelector(".arena");
let getEnemy = document.querySelector(".enemy");
let enemy00 = new Enemy("Goblin", 100, 0, 20, 50, 100, 100);
let enemy01 = new Enemy("Troll", 200, 0, 40, 50, 80, 150);
let chooseRandomEnemy= Math.floor(Math.random() * Math.floor(2));
switch (chooseRandomEnemy) {
case 0:
enemy = enemy00;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
case 1:
enemy = enemy01;
getArena.innerHTML = '<div><p>You are fighting a ' + enemy.enemyType + '<button class="btn-attack" onclick="EventManager.FightEvent()">Attack!</button></p></div>';
break;
}
getEnemy.innerHTML = '<img src="img/avatar-enemy/' + enemy.enemyType.toLowerCase() + '.jpg" alt="' + enemy.enemyType + '" class="img-enemy"><div><h3 class="type-enemy">' + enemy.enemyType + '</h3><p class="health-enemy">Health: ' + enemy.health + '</p><p class="mana-enemy">Mana: ' + enemy.mana + '</P><p class="dexterity-enemy>Dexterity :' + enemy.dexterity + '</p></div>';
},
FightEvent: function() {
let getEnemy = document.querySelector(".enemy");
getEnemy.style.visibility = 'visible';
let getArena = document.querySelector(".arena");
let getPlayerHealth = document.querySelector(".health-player");
let getEnemyHealth = document.querySelector(".health-enemy");
let getPlayerGold = document.querySelector(".gold-player");
let getPlayerDexterity = player.dexterity;
let getEnemyDexterity = enemy.dexterity;
let playerAttack = function () {
let calcBaseDamage;
if (player.mana > 0) {
calcBaseDamage = player.strength * player.mana / 1000;
} else {
calcBaseDamage = player.strength * player.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(10));
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random() * Math.floor(player.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
let enemyAttack = function () {
let calcBaseDamage;
if (enemy.mana > 0) {
calcBaseDamage = enemy.strength * enemy.mana / 1000;
} else {
calcBaseDamage = enemy.strength * enemy.dexterity / 1000;
}
let offsetDamage = Math.floor(Math.random() * Math.floor(6))
let calcOutputDamager = calcBaseDamage + offsetDamage;
let numberOfHits = Math.floor(Math.random * Math.floor(enemy.dexterity / 6) / 2) + 1 ;
let attackValues = [calcOutputDamager, numberOfHits];
return attackValues;
}
if (getPlayerDexterity >= getEnemyDexterity) {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
} else {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + ' hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
getPlayerHealth.innerHTML = 'Health: ' + player.health;
}
}
} else if (getEnemyDexterity >= getPlayerDexterity) {
let enemyAttackValues = enemyAttack();
let totalDamage = enemyAttackValues[0] * enemyAttackValues[1];
player.health = player.health - totalDamage;
getArena.innerHTML = '<div><p>The ' + enemy.enemyType + 'hit you for ' + enemyAttackValues[0] + ' damage ' + enemyAttackValues[1] + ' times!</p></div>';
if (player.health <= 0) {
player.xp = player.xp + (enemy.xp / 2);
getArena.innerHTML ='<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
getPlayerHealth.innerHTML = 'Health: 0';
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
} else {
let PlayerAttackValues = playerAttack();
let totalDamage = PlayerAttackValues[0] * PlayerAttackValues[1];
enemy.health = enemy.health - totalDamage;
getArena.innerHTML = '<div><p>You hit the ' + enemy.enemyType + ' for ' + PlayerAttackValues[0] + ' damage ' + PlayerAttackValues[1] + ' times!</p></div>';
getPlayerHealth.innerHTML = 'Health: ' + player.health;
if (enemy.health <= 0) {
player.gold = player.gold + enemy.gold;
player.xp = player.xp + enemy.xp;
getArena.innerHTML = '<div<p>After a hard fought battle, you won. You also looted the ' + enemy.enemyType + ' and it had ' + enemy.gold + ' gold!<br>Gained ' + enemy.xp + ' XP!</p></div>';
getPlayerGold.innerHTML = 'Gold: ' + player.gold;
getPlayerHealth.innerHTML = 'Health: ' + player.health;
getEnemyHealth.innerHTML = 'Health: 0';
alert("Select another action before fighting again!");
} else {
getEnemyHealth.innerHTML = 'Health: ' + enemy.health;
}
}
}
},
the code seems to run fine unless you are going to lose, then it just breaks. I want to be able to say the first if else, then ask the user to hit a button before it continues. Like, if you don't kill them in one hit I would like it to show the updated health of the player and monster THEN run the if else statement again. I think the problem is if you dont OTK them it just dies. I hope that makes sense!
ps. https://squarecylinder.github.io/Stress-of-The-Kingdom/ here is a link to the game, but I used absolute positioning in CSS to line everything up, so I don't think it would look right in every display! I'm trying to figure that out as well!
The comments have already addressed the fact that you're stating Math.random instead of calling Math.random() at one point in your code, so I'll leave that alone. Other than that, this line doesn't have a semicolon at the end:
getArena.innerHTML = '<div><p>After a gruelling battle, you lost. Maybe you should rest before fighting again.<br>Gained ' + enemy.xp + '!'
It occurs twice in the code. I haven't set up a running sample of the code, so I don't know if this is your only remaining issue. If it still doesn't work after making this update, let me know and I'll remove this answer.
Side note:
Your random statements are a little bit needlessly complex. For example, with this line:
Math.floor(Math.random() * Math.floor(10))
there's no need to floor 10. 10 is already a flat integer. In fact, because you're using a lot of randomness, I'd use randojs.com to make all your randomness simpler and more readable. The line above can be written as just rando(0, 9). If you choose to use randojs, all you have to do is add the following line to the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>

Format time 24 hours to 12 hours with AM/PM and display inside popover fullCalendar

I want to format the time from 24 hours to 12 hours with AM/PM and display it in popover.
This is my code:
eventMouseover: function (event, jsEvent) {
var t1 = event.start;
var t2 = event.end;
$(this).popover({
html:true,
placement: 'left',
trigger: 'hover',
content: t1 + ' - ' + t2,
container: '#calendar'
}).popover('toggle');
}
I search for the answers here but it doesnt work in popover. So i decided to ask for it.
This is the code i used.
It works on here, but not in popover.
eventRender: function(event, element) {
var t1 = event.time;
var t2 = event.time2;
var tmpArr = t1.split(':'), time12;
if(+tmpArr[0] == 12) {
time12 = tmpArr[0] + ':' + tmpArr[1] + 'P';
} else {
if(+tmpArr[0] == 00) {
time12 = '12:' + tmpArr[1] + 'A';
} else {
if(+tmpArr[0] > 12) {
time12 = (+tmpArr[0]-12) + ':' + tmpArr[1] + 'P';
} else {
time12 = (+tmpArr[0]) + ':' + tmpArr[1] + 'A';
}
}
}
var tmpArrs = t2.split(':'), time13;
if(+tmpArrs[0] == 12) {
time13 = tmpArrs[0] + ':' + tmpArrs[1] + 'P';
} else {
if(+tmpArrs[0] == 00) {
time13 = '12:' + tmpArrs[1] + 'A';
} else {
if(+tmpArrs[0] > 12) {
time13 = (+tmpArrs[0]-12) + ':' + tmpArrs[1] + 'P';
} else {
time13 = (+tmpArrs[0]) + ':' + tmpArrs[1] + 'A';
}
}
}
element.find('.fc-content').append(t1 + "-" + t2 +);
}
Assuming you have moment.js included in your webpage (as FullCalendar needs it in any case) use the following code in place of declaring var t1 and var t2
var t1 = $.fullCalendar.moment(event.start).format("h:mm A")
var t2 = $.fullCalendar.moment(event.end ).format("h:mm A")
P.S. You don't need to work out the 12 hour format manually, moment.js does this for you

Javascript If statement not acknowledged

Here is the code
setHighScore: function() {
var highScore = 0;
if (!window.snake || !window.fpsls || !window.fmlts) {
return;
}
if (++bot.tickCounter >= 20) {
bot.tickCounter = 0;
var currentScore = parseInt(Math.floor(150 * (window.fpsls[window.snake.sct] +
window.snake.fam / window.fmlts[window.snake.sct] - 1) - 50) / 10);
if (Number(currentScore) > Number(highScore)) {
highScore = currentScore;
window.localStorage.setItem('highScoreLoc', highScore);
console.log('Current Score: ' + currentScore);
}
}
},
onFrameUpdate: function() {
// Botstatus overlay
var generalStyle = '<span style = "opacity: 0.35";>';
window.fps_overlay.innerHTML = generalStyle + 'FPS: ' +
userInterface.framesPerSecond.getFPS() + '</span>';
if (window.position_overlay && window.playing) {
// Display Personal High Score
userInterface.setHighScore();
window.scoreHuD.innerHTML = generalStyle +
'Your High Score: ' + parseInt(Number(window.localStorage.getItem('highScoreLoc')));
// Display the X and Y of the snake
window.position_overlay.innerHTML = generalStyle +
'X: ' + (Math.round(window.snake.xx) || 0) +
' Y: ' + (Math.round(window.snake.yy) || 0) +
'</span>';
}
It's meant to check if the score is bigger than the high score then save the new high score (if its bigger) and after that print it on screen. But it isn't for some reason
line 10 is the if statement
the 2 lines above it are to find the current score and i know it outputs the current score because of line 13
Its Tampermonkey
and the actual script https://github.com/Classicanon/Slither.io-bot/blob/master/bot.user.js For (Slither.io)

Open Weather Map - add a form field function for city weather (Jquery)

The script I have works well, but I need an additional search field for city and I have some problems with this feature.
This is my code I have # this time.
jQuery code
$(function () { var DEG = 'c'; var weatherDiv = $('#weather'), scroller = $('#scroller'), location = $('div.location');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
function locationSuccess(position) {
try {
var cache = localStorage.weatherCache && JSON.parse(localStorage.weatherCache);
var d = new Date();
if (cache && cache.timestamp && cache.timestamp > d.getTime() - 30 * 60 * 1000) {
var offset = d.getTimezoneOffset() * 60 * 1000;
var city = cache.data.city.name;
var country = cache.data.city.country;
$.each(cache.data.list, function () {
var localTime = new Date(this.dt * 1000 - offset);
addWeather(
this.weather[0].icon,
moment(localTime).calendar() + ' Uhr',
this.weather[0].description,
'<span class="forecast-temp-blue">' + convertTemperature(this.main.temp_min) + '°' + DEG + '</span> | <span class="forecast-temp-red">' + convertTemperature(this.main.temp_max) + '°' + DEG + '</span>',
'<b>' + this.main.humidity + '%</b>',
'<b>' + miles2km(this.wind.speed) + '</b>',
'<b>' + convertDeg2Comp(this.wind.deg) + '</b>'
);
});
location.html(city + ', <b>' + country + '</b>');
weatherDiv.addClass('loaded');
showSlide(0);
} else {
var weatherAPI = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&lang=de&callback=?';
$.getJSON(weatherAPI, function (response) {
localStorage.weatherCache = JSON.stringify({
timestamp: (new Date()).getTime(),
data: response
});
locationSuccess(position);
});
}
} catch (e) {
showError("We can't find information about your city!");
window.console && console.error(e);
}
}
function addWeather(icon, day, description, temperature, humidity, windspeed, winddeg) {
var markup = '<li>' +
'<div class="row-body">' +
'<div class="forecast-day">' + day + '</div>' +
'<div class="forecast-cond">' + description + '</div>' +
'<img src="assets/img/icons/' + icon + '.png" /><br>' +
'<div class="forecast-left-side">' +
'<div class="forecast-temp"><img src="assets/img/icons/temp.png" />' + temperature + '</div>' +
'<div class="humidity"><img src="assets/img/icons/drop.png" />' + humidity + '</div>' +
'</div>' +
'<div class="forecast-right-side">' +
'<div class="wind"><img src="assets/img/icons/wind.png" />' + windspeed + ' km/h</div>' +
'<div class="windr"><img src="assets/img/icons/windr.png" />' + winddeg + '</strong></div>' +
'</div></div></li>';
scroller.append(markup);
}
var currentSlide = 0;
weatherDiv.find('a.previous').click(function (e) {
e.preventDefault();
showSlide(currentSlide - 1);
});
weatherDiv.find('a.next').click(function (e) {
e.preventDefault();
showSlide(currentSlide + 1);
});
$(document).keydown(function (e) {
switch (e.keyCode) {
case 37:
weatherDiv.find('a.previous').click();
break;
case 39:
weatherDiv.find('a.next').click();
break;
}
});
function showSlide(i) {
var items = scroller.find('li');
if (i >= items.length || i < 0 || scroller.is(':animated')) {
return false;
}
weatherDiv.removeClass('first last');
if (i == 0) {
weatherDiv.addClass('first');
} else if (i == items.length - 1) {
weatherDiv.addClass('last');
}
scroller.animate({
left: (-i * 100) + '%'
}, function () {
currentSlide = i;
});
}
function locationError(error) {
switch (error.code) {
case error.TIMEOUT:
showError("A timeout occured! Please try again!");
break;
case error.POSITION_UNAVAILABLE:
showError('We can\'t detect your location. Sorry!');
break;
case error.PERMISSION_DENIED:
showError('Please allow geolocation access for this to work.');
break;
case error.UNKNOWN_ERROR:
showError('An unknown error occured!');
break;
}
}
function convertTemperature(kelvin) {
return Math.round(DEG == 'c' ? (kelvin - 273.15) : (kelvin * 9 / 5 - 459.67));
}
function convertDeg2Comp(num) {
val = Math.round((num - 22.5) / 45);
arr = ["N", "NO", "O", "SO", "S", "SW", "W", "NW"];
return arr[val % 8];
}
function miles2km(num) {
val = (num / 0.62137).toFixed(2);
return val;
}
function showError(msg) {
weatherDiv.addClass('error').html(msg);
}
});
and here is my html code
<div id="weather">
<div class="location"></div>
<ul id="scroller">
<!-- The forecast items will go here -->
</ul>
Previous Next
<form id="search">
<input id="getcity" name="q" type="text" size="40" placeholder="Stadtname" onclick="httpGetCity()"/>
</form>
<input id="gloc" type="submit" title="W3C Geolocation" value="" />
</div>
The user should have the possibility to enter a city name and the weather data should be displayed in the same widget for the entered city.
How can we achieve this?

Categories

Resources