screeps: conditions won't work - clueless - javascript

So i have been trying this to automatically spawn Creeps in percentage to total living creeps.
however when i run this, it just keeps on spawning harvesters, completely ignoring the conditions even though console.log returns the expected results .
and now i'm clueless about what is going wrong
//creepManager.creations() == counts total creeps and spawns creeps in function of total
var spawnCreep = require('spawnCreep');
var counter = require('counter');
exports.creations=function(){
if( counter.guardCount()/counter.totalCount()<0.5 && counter.harvesterCount()>1){
spawnCreep.guard();
} else if (counter.harvesterCount()/counter.totalCount()<0.3){
spawnCreep.harvester();
} else if(counter.builderCount()/counter.totalCount()<0.2){
spawnCreep.builder();
} else {
spawnCreep.guard(); //default
}
}; // 5guards, 3harvesters, 2 builder per 10CREEPS`
(spawnCreep is another module which keeps track of how the creepers are build)

I was doing something similar in my old code:
function allocateResources() {
var counts = {guard : 0, healer : 0}
for (var name in Game.creeps) {
if (name.indexOf("guard") > -1) {
counts["guard"]++;
} else if (name.indexOf("builder") > -1) {
counts["builder"]++;
}
// ...
counts["total"]++;
}
if (counts["guard"] / (counts["total"] + 1) < 0.51) {
spawnCreep("guard");
} else if (counts["builder"] / (counts["total"] + 1) < 0.34) {
spawnCreep("builder");
}
// ...
}
You should make sure that you avoid division by zero, perhaps that's the bug for you.

Related

Having a hard time getting the right probability outcome (js beginner)

I'm trying to make a simple rolling the dice mechanic with probabilities, if pass the level increase, if fail it decrease and if destroyed usually it resets to a certain level, but I'm having a hard time getting the right results, I am not sure if the outcome is supposed to be like this and just my intuition is wrong or something is actually messing it up.
Basically I am making a while loop that while below certain level it will roll the dice and given the results it will do something accordingly to the rates I input (40% for pass, 59.4% for fail and 0.6% to destroy). But when I do a test with 1000 tries, it always return me an average of destroyed way higher than 0.6%. I don't know if my test function is wrong, if the way I'm testing is wrong, if something on my loop is messing up the probabilities outcome.
function checkPass(successRate, failRate, destroyRate) {
let number = Math.random();
if (number < successRate) {
return 1;
} else if (number < failRate) {
return 0;
} else {
return 2;
}
}
function starforceSim(itemLevel) {
let newObj = {"level": 10, "totalMeso": 0, "destroyed": 0};
while (newObj.level < 11) {
if (newObj.level == 10) {
let passOutcome = checkPass(0.4, 0.994, 1)
if (passOutcome == 1) {
//newObj.totalMeso = newObj.totalMeso + (Math.round(1000 + (Math.pow(itemLevel, 3)) * (Math.pow(newObj.starlevel + 1, 2.7)) / 400));
newObj.level = newObj.level + 1;
} else if (passOutcome == 0) {
//newObj.totalMeso = newObj.totalMeso + (Math.round(1000 + (Math.pow(itemLevel, 3)) * (Math.pow(newObj.starlevel + 1, 2.7)) / 400));
//newObj.level = newObj.level - 1;
} else {
//newObj.totalMeso = newObj.totalMeso + (Math.round(1000 + (Math.pow(itemLevel, 3)) * (Math.pow(newObj.starlevel + 1, 2.7)) / 400));
newObj.destroyed = newObj.destroyed + 1
}
}
}
return newObj;
}
let counter = 0;
for (i=0; i<1000; i++) {
let n = starforceSim(140);
if (n.destroyed > 0) {
counter++
}
}
console.log(counter);
I disabled the decrease level when it fails just to focus on the destroy rates.
Is there a better way to code probabilities or to test them? Is there something wrong with my code?
Math.random is only pseudo-random1
1Source
This means you may not get a perfectly uniform distribution. In my own fiddling, it seems like randomness might get worse if you generate many values in rapid succession [citation needed].
If you want a better source of randomness, check out Crypto.getRandomValues.
I don't see anything wrong with your code. I think your expectations are just off. To verify that this is caused by lame randomness, take David Tansey's advice and study just the randomness output.
You may also notice different randomness quality in different browsers (or, different Javascript engines).

Simple number guessing game using Javascript

I'm trying to make a number guessing game on JS for a web dev training I'm on. The problem is that it always prints the keyInYNStrict without giving an another chance for the user. Ignore the fact that the strings and variables are not in English. Basically I want the keyInYNStrict to only come after the arvaus == arvattava is true and the game has ended.
const minLuku = 1;
const maxLuku = 30;
const readlineSync = require('readline-sync');
let arvaus, arvattava, arvaustenLkm
do {
arvaus = readlineSync.question('Ajattelen numeroa 1 ja 30 välillä. Arvaapa vaan');
arvaustenLkm = 1;
arvattava = Math.floor(Math.random() * (maxLuku + 1 - minLuku)) + minLuku
kelvollinen = !isNaN(arvaus) && arvaus > 0 && arvaus < 31;
if (!kelvollinen) {
console.log('Elä viitsi! Laita nyt jokin oikea numero.');
}
else if (arvaus < arvattava){
arvaustenLkm++;
console.log('Kokeile suurempaa lukua.');
} else if (arvaus > arvattava){
arvaustenLkm++;
console.log('Kokeile pienempää lukua.');
} else if (arvaus == arvattava){
console.log('Hienoa. arvasit oikein ' + arvaustenLkm + ' arvauksella.')
}
} while (readlineSync.keyInYNStrict('Haluatko arvata uudestaan?'))
You'll need two while loops nested. The first is to repeat the guessing until the number has been found, the second to ask if the user wished to play again. This becomes clearer if you break a single game into a function, and then wrap "Play again?" around that function.
The following is untested. Notice I also pulled out the "Invalid guess" check to separate it from the game logic. I think that also improves readability, and allows for the option of checking for some other exit condition should the user wish to end early.
EDIT: As I'm thinking about it, there's another problem: Do you want to reset the hidden number each guess? That's probably not consistent with expectations. I've modified the code to reflect.
const minLuku = 1; // Lower bound
const maxLuku = 30; // Upper bound
const readlineSync = require('readline-sync');
let arvaus, arvattava, arvaustenLkm
do {
// Number of guesses
arvaustenLkm = 1;
//Target number
arvattava = Math.floor(Math.random() * (maxLuku + 1 - minLuku)) + minLuku
do {
// User's guess
arvaus = readlineSync.question('Ajattelen numeroa 1 ja 30 välillä. Arvaapa vaan');
// Bad guess test
if (isNaN(arvaus) || arvaus < minLuku || arvaus > maxLuku) {
console.log('Elä viitsi! Laita nyt jokin oikea numero.');
continue;
}
if (arvaus < arvattava){
arvaustenLkm++;
console.log('Kokeile suurempaa lukua.');
} else if (arvaus > arvattava){
arvaustenLkm++;
console.log('Kokeile pienempää lukua.');
} else if (arvaus == arvattava){
console.log('Hienoa. arvasit oikein ' + arvaustenLkm + ' arvauksella.')
}
} while (arvaus != arvattava)
} while (readlineSync.keyInYNStrict('Play again?'))

See if a number is within range of 10 or 30 in hot or cold game

I'm working on a game where you have to guess a number, and if it matches the number that is randomly generated then you win. I've got most of the game completed apart from the part where you have to check if the guessed number is within the range of 30 or 10 of the randomly generated number. To give an example, if the random number is 50 and the guessed number is 60 then this is within a range of 10 of the random number and this should therefore cause the screen to turn to the colour red, because they are 'hot' but iv'e been having trouble working out the calculation for it. Any ideas?
This is the code I'm using to calculate if the number is correct or not.
function guessFunction() {
counter++;
document.getElementById("guessNumber").innerHTML = counter;
if (!checkEqual(document.getElementById("randomNumber"), random)) {
document.body.style.background = "orange";
} else {
document.body.style.background = "green";
document.getElementById("another").style.visibility = "hidden";
}
if (!checkHigher(document.getElementById("randomNumber"), random)) {
return true;
} else {
return false;
}
if (!checkGreater(document.getElementById("randomNumber"),
random)) {
return true;
} else {
return false;
}
}
function checkHigher(element1, element2) {
if (element1.value > element2) {
document.getElementById("highOrLow").innerHTML = "Too High";
} else if (element1.value == element2) {
document.getElementById("highOrLow").innerHTML = "got it";
} else {
document.getElementById("highOrLow").innerHTML = "Too low";
}
}
Basically subtract the two and get the absolute value to find the difference. On another note I see you have multiple functions for testing different cases. You could write one function to handle all cases and only pass the generated number and guess in instead of the elements themselves. Then it is more stand alone. Something like this:
function checkNumber(number, guess) {
// Gets difference by subtracting and finding absolute value
var diff = Math.abs(number - guess);
// Assumes guess is too low and checks if its higher
var highlow = " and too low";
if (guess > number) {
highlow = " and too high";
}
// Checks range for hot and cold while adding in high or lowness, else its exact so ignores adding high or lowness
// Off by more than 20 cold, off by under 20 hot.
if (diff >= 21) {
document.getElementById("highOrLow").innerHTML = "Cold" + highlow;
} else if (diff >= 1 && diff <= 20) {
document.getElementById("highOrLow").innerHTML = "Hot" + highlow;
} else {
document.getElementById("highOrLow").innerHTML = "Got it";
}
}
Fiddle: https://jsfiddle.net/bohxapdw/2/

Why is my Javascript not adding data on submit?

I am building a hot and Cold App in JS and jQuery.
My issue is on form submit that user input inserts a number and the game tells them if its hold or cold or hotter or holder based on how close or far from the number.
Issue is that It only works the first time. After that it does nothing.
How do I made it so that when the user input on submit it generates a new secretNumber and based on the checker I have setup outputs either hot or cold or hotter or colder.
Seems its not generating a new secret number or it is just not inputing it.
Code here http://codepen.io/mackenzieabby/pen/qOXNLg
JS
$(document).ready(function(){
// Global Variables.
var theSecret = Math.floor((Math.random() * 100) + 0); // Creates Secret Number
var userGuess = $('#userGuess').val(); // User Inut Guess
var count = 0;
var addList = document.createElement("li")
// Display information modal box
$(".what").click(function(){
$(".overlay").fadeIn(1000);
});
// Hide information modal box
$("a.close").click(function(){
$(".overlay").fadeOut(1000);
});
// Functions
// New Game
function newGame() {
// new gama data here
}
// Add To List
function addtoList() {
}
function preventRefresh() {
$("form").submit(function(event) {
event.preventDefault();
theSecret();
veryHotGuess();
hotGuess();
veryColdGuess();
coldGuess()
correctAnswer();
});
}
preventRefresh();
function addGuess() {
$("ul#guessList").append("<li>" + userGuess + "</li>");
}
// Checks if hot or cold or correct
function veryHotGuess() {
if (userGuess < 25 && theSecret < 25) {
document.getElementById('feedback').innerHTML = "Very Hot";
}
}
function hotGuess() {
if (userGuess < 50 && theSecret < 50) {
document.getElementById('feedback').innerHTML = "Hot";
}
}
function veryColdGuess() {
if (userGuess < 100 && theSecret < 100) {
document.getElementById('feedback').innerHTML = "Very Cold";
}
}
function coldGuess() {
if (userGuess < 75 && theSecret < 75) {
document.getElementById('feedback').innerHTML = "Cold";
}
}
function correctAnswer() {
if (userGuess == theSecret) {
document.getElementById('feedback').innerHTML = "You Got It";
}
}
});
Calling theSecret(); causes a JavaScript error. You are calling the variable as a function, which it isn’t obviously.
BTW, I think your calculation of guess "temperature" might be quite wrong.
You have to redefine your definition of Global variable in javascript:
$(document).ready(function(){
// Global Variables.
var theSecret = Math.floor((Math.random() * 100) + 0); // Creates Secret Number
var userGuess = $('#userGuess').val(); // User Inut Guess
var count = 0;
var addList = document.createElement("li")
...
those ARE NOT global variables, because you made then in a scope, the document.ready scope... a Global Variable must be defined outside any scope, so it's available in all scopes, including inside the document.ready as well inside any function method you wrote.
Secondly, you need to rethink what you are doing, as a rule, you are repeating yourself over and over with
document.getElementById('feedback').innerHTML = xxxx;
one day you need to change the feedback to something else, or also write something else, can you see in how many places you need to change your code? When you see several lines of almost the same code: You're doing it wrong...
And you need to simplify your calculations, you make it hard to code and see what's going on...
Third, as Alexander pointed out, you need to re-think how you're calculating, what you want to calculate if not the userGuess or the theSecret, but give an answer based on how close/far the user guess is from the correct value ... that I would call it the difference between 2 numbers.
something like: Math.abs(theSecret - userGuess)
Here's my approach:
http://codepen.io/anon/pen/wKqzvg?editors=001
(irrelevant code removed)
var theSecret = 0,
guesses = [];
$(document).ready(function() {
// Creates Secret Number
theSecret = Math.floor((Math.random() * 100) + 0);
$("form").submit(function(evt) {
evt.preventDefault();
checkTemperature();
});
});
// Functions
// Add To List
function addToList(txt) {
guesses.push(txt);
$("#count").text(guesses.length);
$("ul#guessList").append("<li>" + txt + "</li>");
}
function write(txt) {
document.getElementById('feedback').innerHTML = txt;
}
function checkTemperature() {
var userGuess = parseInt($('#userGuess').val()),
dif = Math.abs(theSecret - userGuess);
// for debug only
console.log("theSecret:" + theSecret);
console.log("userGuess:" + userGuess);
console.log("dif:" + dif);
addToList(userGuess);
if (dif < 5)
write("Vulcan Hot");
else if (dif < 25)
write("Very Hot");
else if (dif < 50)
write("Hot");
else if (dif < 75)
write("Cold");
else if (dif < 100)
write("Very Cold");
else if (dif === 0)
write("You Got It");
}
The problem isn't with theSecret but with userGuess. You were not grabbing the value on submit so it was empty. I suggest to always console.log or inspect variables to make sure they are getting populated correctly. In your submit I added this: userGuess = $('#userGuess').val(); and it will now check correctly.
However, as Alexander mentioned the math is wrong. The value will always be under 100 and so it will always be Very Cold. You have to get the absolute difference of both numbers and then do your guess check:
var difference = Math.abs(theSecret - userGuess);
if (difference < 100) {
document.getElementById('feedback').innerHTML = "Very Cold";
}
if (difference < 75) {
document.getElementById('feedback').innerHTML = "Cold";
}
if (difference < 50) {
document.getElementById('feedback').innerHTML = "Hot";
}
if (difference < 25) {
document.getElementById('feedback').innerHTML = "Very Hot";
}
if (difference == 0) {
document.getElementById('feedback').innerHTML = "You Got It";
}
I forked your project here: http://codepen.io/paulmg/pen/xwLExM

Javascript random array checker error

Working on a game and cant figure out why my functions aren't working right..
Uncaught RangeError: Maximum call stack size exceeded
By my knowledge one of my functions have a infinite loop(?)
I have a array witch needs to have 3 random speeds in it.
var randomSpeeds = new Array();
I have a function made witch generate a random speed:
function generateSpeed() {
var randomSpeed = Math.random().toFixed(1) * 5;
if(randomSpeed == 0){
randomSpeed = 1;
}
return randomSpeed;
}
The array is filled by this function:
function fillSpeedArray() {
for(var i = 0; i < 3; i++) {
var randomSpeed = generateSpeed();
if(speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(i, 0, randomSpeed);
} else {
fillSpeedArray();
}
}
}
The function loops 3 times and each time it generates a random speed and goos through a if/else statement for checking if the array already has got the random generated number (speedArrayChecker).
The speedArrayChecker:
function speedArrayChecker(speed) {
for(speeds in randomSpeeds) {
if(speeds != speed) {
return true;
}
}
return false;
}
This last function goos through the array and if the array already go the random generated number, return true else false.
Function called and checked:
fillSpeedArray();
console.log(randomSpeeds);
By a reason I don't see the functions aren't working correctly.
Thanks and regards.
Solution:
var randomSpeeds = new Array();
function generateSpeed() {
var randomSpeed = Math.random().toFixed(1) * 5;
if(randomSpeed == 0){
randomSpeed = 1;
}
return randomSpeed;
}
function fillSpeedArray() {
while (randomSpeeds.length < 3) {
var randomSpeed = generateSpeed();
if (speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(randomSpeeds.length, 0, randomSpeed);
}
}
}
function speedArrayChecker(speed) {
return randomSpeeds.indexOf(speed) === -1
}
fillSpeedArray();
console.log(randomSpeeds);
Explanation:
There were two problems with your code.
The implementation of the speedArrayChecker function was fundamentally flawed. It returned false only when the randomSpeeds was empty.
You had an infinite loop caused by infinite recursion.
The solution was to correct the speedArrayChecker implementation and to use a while loop instead of a for loop.
You have an infinite loop(by recursion) here:
function fillSpeedArray() {
for(var i = 0; i < 3; i++) {
var randomSpeed = generateSpeed();
if(speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(i, 0, randomSpeed);
} else {
fillSpeedArray();
}
}
}
In the else if the speed exists already it will call the function it's currently in again and again. This function will never exit, unless you get 3 random speeds perfectly the first time. I would recommend changing fillSpeedArray() to maybe i--.
On a side note why don't you use randomSpeeds.push(randomSpeed) to add speeds to the array.

Categories

Resources