AnimateCC Canvas calling functions - javascript

I'm trying to change this code that I made from actionscript 3 to html5 canvas. I’m with doubt about calling functions that I created, for example:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(count){
cleanSelection();
count = 0;
return count;
}
I want to make this function below be able to call maxSelection() which calls cleanSelection()
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click()
{
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection(count);
}
}
How can I call these functions?

You Should put "bind(this)" in all methods:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(c){
cleanSelection.bind(this)();
c= 0;
return c;
}
var count = 0;
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click() {
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection.bind(this)(count);
}
}

Related

Toggling between Boolean variable

I'm wondering how you would toggle between two boolean variables. This works correctly the first time running the code but then after running it a second time the output isn't correct.
Output first time running switchPlayer():
player1.isActive = false,
player2.isActive = true
Output second time running switchPlayer():
player1.isActive = true,
player2.isActive = true
Below is the code I wrote:
var Player = function(score, isActive){
this.score = score;
this.isActive = isActive;
}
Player.prototype.toggleIsActive = function(){
if(this.isActive === false){
this.isActive = true;
} else{
this.isActive = false;
}
}
function switchPlayer(){
if(player1.isActive === true){
player1.toggleIsActive();
player2.toggleIsActive();
} else{
player1.isActive = true;
}
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);
switchPlayer();
switchPlayer();
You can simplify it like this:
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
ToggleIsActive should just be the opposite of what it once was. Also note that switchPlayer only calls toggle with no specific logic.
You can achieve this by removing the if/else from the switchPlayer() implementation:
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
Also, consider simplifying your toggleIsActive() method on the Player prototype like so:
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
Here's a full example:
var Player = function(score, isActive){
this.score = score;
this.isActive = isActive;
}
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')
switchPlayer();
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')
switchPlayer();
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')
let player1 = {};
let player2 = {};
player1.isActive = false;
player2.isActive = true;
function toggle () {
player1.isActive = !player1.isActive;
player2.isActive = !player2.isActive;
console.log('player1', player1.isActive, 'player2', player2.isActive);
}
<button onclick="toggle()">Toggle</button>

Trying to run a while loop for a specified amount of time...Not exiting

So, I have a localhost website where you can press a button to start a while loop. My intent is to loop through this while loop and "wait" for button clicks from the additional buttons, until 135 seconds have passed. Then, it is supposed to exit the loop. When the code (which is embedded in html) is executed, it only gets to printing "test1", while failing to leave the loop and print test2.
allyTrack = 0;
scaleTrack = 0;
enemyTrack = 0;
allyString = ""
scaleString = ""
enemyString = ""
allyClicked = false;
scaleClicked = false;
enemyClicked = false;
function allyAdd(){
allyClicked = true;
}
function scaleAdd(){
scaleClicked = true;
}
function enemyAdd(){
enemyClicked = true;
}
//Making the long vectors
function startGame(){
var startTime = new Date().getTime();
//var currentTime = new Date().getTime();
while(true){
document.getElementById('test').innerHTML = 'test1';
if(allyClicked){
allyTrack += 1;
allyString.append(allyTrack.toString())
allyClicked = false;
}
else if(scaleClicked){
scaleTrack += 1;
scaleString.append(scaleTrack.toString())
scaleClicked = false;
}
else if(enemyClicked){
enemyTrack += 1;
enemyString.append(enemyTrack.toString())
enemyClicked = false;
}
else{
allyString.append(allyTrack.toString())
scaleString.append(scaleTrack.toString())
enemyString.append(enemyTrack.toString())
}
currentTime = new Date().getTime();
if(currentTime-startTime > 2000){
break;
}
}
document.getElementById('test').innerHTML = 'test2';
document.getElementById('list').innerHTML = allyString + '\n' + scaleString + '\n' + enemyString;
}
String.append() doesn't belong to JavaScript. I replaced it with concat() and now works.
You could use the global setTimeout method:
function loop(callback, interval) {
return setTimeout(function() {
callback();
}, +interval);
}
loop(function() {
console.log("Looping...");
}, 1000);

Trigger a redirect to a page on form submission after three incorrect attempts in Javascript

I have a page with a coupon field, the page should allow three incorrect attempts after which it has to redirect to another page. I tried setting counters but couldn't make it work. Please help on the below code.
function validateCoupon() {
var couponkey = ["ABCDEF1", "ABCDEF2", "ABCDEF3", "ABCDEF4", "ABCDEF5", "ABCDEF6", "ABCDEF7"];
var keyinput = $('#COUPON').val().trim().toUpperCase();
if (couponkey.indexOf(keyinput) > -1) {
return true;
}
else {
alert("Invalid Key");
return false;
}
}
After three failed attempts, I want to redirect to another page.
It's possible you kept the counter inside of the function? That might've reset it each time you called the function. You could keep the counter outside the scope of the function.
Try this out.
let timesAttemped = 0;
function validateCoupon() {
var couponkey = ["ABCDEF1", "ABCDEF2", "ABCDEF3", "ABCDEF4", "ABCDEF5", "ABCDEF6", "ABCDEF7"];
var keyinput = $('#COUPON').val().trim().toUpperCase();
if (couponkey.indexOf(keyinput) > -1) {
return true;
}
else if (timesAttempted < 3) {
alert("Invalid Key");
timesAttempted++
return false;
} else if (timesAttempted === 3) {
window.location.href = "http://www.lolrofl.com" // any redirect logic here
}
}
You can accomplish this without polluting global scope with closure:
function couponValidator() {
var couponkey = ["ABCDEF1", "ABCDEF2", "ABCDEF3", "ABCDEF4", "ABCDEF5", "ABCDEF6", "ABCDEF7"];
var attempts = 3;
return function () {
var keyinput = $('#COUPON').val().trim().toUpperCase();
if (couponkey.indexOf(keyinput) > -1) {
return true;
}
else if (--attempts <= 0) {
window.location.href = "your_url"
} else {
alert("Invalid Key");
return false;
}
}
}
var validate = couponValidator();

JavaScript function sequence (Phaser game)

can anyone explain how the code below works ? this is a timed animation that uses the Phaser Javascript framework.
I can't work out how this works in sequence, e.g. how each function is triggered, doIntro0() followed by doIntro1()
For brevity , I have ommited the majorty of doIntro functions.
showIntro(); // initial call
var introFlags = new Object();
function showIntro(){
if (!introFlags.step0){
if (!introFlags.doingStep0){
introFlags.doingStep0 = true;
doIntro0();
}
return
}
if (!introFlags.step1){
if (!introFlags.doingStep1){
introFlags.doingStep1 = true;
doIntro1();
}
return
}
}
function doIntro0(){
player.animations.play("rest");
player.x = 160+32;
princess.animations.play("rest0");
princess.x = 240;
graves.alpha = 0;
devil.alpha = 0;
armour = game.add.sprite(140,354,"armour");
setTimeout(endIntro0,500);
}
function endIntro0(){
introFlags.step0 = true;
}
function doIntro1(){
blackBg.alpha = 0.2;
setTimeout(endIntro1,2000);
}
function endIntro1(){
introFlags.step1 = true;
}

Javascript callback managment

I'm having trouble with designing a class which exposes its actions through callbacks. Yes my approach works for me but also seems too complex.
To illustrate the problem I've drawn the following picture. I hope it is useful for you to understand the class/model.
In my approach, I use some arrays holding user defined callback functions.
....
rocket.prototype.on = function(eventName, userFunction) {
this.callbacks[eventName].push(userFunction);
}
rocket.prototype.beforeLunch = function(){
userFunctions = this.callbacks['beforeLunch']
for(var i in userFunctions)
userFunctions[i](); // calling the user function
}
rocket.prototype.lunch = function() {
this.beforeLunch();
...
}
....
var myRocket = new Rocket();
myRocket.on('beforeLunch', function() {
// do some work
console.log('the newspaper guys are taking pictures of the rocket');
});
myRocket.on('beforeLunch', function() {
// do some work
console.log('some engineers are making last checks ');
});
I'm wondering what the most used approach is. I guess I could use promises or other libraries to make this implementation more understandable. In this slide using callbacks is considered evil. http://www.slideshare.net/TrevorBurnham/sane-async-patterns
So, should I use a library such as promise or continue and enhance my approach?
var Rocket = function () {
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: null,
height: 0,
status: null
};
this.listener = {
};
}
Rocket.prototype.report = function () {
for (var i in this.rocketStatus) {
console.log(this.rocketStatus[i]);
};
};
Rocket.prototype.on = function (name,cb) {
if (this.listener[name]){
this.listener[name].push(cb);
}else{
this.listener[name] = new Array(cb);
}
};
Rocket.prototype.initListener = function (name) {
if (this.listener[name]) {
for (var i = 0; i < this.listener[name].length; i++) {
this.listener[name][i]();
}
return true;
}else{
return false;
};
}
Rocket.prototype.launch = function () {
this.initListener("beforeLaunch");
this.rocketStatus.status = "Launching";
this.move();
this.initListener("afterLaunch");
}
Rocket.prototype.move = function () {
var that = this;
that.initListener("beforeMove");
if (that.goingToMoon) {
that.rocketStatus.height += that.velocity;
}else{
that.rocketStatus.height -= that.velocity;
};
that.rocketStatus.velocity = that.velocity;
if (that.velocity != 0) {
that.rocketStatus.status = "moving";
}else{
that.rocketStatus.status = "not moving";
};
if (that.velocity >= 600){
that.crash();
return;
}
if (that.rocketStatus.height == 2000 && that.goingToMoon)
that.leaveModules();
if (that.rocketStatus.height == that.heightMoon)
that.landToMoon();
if (that.rocketStatus.height == 0 && !that.goingToMoon){
that.landToEarth();
return;
}
that.report();
that.initListener("afterMove");
that.timer = setTimeout(function () {
that.move();
},1000)
}
Rocket.prototype.stop = function () {
clearTimeout(this.timer);
this.initListener("beforeStop");
this.velocity = 0;
this.rocketStatus.status = "Stopped";
console.log(this.rocketStatus.status)
this.initListener("afterStop");
return true;
}
Rocket.prototype.crash = function () {
this.initListener("beforeCrash");
this.rocketStatus.status = "Crashed!";
this.report();
this.stop();
this.initListener("afterCrash");
}
Rocket.prototype.leaveModules = function () {
this.initListener("beforeModules");
this.rocketStatus.status = "Leaving Modules";
this.initListener("afterModules");
}
Rocket.prototype.landToMoon = function () {
this.initListener("beforeLandToMoon");
this.rocketStatus.status = "Landing to Moon";
this.goingToMoon = false;
this.initListener("afterLandToMoon");
}
Rocket.prototype.landToEarth = function () {
this.initListener("beforeLandToEarth");
this.stop();
this.rocketStatus.status = "Landing to Earth";
this.initListener("afterLandToEarth");
}
Rocket.prototype.relaunch = function () {
this.initListener("beforeRelaunch");
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: 200,
height: 0,
status: "relaunch"
};
this.launch();
this.initListener("afterRelaunch");
}
init;
var rocket = new Rocket();
rocket.on("afterLaunch", function () {console.log("launch1")})
rocket.on("afterLandToMoon", function () {console.log("land1")})
rocket.on("beforeLandToEarth", function () {console.log("land2")})
rocket.on("afterMove", function () {console.log("move1")})
rocket.on("beforeLaunch", function () {console.log("launch2")})
rocket.launch();
You can add any function before or after any event.
This is my solution for this kinda problem. I am not using any special methods anything. I was just wonder is there any good practise for this like problems. I dig some promise,deferred but i just can't able to to this. Any ideas ?

Categories

Resources