change interval dynamically for clicker game - setinterval

So I already have read other questions about this, but I still do not get it.
I am currently learning JS and I am coding a simple clicker game as a project to show to possible employers.
this is my gameData object:
let gameData = {
coins: 0,
coinsPerClick: 1,
upgradeClickCost: 10,
coinsPerSecond: 0,
upgradeSecondCost: 50,
intervalTime: 1000,
intervalReduceCost: 20
};
this should be my interval reduce upgrade to generate a coin every x ms instead of the current 1000 ms
interval_upgrade.addEventListener("click", e => {
gameData.coins = gameData.coins - gameData.intervalReduceCost;
gameData.intervalTime -= 50;
gameData.intervalReduceCost *= 1.5;
interval_time.innerHTML = `Interval time : ${Math.round(gameData.intervalTime)} ms`;
interval_upgrade.innerHTML = `Reduce interval time / Cost = ${Math.round(gameData.intervalReduceCost)}`;
upgrade_control();
upgrade_control_second();
upgrade_control_interval();
i get that i need to stop the former interval and run the new one with the new value for the interval timing. i just do not know how.

Related

What is the best way to profile SSD for writes using code?

The question comes cause i am writing a application which is very write intensive(using lsm data) and i should be able to say how many transactions i can get on given speced system.
The problem is world of IOPS and throughout is confusing plus OS of different make have different cache at different levels and so on...
Which made me to write my own application(node.js) and do a part of write intensive workload, time it and derive some conclusion around it but the results are confusing..
My app appends to say one file with chuncks of 145MB 3 times in 5 sec.. but if i spread my appends across 100 files thus dividing the payload by 100 ie 145MB/100 i am able to do that in 4 times in 5 seconds.. what explains this behavior?
Is there any better and consistent way to mathematical derive a formula to given iops of ssd what iops can it sustain for one file or multiple files?
Workload is append only and no forced fsync..
Some pseudo code(not full code):
let OPS = 0, newOPS = 0;
for (spreadFactor = 1; (spreadFactor <= 1024) || spreadFactor === 1); spreadFactor += spreadFactor) {
const payload = Array.from({ length: (this.sampleCapacity / spreadFactor) }, (_, idx) => [idx.toString().padStart(20, "0"), idx.toString().padStart(20, "0"), idx.toString().padStart(20, "0"), idx.toString().padStart(20, “0”]));
OPS = newOPS;
let actualBytesOnDisk = 0;
const st = new Stopwatch()
let requests = 0;
while (st.elapsed() < 5000) {
requests++;
for (let index = 0; index < spreadFactor; index++) {
this.handle = fs.openSync(`${spreadFactor}-${index}`, "as");
fs.appendFileSync(this.handle, payload);
fs.fsyncSync(this.handle);
fs.fdatasyncSync(this.handle);
}
}
const elapsed = st.elapsed();
newOPS = (requests / elapsed) * 1000;
console.info(`Calibrating writes R:${requests} E: ${elapsed} F: ${spreadFactor} RPS:${newOPS.toFixed(3)} S:${payload.length} B:${actualBytesOnDisk}`);
}

How to make simple multi-threading with google app scripts for google sheets

I have a lot of google chart to update and I want to parallelize the processing of the for loop.
I've seen the code on this link : Threading in Google App Script
but it's too complicated for I have to do. I do not need to get parallelize the code and get the data back.
for(i=0;i<nbChart;i++)
{
Vmax=rangeMax[i*6];
Vmin=rangeMinId[i*6];
id=rangeMinId[(i*6)+1];
var delta=(Vmax-Vmin)*0.1;
Logger.log("Vmax="+Vmax+"Vmin="+Vmin+"id="+id+"i="+i);
var chart = sheet.getCharts()[id];
if(chart.getType()!="COLUMN")
{
Vmin-=delta
Vmax=Number(Vmax)+(delta*1.5)//Number() function to avoid Vmax becoming a string for no reason
}
Logger.log("Vmax="+Vmax+"Vmin="+Vmin+"id="+id+"i="+i);
chart = chart.modify()
.setOption('vAxes', {0: {textStyle: {fontSize: 10}, titleTextStyle: {fontSize : 8}, viewWindow: {min: Vmin, max:Vmax}}})//adpative vaxis for AREA and COMBO
.build();
sheet.updateChart(chart);
}
I just need to update my charts quickly because it's currently taking about 15 minutes to update for a single sheet.
At current you're calling sheet.getCharts() every time the loop runs which will drastically increase the exectution time. Putting the function call outside of the loop and then only refer to the chart by its ID inside would reduce the number of function calls in the loop:
var chart = sheet.getCharts();
for(i = 0; i < nbChart; i++) {
Vmax = rangeMax[i * 6];
Vmin = rangeMinId[i * 6];
id = rangeMinId[(i * 6) + 1];
var delta=(Vmax - Vmin) * 0.1;
var currChart = chart[id];
if(currChart.getType() != "COLUMN") {
Vmin -= delta
Vmax = Number(Vmax) + (delta * 1.5) //Number() function to avoid Vmax becoming a string for no reason
}
currChart = currChart.modify()
.setOption('vAxes', {0: {textStyle: {fontSize: 10}, titleTextStyle: {fontSize : 8}, viewWindow: {min: Vmin, max:Vmax}}}) //adpative vaxis for AREA and COMBO
.build();
sheet.updateChart(currChart);
}
As another solution, if the order in which you update the charts is not important, you could write a second script with the same loop structure but with a different looping condition.
If you run two loops in two different scripts, one running for (i = 0; i < nbChart; i = i + 2) and the second running for (i = 1; i < nbChart; i = i + 2), you can then set up two installable triggers to run them both at the same time or on the same action which would also reduce oveall execution time.

Distribute a value value along time interval in array. I am using nodejs.

Sorry if the text is confusing, I don't speak English.
My problem is:
1. I have the number of pages that was printed.
2. The duration of printing (start time and finish)
3. I want to plot a chart by hour whith the number of pages per hour
Example:
900 pages
1:30 hous
I want this Array of hour: [600, 300]
I think this is more a mathematical problem, but I don't had a good idea to do this. The are a lot of data and i need to do a algorithm fast and optimized.
Obs: I am more interested in the logic, not in the programming language.
Ok, not sure that works for everything but I think is a good start.
I have made the assumption that your duration is in minutes or else I believe you can transform it to minutes.
function something(pages,totalDutation){
// pages = 900
// totalDutation = 90
var printsPerMinute = pages / totalDutation //get the prints per minute!
var printsPerHour = Math.floor(printsPerMinute * 60) //calculate the prints made in one hour
var countOfHours = parseInt(totalDutation / 60) //divide the total duration by 60 to get the count of hours
var remainingPrints = (totalDutation % 60) * printsPerMinute //add the extra prints that didn't complete a whole hour.
var result = Array(countOfHours).fill(printsPerHour) //create an array and fill it.
if(remainingPrints) result.push(remainingPrints)
return result
}
Take a look at the NodeJS example below to get an idea of how it can be done.
Might need a bit of fine-tuning, though.
Calculate the number of prints per hour
Make as many iterations as hours taken
Do (total prints - prints per hour) as long as a > b,
otherwise return the remaining total prints
const getPagesPerHour = function (totalPrints, totalTime) {
const printsPerHour = (totalPrints / totalTime) * 60;
return Array.apply(null, { length: Math.ceil(totalPrints/printsPerHour) }).map(function (val, key) {
if (totalPrints > printsPerHour) {
totalPrints = (totalPrints - printsPerHour);
return printsPerHour;
} else {
return totalPrints;
}
});
}
console.log(getPagesPerHour(900, 90)); // [600, 300]

Limit drag in gamemaker

Hello I am trying to limit how much a user can drag within Gamemaker.
I have created two views within a room.
The first view is the full room width and size 1250x768
The second view is the area which i would like the user to be able to zoom into and drag which is 955x465. x and y position is 40 by 170.
Currently i have set up the zoom for the second view which is:
vmx=(mouse_x-X)-omx;
omx=(mouse_x-X);
vmy=(mouse_y-Y)-omy;
omy=(mouse_y-Y);
if mouse_wheel_up() && view_wview[1] > 600 {
center_of_space_x=view_xview[1]+view_wview[1]/2;
center_of_space_y=view_yview[1]+view_hview[1]/2;
view_wview[1]-=view_wview[1]*0.15;
view_hview[1]-=view_hview[1]*0.15;
view_xview[1]=center_of_space_x-view_wview[1]/2;
view_yview[1]=center_of_space_y-view_hview[1]/2;
}
if mouse_wheel_down(){
view_xview[1] = 40;
view_yview[1] = 170;
view_wview[1] = 955;
view_hview[1] = 465;}
Below is the code for the drag:
if (mouse_check_button_pressed(mb_left)) {
drag_x = mouse_x
drag_y = mouse_y
}
// update:
if (mouse_check_button(mb_left)) && view_wview[1] < 700 {
// actual dragging logic:
view_xview[1] = drag_x - (mouse_x - view_xview[1])
view_yview[1] = drag_y - (mouse_y - view_yview[1])
// make sure view doesn't go outside the room:
view_xview[1] = max(0, min(view_xview[1], room_width - view_wport[1]))
view_yview[1] = max(0, min(view_yview[1], room_height - view_hview[1]))
So the limit works for the view to not leave the room but i want it not to leave the specific view which has been set up.
Please help
I have modified my code to use a clamp function which works but it is not a clean solution:
view_xview[1] = clamp(view_xview[1],40,400);
view_yview[1] = clamp(view_yview[1],170,500);
The user has to be fully zoomed in to have the view restricted. If he is not then they can still see other areas of the room :(
EDIT: I may have misunderstood your question, I will leave the below code for reference if it helps you solve the problem a bit differently.
I would probably check that mouse_x and mouse_y are not outside the view you want.
if (mouse_x > view_limit_x || mouse_y > view_limit_y)
{
return; // Or continue or break however your language of choice goes.
}
If you cannot do a return statement, wrapping your code in a reverse logic of above should work fine.
Old Post:
I am not 100% familiar with game maker. I would implement something like this by skipping the drag logic every x frames. Say you are updating at 60fps, and you want the drag to be 6 times slower, you just need to only update the logic 10 x per frame.
const int framesToSkip = 6;
int frameCount = 0;
update()
{
// Will only call when framecount = 0, 6, 12, 18 etc.
if (frameCount % framesToSkip == 0)
{
// Drag Logic.
}
frameCount++;
}
This way drag logic only occurs 1/6 the rate as before. You could also change this around to happen the first x amount of frames and then skip for the rest (but this may appear a bit choppy).

Best way to serve / produce silhoutte of the US States?

I'm responsible for delivering pages to display primary results for the US elections State by State. Each page needs a banner with an image of the State, approx 250px by 250px. Now all I need to do is figure out how to serve / generate those images...
I've dug into the docs / examples for Protovis and think I
could probably lift the State coordinate outlines- I would have to
manually transform the coordinate data to be justified and sized
properly (ick)
At the other end of the clever/brute spectrum is an enormous sprite
or series of sprites. Even with png 8 compression the file size of
a grid of 50 non-overlapping 250x250px sprites is a concern, and
sadly such a file doesn't seem to exist so I'd have to create it
from hand. Also unpleasant.
Who's got a better idea?
Answered: the right solution is to switch to d3.
What we hacked in for now:
drawStateInBox = function(box, state, color) {
var w = $("#" + box).width(),
h = $("#" + box).height(),
off_x = 0,
off_y = 0;
borders = us_lowres[state].borders;
//Preserve aspect ratio
delta_lat = pv.max(borders[0], function(b) b.lat) - pv.min(borders[0], function(b) b.lat);
delta_lng = pv.max(borders[0], function(b) b.lng) - pv.min(borders[0], function(b) b.lng);
if (delta_lat / h > delta_lng / w) {
scaled_h = h;
scaled_w = w * delta_lat / delta_lng;
off_x = (w - scaled_w) / 2;
} else {
scaled_h = h * delta_lat / delta_lng;
scaled_w = w;
off_y = (h - scaled_h) / 2;
}
var scale = pv.Geo.scale()
.domain(us_lowres[state].borders[0])
.range({x: off_x, y: off_y},
{x: scaled_w + off_x, y: scaled_h + off_y});
var vis = new pv.Panel(state)
.canvas(box)
.width(w)
.height(h)
.data(borders)
.add(pv.Line)
.data(function(l) l)
.left(scale.x)
.top(scale.y)
.fillStyle(function(d, l, c) {
return(color);
})
.lineWidth(0)
.strokeStyle(color)
.antialias(false);
vis.render();
};
d3 seems to have the capability to do maps similar to what you want. The example shows both counties and states so you would just omit the counties and then provide the election results in the right format.
There is a set of maps on 50states.com, e.g. http://www.50states.com/maps/alabama.htm, which is about 5KB. Roughly, then, that's 250KB for the whole set. Since you mention using these separately, there's your answer.
Or are you doing more with this than just showing the outline?

Resources