JS math causing total sum to be negative - javascript

I am trying to develop a game.
However my math is a problem. Every time the total profit value goes into negative value.
How can i fix it?
var gameProfit = 10000;
var tinyOwned = 0;
var tinyCost = 10000;
var tinyIncome = 0;
function buyTiny(){
if (gameProfit >= tinyCost){
tinyOwned += 1;
document.getElementById('tiny-owned').innerHTML = tinyOwned;
document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit -= tinyCost * tinyOwned);
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + (tinyCost * tinyOwned + 10000);
document.getElementById('tiny-income').innerHTML = "Income : $ " + (tinyIncome = 15000 * tinyOwned);
}
}
var timer = 0;
var timeInterval = 10;
window.setInterval(function gameTimer() {
if (timer >= 0) {
timer++;
document.getElementById('timer-value').style.width = timer + "px";
}
if (timer >= 600) {
timer = 0 + 1;
document.getElementById('timer-value').style.width = "0px";
tinyIncome = 15000 * tinyOwned;
gameProfit += tinyIncome;
document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit);
}
}, timeInterval);
Can anyone see the problem in my code? gameProfit Variable goes into negative how to fix this?

You allow someone to buy when: gameProfit >= tinyCost
But you reduce gameProfit like: gameProfit -= tinyCost * tinyOwned
So you take more then you initially check! to fix:
if (gameProfit >= tinyCost * tinyOwned){
The math looks really messy especially since it is mixed up with setting InnerHtml. I strongly advice to first do the math and then update the Html.InnerHTML
Offtopic: make sure you escape your data if you are ever going to make it to a multiplayer game, else people can crosside script it (Can I escape html special chars in javascript?) but this is something you don't really have to worry about at this stage.

Related

Javascript - few intervals in right order

In my code I have three intervals which should be executed random times one after the another.
var times = Math.floor((Math.random() * 3) + 2);
var turn = 0;
var schemaInterval1 = setInterval(function(){
console.log('first');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval1);
}
},1000);
var schemaInterval2 = setInterval(function(){
console.log('second');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval2);
}
},1000);
var schemaInterval3 = setInterval(function(){
console.log('third');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval3);
}
},1000);
After each execution of the code within interval, I add 1 to the turn value. When turn and times values are equal I reset both of them. Leave currently working interval and skip to another one. But unfortunately they don't work in correct order and in my console I get that message:
first
second
third
first
second
first
(4)second
How can I rewrite my code to put those intervals in proper order and don't allow others work until first finish it's task?
You start your intervals all at the same time. If you want to run them in series, you have to start one when you clear the previous one.
This code should do what you are looking for:
var times = Math.floor((Math.random() * 3) + 2);
var turn = 0;
var intervalNumber = 1;
var intervalTime = 1000;
var numberOfIntervals = 3;
function instantiateInterval() {
if (intervalNumber <= numberOfIntervals) {
console.log('Timer number: ' + intervalNumber);
var interval = setInterval(function() {
turn++;
if(turn === times) {
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(interval);
instantiateInterval();
}
}, intervalTime);
intervalNumber++;
}
}
instantiateInterval();

Trying to get timer to start once arrived on the page

I made the following fiddle of what I have right now..
https://jsfiddle.net/r5yj99bs/1/
I'm trying to start right when I get onto a page, but allowing the option to leave the pause/resume option. Then is there anyway to display the remaining time as '5 minutes' instead of '300 seconds' and then count down that way rather than only seconds.
<button class="start-pause">Start</button>
<h2 class="time-left"></h2>
var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');
// timer length in seconds
var timer_length = 300;
$('body').on('click', '.start-pause', function() {
// are we starting or stopping?
var starting = times.length % 2 == 0;
times.push(Date.now());
if (starting) {
$button.html('Pause');
counter_interval = setInterval(function() {
var time_left = Math.floor(timer_length - sum_elapsed());
if (time_left < 1) {
clearInterval(counter_interval);
return finished();
}
$time_left.html(time_left);
}, 100);
} else {
$button.html('Resume');
clearInterval(counter_interval);
}
});
var sum_elapsed = function() {
sum = 0;
for (var i=0; i<times.length; i++) {
if (i % 2 == 1) {
sum += (times[i] - times[i-1]);
}
if (i == (times.length - 1)) {
sum += (Date.now() - times[i]);
}
}
// convert milliseconds to seconds
return sum / 1000;
};
var finished = function() {
$button.attr('disabled','disabled').html('Finished');
$time_left.html("Time's Up");
};
There is a good time module called moment. You can get it through npm or from moments.com
That can format relative time to human readable strings.
If you want to do it yourself, take the seconds modulus 60 to get the minutes. Using modulus you can extract all info about hours and so on.
You may change the following line:
$time_left.html(time_left);
to:
$time_left.html(secToMinTxt(time_left));
and add the following functions:
function pad(num) {
var str = "" + num;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
function secToMinTxt(seconds) {
var min = Math.floor(seconds / 60);
var sec = seconds % 60;
return pad(min) + ":" + pad(sec);
}
JSFiddle reference : https://jsfiddle.net/r5yj99bs/2/
If interpret Question correctly, try using Math.round with argument existing time_left variable divided by 60
var time_left = Math.round(Math.floor(timer_length - sum_elapsed()) / 60);
jsfiddle https://jsfiddle.net/r5yj99bs/3/

Creating a slider between two numbers

So I've been working on re-producing the slider found here https://www.skylight.io/ ( Scroll down to find the price slider ).
So far Ive managed to create something similiar, but some numbers are hard coded, making it difficult to change and not very re-usable.
I've been researching around and I think I need to use Math.log() and Math.exp() together to achieve something like in the link above but I'm not sure.
Heres a jsfiddle of what I have so far https://jsfiddle.net/7wrvpb34/.
I feel that its the maths part of this problem that is halting me I think, so any help would be greatly appreciated.
Javascript code below:
var slider = document.getElementById("slider")
var sliderFill = document.getElementById("slider-fill")
var knob = document.getElementById("knob")
var mouseDown;
var mousePos = {x:0};
var knobPosition;
var minPrice = 20;
var price = 0;
var minRequests = 50;
var requests = 50 + ",000";
var incrementSpeed = 2;
var incrementModifier = 20;
var incrementValue = 1;
var minMillionCount = 1;
var millionCount = 1;
var previousRequestAmount = 0;
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
highlightTable(1);
document.addEventListener('mousemove', function(e) {
if(mouseDown) {
updateSlider(e);
}
})
function updateSlider(event) {
mousePos.x = event.clientX - slider.getBoundingClientRect().left;
mousePos.x -= knob.offsetWidth / 2;
console.log(mousePos.x);
if(mousePos.x < 0) {
knob.style.left = "0px";
sliderFill.style.width = "0px";
price = 0;
requests = 50 + ",000";
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
return
}
if(mousePos.x > slider.offsetWidth - 20) {
return
}
sliderFill.style.width = mousePos.x + 10 + "px";
knob.style.left = mousePos.x + "px";
//Increase requests by using X position of mouse
incrementSpeed = mousePos.x / incrementModifier;
requests = minRequests + (mousePos.x * incrementSpeed);
//Round to nearest 1
requests = Math.round(requests / incrementValue) * incrementValue;
if (requests >= 1000){
var m = requests/ 1000;
m = Math.round(m / 1) * 1;
//Problem, lower the modifier depending on requests
incrementModifier = 20 * 0.95;
document.getElementById("requests").innerHTML = m + " million";
//Adjust Prices
if(( requests >= 1000) && (requests < 10000)) {
var numOfMillions = requests / 100;
//Round to closest 10.
//10 * number of millions
var rounded = Math.round(numOfMillions / 10) * 10;
price = minPrice + rounded;
highlightTable(3);
}
//Adjust Prices
if(requests >= 10000) {
var numOfMillions = requests / 1000;
var rounded = Math.round(numOfMillions / 1) * 1;
var basePrice = minPrice * 6;
price = basePrice + rounded;
highlightTable(4);
}
} else {
incrementModifier = 20;
document.getElementById("requests").innerHTML = requests + ",000"
if(requests < 100) {
highlightTable(1);
price = 0;
} else {
highlightTable(2);
price = 20;
}
}
previousRequestAmount = requests;
document.getElementById("price").innerHTML = price;
}
knob.addEventListener('mousedown', function() {
mouseDown = true;
});
document.addEventListener('mouseup', function() {
mouseDown = false;
});
function highlightTable(rowNum) {
var table = document.getElementById("payment-table")
for(var i = 0; i < table.rows.length; ++i) {
var row = table.rows[i]
if(i == rowNum) {
row.style.background = "grey"
} else {
row.style.background = "white";
}
}
}
Thank you for your time.
If you want it to be reusable you need to create a mathematical function that assigns a result to the number of requests. I will give you a very easy example.
If you want a different result for 1,10,100,100,10000 etc
var d = Math.log10(requests);
if(d<1){
doSomething();
}else if(d<2){
doSomethingElse();
} //etc
This way if you want to change the specific values that create certain results, all you need to do is change the function.
This only works if your tiers of requests follow a math function, if they don't you need to hard code it.
However if say they don't follow a math function, but you know how you would like them to change based on a value then you can do this.
var changingValue = 4;
if(requests < 400*changingValue){
doSomthing();
}else if(requests <= 400*changingValue*changingValue){
doSomethingElse();
}else{// the requests is greater than any of the above
doTheOtherThing();
}
Edit:
For the second one you need to make sure that each condition if always larger than the other from top to bottom.
The description "increasingly increasing" matches an arbitrary number of functions. I assume you also want it to be continuous, since you already have a non-continuous solution.
TL;DR
Use an exponential function.
Generic approach
Assuming imin and imax are the minimal and maximal values of the slider (i for input) and omin and omax are the minimal and maximal values to be displayed, the simplest thing I can think of would be a multiplication by something based on the input value:
f(x)
{
return omin + (omax - omin) * g((x - imin) / (imax - imin));
}
This will pass 0 to g if x == imin and 1 if x == imax.
The return value r of g(y) should be
r == 0 for y == 0
r == 1 for y == 1
0 < r < y for 0 < y < 1
The simplest function that I can think of that fulfills this is an exponential function with exponent > 1.
An exponent of 1 would be a linear function.
An exponent of 2 would be make the middle of the slider display one fourth of the maximum price instead of half of it.
But you really need to find that exponent yourself, based on your needs.

Increment from zero to number in a set time

I am trying to increment from 0 to a number (can be any number from 2000 to 12345600000) within a certain duration (1000 ms, 5000 ms, etc). I have created the following:
http://jsfiddle.net/fmpeyton/c9u2sky8/
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = duration/counterTotal;
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var currentCounterNumber = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
if (currentCounterNumber < counterTotal){
currentCounterNumber += Math.ceil(counterTotal/duration);
// convert number back to comma format
// currentCounterNumber = addCommas(currentCounterNumber);
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
function addCommas(number){
for (var i = number.length - 3; i > 0; i -= 3)
number = number.slice(0, i) + ',' + number.slice(i);
return number;
}
And this somewhat works, but it does not respect the duration. I.e. if you increase the number from 1000 to 1000000000, they both take different amounts of time to reach the destination number.
How can I increment from zero to a number in a specific time frame?
As #Mouser pointed out, the issue is that the animationInterval can't be too small (the actual minimum threshold will vary based on the browser and platform). Instead of varying the interval, vary the increment to the counter:
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = 10;
var startTime = Date.now();
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var elapsed = Date.now() - startTime;
var currentCounterNumber = Math.ceil(elapsed / duration * counterTotal);
if (currentCounterNumber < counterTotal){
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
I played around with your fiddle and found that the delay needs to be higher. At 8ms or 16ms, it is accurate enough to handle a second, but not accurate enough to handle half a second. From experimenting, it seems like a delay of 64ms is small enough to seem like it's incrementing smoothly, but big enough to have an accurate effect.
The difference is that the current number is calculated based on the process rather than directly manipulated.
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.data('total'));
var interval = 0;
var duration = parseInt(counterElement.data('duration'));;
var delay = 64
var numberIncrementer = setInterval(function(){
var currentCounterNumber = 0;
interval += delay;
if (interval <= duration){
var progress = interval / duration;
currentCounterNumber = Math.round(progress * counterTotal);
} else {
currentCounterNumber = counterTotal
clearInterval(numberIncrementer);
}
counterElement.text(currentCounterNumber);
}, delay);
http://jsfiddle.net/c9u2sky8/5/
Also: Javascript timers are not perfectly accurate. But this should be accurate enough for UI use cases.

Javascript - Distance (in pixels) - Decision

I have a simple javascript animation, where two cowboys (iamges) 'race' each other based on a random interval number.
What I can't find out how to do is for the script to take a decision on who is the winner, meaning if a cowboy reaches a pre-defined distance first, the script will know and will show an alert on who won.
Here is a screen shot to show an example:
This is the code I have so far: http://pastebin.com/Cmt4N8c9
Can give me some directions?
Thanks,
Brian
In your move() function you should do something like
if (x >= dest_x) {
alert('player 1 won');
} else if (x2 >= dest_x2) {
alert('player 2 won');
} else {
... continue the loop ...
}
You'd most likely put that behind
document.getElementById("cowboy").style.top = y+'px';
document.getElementById("cowboy").style.left = x+'px';
document.getElementById("cowboytwo").style.top = y2+'px';
document.getElementById("cowboytwo").style.left = x2+'px';
You might want to check your code on duplicate variables too, by the way.
AFAIK dest_x and dest_x2 are both the same for example.
Simple move
/* Y is not relevant since you only move it on X axis */
var position1 = 100;
var position2 = 100;
var dest = 800; //Or any given value
function move() {
var step1 = Math.floor(1 + (10 * Math.random() ) );
var step2 = Math.floor(1 + (10 * Math.random() ) );
position1 += step1;
position2 += step2;
document.getElementById("cowboy").style.left = position1+'px';
document.getElementById("cowboytwo").style.left = position2+'px';
if(position1 < dest && position2 < dest) {
window.setTimeout('move()',100);
} else {
//We have the winner
if(position1 > dest) alert("Winner is Cowboy1");
if(position2 > dest) alert("Winner is Cowboy2");
//Its also possible that both of them pass target value at the same step
}
}

Categories

Resources