I have a script for a gambling site.
What I need is that after 2 calls to the function multiply, it bets the maximum stake possible and after that calls the function reset, I mean in each two sequential loss it bets the full balance in my account reset for the minimum stake and continue playing, Because I realized that in odds of 1.1 on 'manual bet' in each 2 loss the next will be a won.
It is like: after 2 multiplyCalls bet the full balance (it is the "MAX" button in the image below) and reset the game to continue playing. Am I being clear enough?
I tried to create a function for this but did not work
The "Maximum stake" button element code is:
MAX
this is the printscreen
The part of the script I want to modify is this, the multiplyCalls function is already created. I changed the var multiply = (current * 2).toFixed(8); to var multiply = (current * 1).toFixed(8); because my strategy does not have martingale.
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 2).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
reset();
console.log('=== RESETING ===');
}
}
This is the full script:
var startValue = '0.00000001', // Don't lower the decimal point more than 4x of current balance
stopPercentage = 0.001, // In %. I wouldn't recommend going past 0.08
maxWait = 500, // In milliseconds
stopped = false,
stopBefore = 3; // In minutes
multiplyCalls = 0; // <--- Added this global
var $loButton = $('#double_your_btc_bet_lo_button'),
$hiButton = $('#double_your_btc_bet_hi_button');
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 1).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
reset();
console.log('=== RESETING ===');
}
}
function getRandomWait(){
var wait = Math.floor(Math.random() * maxWait ) + 100;
console.log('Waiting for ' + wait + 'ms before next bet.');
return wait ;
}
function startGame(){
console.log('Game started!');
reset();
$loButton.trigger('click');
}
function stopGame(){
console.log('Game will stop soon! Let me finish.');
stopped = true;
}
function reset(){
$('#double_your_btc_stake').val(startValue);
}
// quick and dirty hack if you have very little bitcoins like 0.0000001
function deexponentize(number){
return number * 1000000;
}
function iHaveEnoughMoni(){
var balance = deexponentize(parseFloat($('#balance').text()));
var current = deexponentize($('#double_your_btc_stake').val());
return ((balance*2)/100) * (current*2) > stopPercentage/100;
}
function stopBeforeRedirect(){
var minutes = parseInt($('title').text());
if( minutes < stopBefore )
{
console.log('Approaching redirect! Stop the game so we don\'t get redirected while loosing.');
stopGame();
return true;
}
return false;
}
// Unbind old shit
$('#double_your_btc_bet_lose').unbind();
$('#double_your_btc_bet_win').unbind();
// Loser
$('#double_your_btc_bet_lose').bind("DOMSubtreeModified",function(event){
if( $(event.currentTarget).is(':contains("lose")') )
{
console.log('You LOST! Multiplying your bet and betting again.');
multiply();
setTimeout(function(){
$loButton.trigger('click');
}, getRandomWait());
//$loButton.trigger('click');
}
});
// Winner
$('#double_your_btc_bet_win').bind("DOMSubtreeModified",function(event){
if( $(event.currentTarget).is(':contains("win")') )
{
if( stopBeforeRedirect() )
{
return;
}
if( iHaveEnoughMoni() )
{
console.log('You WON! But don\'t be greedy. Restarting!');
reset();
if( stopped )
{
stopped = false;
return false;
}
}
else
{
console.log('You WON! Betting again');
}
setTimeout(function(){
$loButton.trigger('click');
}, getRandomWait());
multiplyCalls = 0; // reset value
}
});startGame
So basically, you want to max the bet after two losses. Because multiply calls only occur after a loss, we can assume that the if(multiplyCalls < 2) bit takes care of that. So in the following else, all you really need to do is hit max bet instead of call reset(). Based on what I understand the code to be doing, this should be sufficient, correct?
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 1).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
//reset(); /* instead of resetting here, let's max the bet. */
$('#double_your_btc_max').trigger('click');
console.log('=== RESETING ===');
}
}
Related
I want to get data from a sensor in milliseconds and then calculate the average value within ten seconds to alert based on the average value. The problem is that this code runs well as long as the while loop been set to less than 1000 or one second and when I set it to larger numbers(I want the loop to work infinitely and stop with a button function). I want to know if there any way to function this infinite loop in Javascript?
Here is my code:
const now = Date.now();
var epochTime = now;
//Arrey of the value
var Arrey = [];
Counter =0
while (epochTime<now+10000000) { //should be set infinite and stop with button
$.get('http://xxx/'+epochTime, function(data){
let myValue= data.data[354708094967841].crosscorrelations[0].value;
document.getElementById("demo").innerHTML +="<br/>"+ myValue ;
Arrey.push(myValue);
console.log(Arrey);
var sum =0;
console.log(epochTime);
if (Counter>=10000 && Counter%10000==0){
for ( i=Counter-10000; i<Counter; i++)
sum = sum + Arrey[i];
valueAverage= sum/10000;
console.log(valueAverage);
document.getElementById("valueAverage").innerHTML +="<br/>"+ valueAverage;
if (valueAverage>0.01){
alert("the value ave is high"); // ----> to check the code
}else{
alert("the value ave is low"); //-----> to check the code
}
}
console.log(Counter);
Counter++;
console.log(myValue); //get data from value in async version
});
epochTime ++;
}
As the comments said: $.get() is asynchronous, so it doesn't wait. What you could do, is wrap the get request in a function and call the function from within the request, thus creating a loop. So sort of like this:
var buttonClicked = false;
//Function simply wraps the get request so that it can be called at anytime
function getSensorData(){
$.get('http://xxx/'+epochTime, function(data){
let myValue = data.data[354708094967841].crosscorrelations[0].value;
document.getElementById("demo").innerHTML += "<br/>" + myValue;
Arrey.push(myValue);
console.log(Arrey);
var sum = 0;
console.log(epochTime);
if (Counter >= 10000 && Counter % 10000 == 0) {
for (i = Counter - 10000; i < Counter; i++)
sum = sum + Arrey[i];
valueAverage = sum / 10000;
console.log(valueAverage);
document.getElementById("valueAverage").innerHTML += "<br/>" + valueAverage;
if (valueAverage > 0.01) {
alert("the value ave is high"); // ----> to check the code
} else {
alert("the value ave is low"); //-----> to check the code
}
}
console.log(Counter);
Counter++;
console.log(myValue); //get data from value in async version
//Now that you're done with everything, you can check if the button is clicked and if it is, don't run the function again.
if (!buttonClicked){
getSensorData();
}
}
}
//Here we check if the button is clicked and change the variable when it is
$("#stopButton").click(function(){
buttonClicked = true;
});
Also, quick note: Variables in javascript are usually camelCase, not Capitalized; constants are the exception because they are generally ALLCAPS.
I have a function that when called will decrease by 1. It is called when a user reports something. I want to be able to store this and then when it hits 0, to execute an action.
function userReported() {
console.log('user report ' + add());
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
Now the problem is I can return the counter so it logs down from 10. But the issue I have is that I can seem to add an if/else before returning counter as it does not store the variable.
I attempted the following but it doesn't work and I don't know how to return something > store it, and at the same time check its value. I also tried a while loop but failed too.
function userReported() {
var limit = add;
if ( limit <= 0 ) {
console.log('Link does not work!');
}
else {
console.log('user report ' + limit);
}
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
How do I go about creating a value, increment/decrement said value, then when it reaches a number -> do something?
You would typically do this with a function that returns a function that captures the counter in a closure. This allows the returned function to maintain state over several calls.
For example:
function createUserReport(limit, cb) {
console.log('user report initiated' );
return function () {
if (limit > 0) {
console.log("Report filed, current count: ", limit)
limit--
} else if (limit == 0) {
limit--
cb() // call callback when done
}
// do something below zero?
}
}
// createUserReport takes a limit and a function to call when finished
// and returns a counter function
let report = createUserReport(10, () => console.log("Reached limit, running done callback"))
// each call to report decrements the limit:
for (let i = 0; i <= 10; i++){
report()
}
You can of course hard-code the callback functionality and limit number into the function itself rather than passing in arguments.
Ok, if you need to get a report based on an external limit, you could do something like that:
var limit = 10;
function remove() {
limit -= 1;
}
function userReport() {
if (limit <= 0) {
console.log("Link does not work!");
} else {
remove();
console.log(`User report: ${limit}`);
}
}
userReport();
If that's what you want, removing the remove function from userReport and taking the limit variable out will make things work
<div id="counter">1:00</div>
function countdown() {
var secs = 60;
function tick() {
var counter = document.getElementById("counter");
secs--;
counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs);
if( secs > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game Over");
}
}
tick();
}
countdown(60);
I am having a problem with this portion of my game. I'm trying to set a 60 seconds timer for the game that starts at 60 and ends at 0, when it gets to 0 the game stops and an alert shows that the game is over.
I am very new to programming, so please give me as many feedbacks as you can. I found this code on the internet, and I figured out most of it, could you also tell me what does the tick() function do over here?
Here is one way you can do it:
First declare a variable you will use for an interval (should be 'global', attached to window):
var countDownInterval = null;
Then, a function to trigger the tick interval, you should call this whenever the game is ready to start:
function startCountDown()
{
countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
}
which will call the tick function every second:
function tick()
{
// Check to see if the counter has been initialized
if ( typeof countDownInterval.counter == 'undefined' )
{
// It has not... perform the initialization
countDownInterval.counter = 0; //or 60 and countdown to 0
}
else
{
countDownInterval.counter++; //or --
}
console.log(countDownInterval.counter); //You can always check out your count # the log console.
//Update your html/css/images/anything you need to do, e.g. show the count.
if(60<= countDownInterval.counter) //if limit has been reached
{
stopGame(); //function which will clear the interval and do whatever else you need to do.
}
}
and then the function where you can do everything you need to do after game has finished:
function stopGame()
{
clearInterval(countDownInterval);//Stops the interval
//Then do anything else you want to do, call game over functions, etc.
}
You can fire up the counter at any time by calling startCountDown();
Pseudo code of tick:
function tick() {
reduce counter variable;
if counter > 0
wait for 1 second; (This is what setTimeout(tick, 1000) means)
call tick() again (recursively)
}
else {
game over
}
}
Something like this?
var countdown = function(sec, tick, done) {
var interval = setInterval(function(){
if(sec <= 0) {
clearInterval(interval);
done();
} else {
tick(sec)
sec--;
}
}, 1000)
}
countdown(10, console.log, function(){console.log('done')})
This question already has an answer here:
How to disable a button with a timed loop?
(1 answer)
Closed 9 years ago.
Attack = attack button.
When I run this code (click on the button), it takes about 1 second to disable the button. How can I set this up to disable instantly? I'm assuming it's because of the 1000 ms timer, but i'm not sure.
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 0;
function disabledTimer() {
if (start > 5){
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
blitz.disabled = true;
start++;
};
}
yes, it's because of the 1000ms timer. if you set it to 10 it will take 10 ms to disable. if you need it to start disabled, move (or copy) the blitz.disabled = true code out of the interval callback:
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 1; // set to 1 to maintain consistency (i.e. call blitz.disabled = true the same amount of times as the original code.
blitz.disabled = true;
function disabledTimer() {
if (start > 5) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
blitz.disabled = true;
start++;
}
}
if you need to do more complex stuff and this code is just an example, you can wrap your complex statements inside a function and call it from outside and inside the interval:
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 1; // set to 1 to maintain consistency (i.e. call blitz.disabled = true the same amount of times as the original code.
function disableBlitz() {
blitz.disabled = true;
}
disableBlitz();
function disabledTimer() {
if (start > 5) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
disableBlitz();
start++;
}
}
set the timer to 0
var disabledStartTimer = setInterval(disabledTimer, 0);
or simply call
disabledTimer();
Set this:
var disabledStartTimer = setInterval(disabledTimer, 1000); // 1 sec
To this:
var disabledStartTimer = setInterval(disabledTimer, 0); // 0 sec
As the time is counted here in Milliseconds. You can be sure of this, it really is because of the setInterval.
I am trying to make a simple game in HTML5 Canvas. I want, at most, two keyboard input per second.
This is my code so far:
function move( x, y, r ) {
var canid=document.getElementById("draw");
canid.addEventListener('keydown',readkey,false);
function readkey(e) {
if(e.keyCode == 37) {
clearField();
x = x-draw.width / 10;
redrawpic(x,y,r);
}
else if(e.keyCode == 38){
clearField();
y = y-draw.height / 10;
redrawpic( x, y, r );
}
//..........etc
}
}
The function move is used to move picture from one cell to another. How to set delay a between two moves?
You can use a timestamp to check when the last event has occured:
function move(x,y,r){
/* your variable declarations*/
var d1 = Date.now();
var d2;
function readkey(e){
d2 = Date.now();
// difference between timestamps needs to be 500ms
if(d2-d1 > 500){
// set old Timestamp to new one
d1 = d2;
/*
Rest of your code
*/
}
This allows one key event every 500ms. Not exactly the same like 2 events in 1 second (which could occure in 50ms and then pause 950ms), but maybe close enough?
Timeout/Interval is possible too, but I personally dislike the overhead of consecutive (possibly unnecessary) timeout calls.
var throttle = false;
function readkey(e) {
if (throttle)
return;
throttle = true;
setTimeout(function () { throttle = false; }, 500);
/* the rest of your code */
500ms is two inputs per second, but they are throttled individually. You could also keep a count of how many inputs there have been in a full second. Something like
if (throttle > 1)
return;
throttle++;
setTimeout(function () { throttle = 0; }, 1000);