I want to make a game project, which will have its own internal currency. I want to make sure that when a local currency loses, it automatically begins to replenish and stop at a fixed limit.

Suppose a player has 50 chips, he lost them, it became 0 - at this moment they should start replenishing and stopping, say, 50. You can 10 every 10 minutes, you can 1 every minute, not fundamental, if anyone understood Please give me a code. You can formal, at least to understand. Thank you in advance)

    1 answer 1

    It is necessary to somehow mark the time when everything is spent to zero and enable the player a temporary mode of "accumulating money over time."

    Further, the amount of currency becomes a function of time:

    start = XXX; // врСмя ΠΊΠΎΠ³Π΄Π° ΡƒΠΏΠ°Π»ΠΎ Π΄ΠΎ 0 mode = "earning"; // ΠΈΠ³Ρ€ΠΎΠΊ находится Π² Ρ€Π΅ΠΆΠΈΠΌΠ΅ накоплСния Π·Π° врСмя now = (new Date).getTime(); // врСмя сСйчас money = Math.floor((now - start) / N) * K; if( money > 50) { mode = "game"; // большС Π½Π΅Ρ‚ Ρ€Π΅ΠΆΠΈΠΌΠ° накоплСния money = 50; } 

    Think over the moment when, during the accumulation of money, the player somehow managed to earn a few coins - what to do then?


    Let me explain the line money = Math.floor((now - start) / N) * K; . This is a school, linear algebra - we need a function that grows from 0 at the start point. In the simplest version, this is y = k * (x - start) , where k a certain coefficient. growth rate. But so will be the fractional values, and you write in the question about discrete - " 10 every 10 minutes, you can 1 every minute ."

    Those. the growth graph is not an inclined line, but steps by integer values. Therefore rounding is added:

    graphics

    How to choose the coefficients N and K Without delving into the explanation, here is the recipe. If you need to once a minute (60 seconds) by 1, divide by N=60 and you can not multiply. If every 10 minutes (600 seconds) by 10, divide by N=600 , and multiply by K=10 .

    • If you go into the game - the replenishment goes, but if the limit (50 coins) is exceeded, then the accumulation stops . Thanks for the code :) - He4ToEnT
    • And can you explain the fourth line?) And more specifically: ((now - start) / N) * K; And if it is even more specific - I don’t understand N and K, I don’t have much in js) - He4ToEnT
    • Explained in response. - Sergiks