JavaScript Conditionals not working - javascript

I'm sorry I didn't search for another topic I thought this was a bit too specific, ok now that's out of the way!
When this is run missionButton.click(); is always ran, even though CheckHealth() is = to 0 it's like it's just skipping over the original if statement, is this normal for JavaScript (I'm used to other languages)
//__Action_Functions__
// When you're at zero health.
function Hospital(){
location.assign("http://www.gangwarsmobile.com/index.php?p=hospital");
var HospitalUse = HospitalID;
HospitalUse.click();
setTimeout(location.assign("http://www.gangwarsmobile.com/index.php?p=crimes"),5000);
}
//__Does Mission__
function start(){
var missionButton = CrimeID; //CrimeID is the ButtonID from the /crimes page/ variables at the top of this script.
if(CheckHealth() === 0){Hospital();}
else if (CheckStamina() > 0);{missionButton.click();}
}
I can't see a reason why this will not work.
EXTRA
I'm using TamperMonkey, if that makes any difference.

Did you forget to take out ; after the () > 0 ?
Original:
if(CheckHealth() === 0){Hospital();}
else if (CheckStamina() > 0);{missionButton.click();}
Fixed:
if(CheckHealth() === 0){
Hospital();
} else if (CheckStamina() > 0) {
missionButton.click();
}

Related

Phaser 2 buttons are needed to work text? What's happening?

I'm working on a dialogue system for my game. I have it almost finished, but I'm stuck on one weird bug. Here is the code for it in the update method. Assume everything with this in front of it was declared in the create method.
if ((this.checkCollision(this.p1, this.goodLamb) || this.checkCollision(this.p1, this.stiches)) && Phaser.Input.Keyboard.JustDown(this.keyT)) {
this.talking = true;
}
if (this.talking == true){
if (this.checkCollision(this.p1, this.goodLamb) || this.checkCollision(this.p1, this.stiches)) {
if (this.has("spool") && this.has("needleOne") && this.has("needleTwo")){
this.line1.setText('Good Lamb: Oh, thanks Peef! Now we can fix Stiches!');
this.line2.setText('Peef: Glad to help. I know how painful rips are.');
}
else if (!(this.has("spool")) || !(this.has("needleOne")) || !(this.has("needleTwo"))) {
this.line1.setText('Good Lamb: Help! Stiches ripped herself again! Can you get the sewing supplies?');
this.line2.setText('Peef: Oh gosh! Sit tight Stiches. Ill be back soon!');
}
}
if(this.keyA.isDown) {
this.p1.setVelocityX(0);
}
else if(this.keyD.isDown) {
this.p1.setVelocityX(0);
}
if(this.p1.body.touching.down && Phaser.Input.Keyboard.JustDown(this.keyW)) {
this.p1.body.setVelocityY(0);
}
if ((this.checkCollision(this.p1, this.goodLamb) || this.checkCollision(this.p1, this.stiches)) && Phaser.Input.Keyboard.JustDown(this.keyT)){
this.talking = false;
this.line1.setText('');
this.line2.setText('');
}
}
I admit this may be an outrageously overly complicated text system, but it's the only one I've gotten to work. When the player presses the talk button when touching an npc, the game checks for collision and sets the talking Boolean to true. If that Boolean is true, the game disables the player's movement and displays dialogue based on who the npc is and if they met the criteria for completing the associated quest, in this case gathering 2 needles and a spool of thread. For the player to continue, they have to press the talk button again, which turns the talking Boolean back to false, restores movement and makes the text disappear.
It's the last step that's not working. For some reason, when the player presses the talking button again, the talking Boolean doesn't change back and none of the associated actions happen.
The only solution I currently have is to change the button that makes the text disappear to a different button from the talking button. This lets things work as intended, but it's also an awkward button set up for the player.
Is there a solution, or am I just going to have to live with this issue?
If it helps, I'm using Phaser 3 in VSCode employing arcade physics.
No 1 Button is enough. What is happening, is hard to say, because your code is pretty complicated. In any case the main problem is that your if/else blocks are setup incorrect.
I cleaned it up and tried teh if/elseblocks in the correct order, so that they reflect, what you want to happen.
Although it is hard to say since, your code snippet covers only a small part of your update function.
if ((this.checkCollision(this.p1, this.goodLamb) || this.checkCollision(this.p1, this.stiches)) && Phaser.Input.Keyboard.JustDown(this.keyT)) {
if(this.talking == false){
this.talking = true;
if (this.has("spool") && this.has("needleOne") && this.has("needleTwo")) {
this.line1.setText('Good Lamb: Oh, thanks Peef! Now we can fix Stiches!');
this.line2.setText('Peef: Glad to help. I know how painful rips are.');
}
else if (!(this.has("spool")) || !(this.has("needleOne")) || !(this.has("needleTwo"))) {
this.line1.setText('Good Lamb: Help! Stiches ripped herself again! Can you get the sewing supplies?');
this.line2.setText('Peef: Oh gosh! Sit tight Stiches. Ill be back soon!');
}
/* this velocity blocks seem strange, but if it works for you why not */
if (this.keyA.isDown || this.keyD.isDown) {
this.p1.setVelocityX(0);
}
if (this.p1.body.touching.down && Phaser.Input.Keyboard.JustDown(this.keyW)) {
this.p1.body.setVelocityY(0);
}
} else {
this.talking = false;
this.line1.setText('');
this.line2.setText('');
}
}
Try to keep if/else nesting low, and try to group condition to avoid mistakes and performance issues (for example: multiple calculations / collision checks)
Update / Improvement:
Here the same code from above just more concise, and easier to understand / read
/* default text values is empty string */
let textLine1 = '';
let textLine2 = '';
/* I put "Phaser.Input.Keyboard..." first, for performance reasons */
if (Phaser.Input.Keyboard.JustDown(this.keyT) && (this.checkCollision(this.p1, this.goodLamb) || this.checkCollision(this.p1, this.stiches))) {
if(this.talking == false){
let hasAllItems = this.has("spool") && this.has("needleOne") && this.has("needleTwo");
if (hasAllItems) {
textLine1 = 'Good Lamb: Oh, ...';
textLine2 = 'Peef: Glad to help. ...';
} else {
textLine1 ='Good Lamb: Help! ...';
textLine2 = 'Peef: Oh gosh! ...';
}
/* just set the velocity always to 0, no if/else is needed */
this.p1.setVelocity(0);
}
// toggles: true <=> false
this.talking = !this.talking;
/* set the text's object in one place, no matter the text */
this.line1.setText(textLine1);
this.line2.setText(textLine2);
}

While loop inside if/else

while(playerTwoHealth > 0 && playerOneHealth > 0){
changeScreen("Player1's Turn", "<button id='player1Attack'>Attack</button><button id='player1Defend'>Defend</button>");
$("#player1Attack").click(function(){
var successfulAttack = alert("Did you get this question right?");
if(successfulAttack === true){
playerTwoHealth = playerTwoHealth - 1;
if(playerTwoHealth === 0){
break;
};
}else{
};
});
};
I'm making a educational mathematics game, and In this section of code, I am trying to test the reaction to questions being asked. The function changeScreen changes the title and paragraph sections of the screen to be the specified HTML. On line no. 7-9, the if/else statement is designed to test if a player's health has reached 0, and if it has, break the while loop declared on line 1. However, the break statement throws an illegal break statement error. Please post any suggestions on how to solve.
Move the click event outside of the loop. In fact you don't really need a break since the while loop condition will not be valid when health is 0
while(playerTwoHealth > 0 && playerOneHealth > 0){
changeScreen("Player1's Turn", "<button id='player1Attack'>Attack</button><button id='player1Defend'>Defend</button>");
};
$("#player1Attack").click(function(){
var successfulAttack = alert("Did you get this question right?");
if(successfulAttack === true){
playerTwoHealth = playerTwoHealth - 1;
if(playerTwoHealth === 0){
// Do stuff
};
} else {
};
});
Your break statement is inside a function which you are binding to the click event, so it's not inside the while loop. You should never bind events within a while loop, as this will try to bind the event every time it loops around.
Also, you might want to replace alertwith prompt

DOM manipulation slow in Chrome (hiding / showing elements)

I've put together a small test at http://jsfiddle.net/Hwqb3/3/ this morning. This is on the back of a larger project with pagination. I have tried this with native JS and jQuery. The test uses jQuery.
A quick search on SO says that Chrome handles things poorly if background-size is set, but this is not the case here. No trace of background-size in the source, and inspecting elements shows no background-size being set / inherited.
Ignore the initial page load while 5,000 elements are added to the list. It is only a few seconds, but it just so there are some elements to test with.
In Firefox 18.0.1, the moving between pages is almost instant and in IE9 there is maybe a 0.1s delay between mouse click and the paged results refreshing; However, in Chrome (24.0.1312.57 m) the delay is a noticeable 1-2 seconds.
I spent the majority of my night last night pouring over my code to see if I can find the cause before writing this test. This is bare bones and still has the issue.
I can only assume that Chrome is handling the element.style.display=''; poorly. Without that (even looping through the 5,000 elements to display='none') the thing is snappy.
Any ideas? Client wants pagination on a result set of around 4,000 - 7,500, but doesn't want page reloads and doesn't understand that they should apply filters to whittle that list down to <100, as no one is ever going to page through 200 - 375 pages looking for something specific.
Last resort is AJAX calls, which may be slightly quicker on Chrome. Untested yet though.
Thanks in advance.
Code from jsfiddle, excluding the jQuery CDN link
HTML:
First
Previous
Next
Last
<br>
<ul id='list'>
</ul>
JS:
window.onload=function() {
window.list=$('#list'), window.max=20, window.page=0, window.pages=0, window.elements;
var i=0;
while(i<5000) {
i++;
list.append("<li>"+i+"</li>");
}
jump('first');
};
function jump(operation) {
window.elements=list.find('li');
window.pages=Math.ceil(window.elements.length/window.max);
if(operation=='first') {
window.page=0;
}
else if(operation=='last') {
window.page=(window.pages-1);
}
else if(operation=='+1') {
window.page=(window.page+1);
if(window.page>=window.pages) {
window.page=(window.pages-1);
}
}
else if(operation=='-1') {
window.page=(window.page-1);
if(window.page<0) {
window.page=0;
}
}
var showing=0, total=0;
window.elements.each(function() {
var show=false, self=$(this);
if(showing<window.max) {
if(total>=(window.page*window.max) && total<((window.page*window.max)+window.max)) {
self[0].style.display='';
showing++;
show=true;
}
}
if(!show) {
self[0].style.display='none';
}
total++;
});
}
check this
window.onload = function() {
window.list = $('#list'),
window.max = 20,
window.page = 0,
window.pages = 0,
window.elements;
var i = 0;
var html = '';
while(i < 5000) {
i++
html += '<li>' + i + '</li>';
}
list.append(html);
window.elements = list.find('li');
window.pages = Math.ceil(window.elements.length/window.max);
jump('first');
};
function jump(operation) {
if (operation == 'first')
window.page = 0;
else if (operation == 'last')
window.page = window.pages - 1;
else if (operation == '+1')
(window.page + 1 >= window.pages) ? window.page = window.pages - 1 : window.page++ ;
else if (operation == '-1')
(window.page - 1 < 0) ? window.page = 0 : window.page--;
var index = page * window.max;
window.elements.hide().slice(index, index + window.max).show();
}
http://jsfiddle.net/Hwqb3/16/

jQuery-implemented Calculator

guys. I am trying to create a web-based calculator with basic operations using jQuery. I already have implemented the addition operation. Now, I am hooked in subtraction.
Here is a code snippet when you click on the minus button:
$("#btnSub").click(function () {
holdValue = $("#result").val();
currentValue = $("#result").val("0");
flagSub = "1";
flagNotEmpty = "0";
flagDecimal = "0";
});
Here is a code snippet when you click the equals button:
$("#btnEquals").click(function () {
if (flagNotEmpty == "0") {
alert("Missing Value.");
} else {
if (flagAdd == "1") {
currentValue = $("#result").val();
var output = parseFloat(holdValue) + parseFloat(currentValue);
$("#result").val(parseFloat(output));
} else if (flagSub == "1") {
currentValue = $("#result").val();
var output2 = parseFloat(holdValue) - parseFloat(currentValue);
$("#result").val(parseFloat(output2));
}
}
flagSub = "0";
flagAdd = "0";
flagNotEmpty = "0";
flagDecimal = "0";
});
Variables functions:
flagSub: used to determine that the operation choosen is subtraction
flagNotEmpty: used to determine if a number is pressed after selecting an operator. Displays error message if equal sign is clicked on right after the operator button.
flagDecimal: used to tell the program that a decimal has already been entered. Display error message for decimal point duplication.
Problem with this program is that it cannot perform subtraction when it is the first operation you do. That is, when the browser loads the UI and you do subtraction, nothing happens. BUT, when you do, for example, click 1 + 2 = then the program displays 3 in the textbox. Without refreshing the page, click - 10 =. Difference is displayed.
To start from the beginning, please refresh the page; will just add the CLEAR button after I am done with all the operations.
Just want to know what is wrong with my algorithm. For the complete code with html and css, here is its fiddle.
By the way, I have just started learning jQuery so please forgive me for the kind of messy and might be inefficient way of coding. Help is really much appreciated. Thanks in advance.
flagAdd needs to be initialized, you can alter the btnSub handler to do that
$("#btnSub").click(function () {
holdValue = $("#result").val();
currentValue = $("#result").val("0");
flagAdd = "0";
flagSub = "1";
flagNotEmpty = "0";
flagDecimal = "0";
});
alternatively you could initialize it in the document ready handler Fiddle

GC_CURRENT - Phonegap App crashes

I want to fill a lottery field with random numbers when the user shakes the phone.
My shake detection
function watchForShake(threshold)
{
console.log ("Am Watching for shakes");
axl.watchAcceleration(
function (Accel)
{
if (true === Accel.is_updating){
return;
}
var diffX = Accel.x - prevX;
if (diffX >= threshold)
{
console.log("Phone shaken");
if (gettingRandomNumbers==false){
randomNumbers();
}
}
prevX = Accel.x
}
, function(){}
, {frequency : 100}
);
}
this Method sets a number in the lottery field as selected.
function clickNumber(number)
{
console.log("ClickNumber invoked with number "+number);
tNumber = $(number).html();
tPosition = $(number).position();
if($(number).hasClass('selected'))
{
lottoNumbers.pop(number);
console.log("number.hasClass = true");
$(number).removeClass('selected');
$(number).children().remove();
}else{
if (lottoNumbers.length <= 5) {
lottoNumbers.push(number);
console.log("number.hasClass = false");
$(number).addClass('selected');
$(number).append('<img src="assets/images/spielschein_kreuz.png" style="position:absolute;top:'+ tPosition.top +'px;left:'+ tPosition.left +'px;"/>');
}
}
}
The next method gets random numbers and sets them in the lotteryfield (using jquery). I think this method is what causes the memory leak. The app doesnt crash when I take out the inner for-loop, but I dont know how to fix it.
function randomNumbers(){
console.log("Am Getting Random Numbers");
gettingRandomNumbers=true;
counter = 0;
clearAllNumbers();
while (counter < 6){
zufallsZahl = Math.floor((Math.random()*49)+1);
zufallsZahlen[counter]=zufallsZahl;
if (isUniqueNumber){
counter++;
console.log("Zufallszahl: "+zufallsZahl);
clickNumber($('#ticket_detail .tipfield .tipbox ul li').filter(function(){return $(this).html() == zufallsZahl;}));
}
}
gettingRandomNumbers = false;
}
I dont know what exactly causes the GC_CONCURRENT message. The app crashes and freezes without an explicit error message. After several shakes detected, the app crashes.
All variables are initialized in the document.ready() method in the index.html file. I dont create new objects on every shake, do I?
any help or hints greatly appreciated.
thank you,
Daniel

Categories