createjs newbie issue - changing score on event - createjs

I'm trying to decrease score of my hero on event. Specifically, when she misses her score decreases.
I've tried putting the event in the tick function and outside the tick function but both continue to decrement the score continuously.
function reducePower()
{
princessPower -= 1;
text.text = "Princess Power: " + princessPower;
gameStage.update();
}
Within the tick() function this code exists:
if(hitOrMiss == 'Miss')
{
reducePower();
//setTimeout(makeMada, 1);
}
The gameStage.update here causes the score to reduce constantly, I just want it to take one off every time the condition is met i.e. once when she misses - as in onChange. I see there is a createjs onchange function but when I try to use it, it fails for me, I'm probably using it wrong. The code is large so not saved it all but I've created a JSfiddle here: http://jsfiddle.net/3AJ48/
Any help appreciated.
Thanks,

I fixed this one myself. The score needed to be added outside the tick function as below for those who looked at the JSFiddle:
function onDeviceReady()
{
$("#image").rotate(
{
bind:
{
touchstart: function()
{
var rot = Math.floor ( Math.random() *24 ) *15;
value += rot;
$(this).rotate({ animateTo:value});
if(value % 2 === 0)
{
setTimeout(reduceMonsterPower, 2500);
setTimeout(hit,1000);
}
else
{
setTimeout(reducePower, 1500);
setTimeout(miss,1000);
}
}
}
});
}
function reducePower()
{
princessPower = princessPower - 20;
}
function reduceMonsterPower()
{
monsterPower = monsterPower - 40;
}

Related

change setInterval to requestAnimationFrame

How do I change the following code? I did not know how to convert this code. Can anyone help me?
let timer = ref(30);
let interval = setInterval(() => {
if (timer.value === 0) {
clearInterval(interval)
alert('done')
} else {
timer.value--
}
}, 1000)
This should work the same way as your original code. Of course, you don't need to pass an interval since requestAnimationFrame will be timed to the screen refresh rate.
let timer = ref(30);
function mainLoop() {
if (timer.value === 0) {
alert('done')
} else {
timer.value--
}
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
First the function mainLoop is defined. Then, it is called through requestAnimationFrame at the end of the script to 'kickstart' the loop. The subsequent calls to requestAnimationFrame within the function are there to maintain it.

How to correctly use setInterval for multiple functions being called repeatedly in React Native

I am building a simple app in React Native that aims to flash different colors on the screen at certain time intervals. My implementation is as follows:
useEffect(() => {
var blinkOnValue;
var blinkOffValue;
function blinkOn() {
const colorAndWord = getRandomColor(colorArray);
setBackground(colorAndWord.color);
}
function blinkOff() {
setBackground('#F3F3F3');
}
if (strobeStart) {
if (on) {
blinkOnValue = setInterval(() => {
blinkOn();
setOn(false);
}, info.length * 1000);
} else {
blinkOffValue = setInterval(() => {
blinkOff();
setOn(true);
}, info.delay * 1000);
}
}
return () => {
on ? clearInterval(blinkOnValue) : clearInterval(blinkOffValue);
};
}, [colorArray, info.delay, info.length, on, strobeStart]);
The blinkOn function sets the background a certain color and the blinkOff function sets the background a default light gray-ish color. These functions should alternate back and forth, blinking on and off at different intervals. For example, if info.length is 2 and info.delay is 0.5, then the color should flash on for 2 seconds and then the screen should be light gray for 0.5 seconds and repeat. However, the duration of both of the blinkOn and blinkOff are happening for the same amount of time, no matter what the two values are. Sometimes it uses the value from info.length, and sometimes it uses the value from info.delay which is also quite strange.
I think it has something to do with components mounting and unmounting correctly but honestly I am quite lost. If anyone has any advice on how to make this code consistently work where it flashes appropriately I would really appreciate it.
Instead of trying to time your events just right, I suggest using a single timer and computing the blink state from the current system time.
var oldState = true;
function blink() {
var ms = new Date().getTime();
var t = ms % (info.delay + info.length);
var state = (t < info.length ? true : false);
if (state == oldState) return;
if (state) {
blinkOn();
}
else
{
blinkOff();
}
oldState = state;
}
Now set a short timer to check the time and update the blink state as needed:
setInterval( () => blink(), 100 );

Restart a countdown in Livewire with Alpine.js

I try to build a survey, where a countdown should show a modal each 10 seconds, when the user waits too long.
The countdown should be stopped while the modal is shown and it should be restarted when the "back to survey" button is clicked and also when a question is answered.
I tried it that way with the alpine object:
let Countdown = () => {
return {
open: false,
heart:'',
ccdown(time,hue)
{
time -= 1;
hue += 60;
if (time > 0) {
this.heart=setTimeout(this.ccdown, 500, time, hue);
console.log("time: "+ time);
console.log("hue: " + hue);
}
if(time == 0) {
console.log("done");
this.open = true;
}
}
}
}
This is how I call the function in the blade component:
<div x-data="Countdown()" x-init="ccdown(10,30)">
...
</div>
But it stops after the second time.
Could anybody show me the problem?
The problem is here:
setTimeout(this.ccdown, 500, time, hue);
setTimeout only accepts two arguments, the function, and the timeout. If you have to call the function using arguments, you should either use bind or create a new function. So either it should be:
setTimeout(() => {
this.ccdown(time, hue)
}, 500)
Or,
setTimeout(this.ccdown.bind(this, time, hue), 500)

Trouble Animating svgX of HighCharts Column Label

BOUNTY UPDATE: I'm putting a bounty on this, so I wanted to give a little bit more information in case someone comes up with a different solution than modifying my code. The object is to animate the actual category position in HighCharts for bar and column charts. Animating the actual "bar/columns" seems to be built in to HighCharts, however, the label positions is what I'm having trouble with. See below for JSFiddle. Also, I know this question is dealing with SVG, but I need the animation support in IE8 as well.
I'm currently on a mission to animate the reorganization of categories in HighCharts for bar and column charts.
I have bar charts working fine, with the ability to reorganize categories and labels, with labels animating with the following code:
$(this).animate({'svgY': c.labelPositions[myX]}, {'duration': animDuration, 'queue': false});
Now I'm working on the columns, and I'm having significant trouble getting the labels to animate. The code is relatively the same:
$(this).animate({'svgX': c.labelPositions[myX]}, {'duration': animDuration, 'queue': false});
I'm using jQuery SVG to allow the animation of SVG elements, you can find it here.
You can view the jsFiddle I'm working on here. Just click the "Go" buttons under each chart to see them in action.
The actual "hack" to allow category animating is the Highcharts.Series.prototype.update = function(changes, callback){ function.
Just playing around trying to get something to work, I found that I could animate the svgY of the Column labels, but svgX just seems to not function at all.
Actual HighCharts.js hacks are welcome.
I took a look into your code and improved it a little bit. I did the following:
Unified code for column/bar using single variable that stores the attribute we're going to update
Removed jQuerySVG dependency, instead my code uses built-in Highcharts animate method
Fixed some minor bugs
I tested this with IE7+/Chrome/Firefox, it works fine in all of them.
Here you can find my version of Highcharts.Series.prototype.update:
Highcharts.Series.prototype.update = function (changes, callback) {
var series = this,
chart = this.chart,
options = chart.options,
axis = chart.xAxis[0],
ticks = axis.ticks,
type = chart.options.chart.type,
animDuration = 400,
attr = type === 'bar' ? 'y' : 'x',
animOpt = {},
text;
if (options.chart.animation && options.chart.animation.duration) {
animDuration = options.chart.animation.duration;
}
if (type == "bar" || type == "column") {
if (typeof chart.labelPositions === "undefined") {
chart.labelPositions = [];
$.each(ticks, function () {
chart.labelPositions.push(this.label[attr]);
});
}
for (var category in changes) {
for (var i = 0; i < series.points.length; i++) {
if (typeof series.points[i].originalCategory === "undefined") {
series.points[i].originalCategory = series.points[i].category;
}
if (series.points[i].originalCategory == category) {
$.each(ticks, function () {
text = this.label.text || this.label.element.innerHTML; // use innerHTML for oldIE
if (text == category) {
var myX = (typeof changes[category].x !== "undefined") ? changes[category].x : series.points[i].x;
series.points[i].update(changes[category], false, {
duration: animDuration
});
animOpt[attr] = parseInt(chart.labelPositions[myX]);
// This is the line that animates the bar chart labels.
this.label.animate(animOpt, {
'duration': animDuration,
'queue': false
});
return false;
}
});
}
}
}
chart.redraw();
if (typeof callback !== "undefined") {
setTimeout(function () { callback(); }, animDuration);
}
}
}
Check out the demo: http://jsfiddle.net/evq5s/17

In xmlhttp.onreadystatechange function, how do I pass the name of the ID I want to edit?

Here's my code. See the line that is commented out. When the element id (which is a span) is hardcoded, it works. When the id is created by concatenating the variables passed into stateChanged, it does not work. Am I not allowed to pass variables in to stateChanged? What's wrong?
function multiplePassportPoints(id, counter)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="addmorepoints.php";
url=url+"?id="+id+"&c="+counter;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged(id,counter);
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged(id, counter)
{
if (xmlhttp.readyState==4)
{
//THIS WORKS (assuming id is 99 and counter is 5:
//document.getElementById("99_5").innerHTML += xmlhttp.responseText;
//BUT I NEED IT TO WORK LIKE THIS:
document.getElementById(studentID+"_"+counter).innerHTML += xmlhttp.responseText;
}
}
Thanks!
You can change the code to this
xmlhttp.onreadystatechange = function () {
stateChanged(id,counter);
};
<script type="text/javascript">
var i=1;
function validate(str)
{
xmlHttp=GetXmlHttpObject()
var url="checkvalidate.php"
url=url+"?User9="+str
xmlHttp.onreadystatechange=stateChanged19
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged19()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("valid"+i)
.innerHTML=xmlHttp.responseText
i=i+1;
} }
</script>
A better method which can be called multiple times before the previous call finishes. Notice that if you call multiplePassportPoints twice your previous value of xmlhttp will get overwritten. There are two outcomes:
1- everything works fine when no concurrency occurs (very high possibility),
2- first call never happens (very low possibility but it will happen from time to time and will be very hard to spot and reproduce)
But the following code uses local variable and might (not tested) be safe to call again and again.
function multiplePassportPoints(id, counter) {
var xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="addmorepoints.php";
url=url+"?id="+id+"&c="+counter;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
stateChanged(id, data, xmlhttp.responseText);
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged(id, counter,text)
{
document.getElementById(id+"_"+counter).innerHTML += text;
}