js Array index out of bound - javascript

NPC :
var posArrayx = [-1638, -1496, -1386, -1366, -1286, -1252, -1178, -1040, -908, -884, -678, -578, -584, -438, -318, -200, 300, 560, 618, 784, 778, 894, 1142, 1048, 1234, 1348];
var eim, status = -1;
function start() {
eim = cm.getPlayer().getEventInstance();
if (eim != null) {
action(1, 0, 0);
} else {
cm.warp(261000021);
cm.dispose();
}
}
function action(m, t, s) {
if (m < 0) {
cm.dispose();
return;
}
if (m == 1)
status++;
else
status--;
if (status < 0) {
cm.dispose();
return;
}
var randClick = parseInt(eim.getProperty("randClick"));
var mesosArray = eim.getProperty("mesosArray").split(",");
var expArray = eim.getProperty("expArray").split(",");
var clickedSpots = eim.getProperty("clickedSpots").split(",");
for (var i = 0; i < posArrayx.length; i++) {
if (npc.getPosition().getX() == posArrayx[i]) {
if (i == randClick) {
cm.sendOk("Lol its the right one, but it isnt coded yet");
cm.dispose();
} else if (clickedSpots[i] > 0) {
cm.sendOk("Its looks someone already checked this place, i'd better look somewhere else.");
} else if (expArray.indexOf(posArrayx[i]) >= 0) {
cm.sendOk("You gained some mesos");
var meso = Math.floor(Math.random() * 3000) + 1000;
cm.gainMeso(meso);
} else if (mesosArray.indexOf(posArrayx[i]) >= 0) {
cm.sendOk("You gained some mesos");
var exp = Math.floor(Math.random() * 3000) + 1000;
cm.gainExp(exp);
} else {
cm.sendOk("Unable to find anything inside.");
}
clickedSpots[i] = 1;
}
}
eim.setProperty("clickedSpots", clickedSpots.toString());
cm.dispose();
}
Eim :
var pqtime = 45, eventMaps = [926110000], minPlayers = 3, exitMap = 261000021;
var posArrayx = [-1638, -1496, -1386, -1366, -1286, -1252, -1178, -1040, -908, -884, -678, -578, -584, -438, -318, -200, 300, 560, 618, 784, 778, 894, 1142, 1048, 1234, 1348];
function init() {
}
function setup() {
var eim = em.newInstance("Romeo and Juliet");
var randClickSpot = Math.floor((Math.random() * 26) + 0);
eim.setProperty("randClick", randClickSpot);
var mesosArray = new Array();
var expArray = new Array();
var clickedSpots = new Array();
for (var i = 0; i < posArrayx.length; i++) {
clickedSpots.push(0);
var rand = Math.floor(Math.random() * 5);
if (i != randClickSpot) {
if (rand == 4) {
mesosArray.push(posArrayx[i]);
} else if (rand == 3) {
expArray.push(posArrayx[i]);
}
}
}
eim.setProperty("mesosArray", mesosArray.toString());
eim.setProperty("expArray", expArray.toString());
eim.setProperty("clickedSpots", clickedSpots.toString());
eim.startEventTimer(1000 * 60 * pqtime);
return eim;
}
function playerEntry(eim, player) {
var map = eim.getMapInstance(eventMaps[0]);
player.changeMap(map);
}
function playerDead(eim, player) {
}
function playerRevive(eim, player) {
var party = eim.getPlayers();// player presses ok on the death pop up.
if (eim.isLeader(player) || party.size() <= minPlayers) { // Check for party leader
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
} else {
playerExit(eim, player);
}
}
function changedMap(eim, player, mapid) {
var onEvent = false;
for (var i = 0; i < eventMaps.length; i++) {
if (mapid == eventMaps[i]) {
onEvent = true;
}
}
if (!onEvent) {
removePlayer(eim, player);
}
}
function playerDisconnected(eim, player) {
var party = eim.getPlayers();
if (eim.isLeader(player) || party.size() < minPlayers) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
if (party.get(i).equals(player)) {
removePlayer(eim, player);
} else {
playerExit(eim, party.get(i));
}
eim.dispose();
}
} else {
removePlayer(eim, player);
}
}
function leftParty(eim, player) {
var party = eim.getPlayers();
if (party.size() < minPlayers) {
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
} else {
playerExit(eim, player);
}
}
function disbandParty(eim) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
}
function playerExit(eim, player) {
eim.unregisterPlayer(player);
player.changeMap(exitMap);
}
function removePlayer(eim, player) {
eim.unregisterPlayer(player);
player.getMap().removePlayer(player);
player.setMap(exitMap);
}
function clearPQ(eim) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
}
function allMonstersDead(eim) {
}
function monsterDead(eim) {
}
function monsterValue(eim) {
return -1;
}
function cancelSchedule() {
}
function scheduledTimeout(eim) {
if (eim != null) {
if (eim.getPlayerCount() > 0) {
var pIter = eim.getPlayers().iterator();
while (pIter.hasNext()) {
playerExit(eim, pIter.next());
}
}
eim.dispose();
}
}
function dispose(eim) {
}
Error :
Caused by: sun.org.mozilla.javascript.internal.EvaluatorException: Array index 1
5 is out of bounds [0..0]. (<Unknown source>#49)
at sun.org.mozilla.javascript.internal.DefaultErrorReporter.runtimeError
(Unknown Source)
at sun.org.mozilla.javascript.internal.Context.reportRuntimeError(Unknow
n Source)
at sun.org.mozilla.javascript.internal.Context.reportRuntimeError(Unknow
n Source)
at sun.org.mozilla.javascript.internal.Context.reportRuntimeError2(Unkno
wn Source)
at sun.org.mozilla.javascript.internal.NativeJavaArray.put(Unknown Sourc
e)
at sun.org.mozilla.javascript.internal.ScriptableObject.putProperty(Unkn
own Source)
at sun.org.mozilla.javascript.internal.ScriptRuntime.setObjectIndex(Unkn
own Source)
at sun.org.mozilla.javascript.internal.ScriptRuntime.setObjectIndex(Unkn
own Source)
at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Unknown
Source)
at sun.org.mozilla.javascript.internal.Interpreter.interpret(Unknown Sou
rce)
at sun.org.mozilla.javascript.internal.InterpretedFunction.call(Unknown
Source)
at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(Unknown
Source)
at com.sun.script.javascript.RhinoScriptEngine$1.superDoTopCall(Unknown
Source)
at com.sun.script.javascript.RhinoScriptEngine$1.doTopCall(Unknown Sourc
e)
at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(Unknown S
ource)
at sun.org.mozilla.javascript.internal.InterpretedFunction.call(Unknown
Source)
... 27 more
No matter how am i trying to do it. for somereason i can't change the clickedSpots Array.. it does recognize the array but i can't change the data. i cant push into it. and i can't change the data inside it. Line : 49 is , clickedPos[i] = 1. any one have a solution to this problem ? i'm really desperate. i tried couple of things and none of them are working.

Related

I'm trying to make this code in vanilla javascript work in reactjs, but it's falling into the infinite loop

This is the code i got from codepen, it generates special characters and changes to the phrase i put, I'm wanting to compile this vanilla javascript code to react, because you can't use the DOM
there.
My real doubt is where do I put the useState so that it stops looping and shows character by character, this passing for example the state 'title' in a .
vanilla javascript code:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = $('.text__error').data('text').length;
var progressLink = 0;
var totalLink = $('.text__link a').data('text').length;
var scrambleInterval = setInterval(function() {
var string404 = $('.text__error').data('text');
var stringLink = $('.text__link a').data('text');
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
string404 = setCharAt(string404, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
stringLink = setCharAt(stringLink, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
$('.text__error').text(string404);
$('.text__link a').text(stringLink);
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);
This is the code I developed to try to work:
const [ title, setTitle ] = useState('404 page not found')
const [ link, setLink ] = useState('click here to go home')
function setCharAt(str: string,index: number,chr: any) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = title.length
var progressLink = 0;
var totalLink = link.length
var scrambleInterval = setInterval(function() {
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
setTitle( setCharAt(title, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
setLink( setCharAt(link, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);

update priority of queue in javascript

in hasValue class, why return is not working? when i try with console.log and alert, it worked.
want to implement function like priorityQueue.changePriority("Sheru", 1); changePriority class is not working.
commented code is code i tried to implement the changes i.e. i want to change the priority of existing item present in queue. Could anyone please help?
class QElement {
constructor(element, priority) {
this.element = element;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.items = [];
}
isEmpty() {
return this.items.length == 0;
}
add(element, priority) {
var qElement = new QElement(element, priority);
var contain = false;
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].priority > qElement.priority) {
this.items.splice(i, 0, qElement);
contain = true;
break;
}
}
if (!contain) {
this.items.push(qElement);
}
}
peek() {
if (this.isEmpty())
return "No elements in Queue";
return this.items[0];
}
poll() {
if (this.isEmpty())
return "Underflow";
return this.items.shift();
}
/*changePriority(firstTerm, secondTerm)
{
let xxx = new QElement(firstTerm, secondTerm);
for (let i = 0; i < this.items.length; i++){
if (this.items[i].element === firstTerm){
this.items[i].priority = secondTerm;
this.items.splice(i, 0, xxx);
}
}
this.items.push(xxx);
}*/
hasValue(args) {
let status = false;
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].element === args) {
status = true;
}
}
console.log(status);
}
size() {
if (this.isEmpty())
return "Underflow";
return this.items.length;
}
printPQueue() {
var str = "";
for (var i = 0; i < this.items.length; i++)
str += this.items[i].element + " ";
return str;
}
}
var priorityQueue = new PriorityQueue();
console.log(priorityQueue.isEmpty());
console.log(priorityQueue.peek());
priorityQueue.add("Sumit", 2);
priorityQueue.add("Gourav", 1);
priorityQueue.add("Piyush", 1);
priorityQueue.add("Sunny", 2);
priorityQueue.add("Sheru", 3);
console.log(priorityQueue.printPQueue());
console.log(priorityQueue.peek().element);
console.log(priorityQueue.poll().element);
priorityQueue.add("Sunil", 2);
console.log(priorityQueue.size());
priorityQueue.hasValue('Sumit');
console.log(priorityQueue.printPQueue());
priorityQueue.changePriority("Sheru", 1);
console.log(priorityQueue.printPQueue());
You missing return keyword. This just works:
hasValue(args) {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].element === args) {
return true;
}
}
return false;
}
I did not understand the idea how your changePriority function should work. Just find the element and move it up or down based on priority change:
swap(a, b) {
let tmp = this.items[a];
this.items[a] = this.items[b];
this.items[b] = tmp;
}
changePriority(firstTerm, secondTerm) {
let i = 0;
while (i < this.items.length) {
if (this.items[i].element === firstTerm) {
if (secondTerm < this.items[i].priority) {
// move up
this.items[i].priority = secondTerm;
while (i > 0 && this.items[i - 1].priority > secondTerm) {
this.swap(i - 1, i);
i--;
}
} else if (secondTerm > this.items[i].priority) {
// move down
this.items[i].priority = secondTerm;
while (i < this.items.length - 1 && this.items[i + 1].priority < secondTerm) {
this.swap(i + 1, i);
i++;
}
}
break;
}
i++;
}
}

How to pause the entire code for 1 second in javascript

I am trying to code an evolutionary neural network for the game snake. I already coded the neural network part and now I'd like to output the game of the best individual of every generation. For that I'm using the drawing library p5.js (https://p5js.org/).
In my code I am running a loop in where a new generation based on the last generation is created. Each individual of the generation will have to play the game and that is how they are rated. Now I want the best individual to be outputted after I let every individual play once.
Between each outputted turn of the game of the best individual I want the code to wait 500 milliseconds. How do I achieve that?
Here is the code I've already tried but here it only outputed the board after the last turn of each generation:
async function start() {
for (let i = 0; i < 50; i++) {
population.createNewGeneration();
let bestGameTurns = population.bestIndividual.game.turns; //Array of boards
for (let turn = 0; turn < bestGameTurns.length; turn++) {
let board = bestGameTurns[turn];
drawBoard(board);
let p = new Promise(resolve => setTimeout(resolve, 500));
await p;
function drawBoard(board) {
//Draw the board using p5.js rect()'s
}
}
}
}
Another version but the waiting didn't work here:
let i = 0;
setInterval(async () => {
population.createNewGeneration();
console.log(i, population.avgFitness);
let bestGameTurns = population.bestIndividual.game.turns; //Array of boards
for (let turn = 0; turn < bestGameTurns.length; turn++) {
let board = bestGameTurns[turn];
drawBoard(board);
let p = new Promise(resolve => setTimeout(resolve, 500));
await p;
function drawBoard(board) {
//Draw the board using p5.js rect()'s
}
}
i++;
}, 1);
The code you provided should do what you asked for, I could only clean up some parts for you. Explain a bit better what is the problem you are facing.
// The function should be defined only once.
function drawBoard(board) { }
async function start() {
for (let i = 0; i < 50; i++) {
population.createNewGeneration();
const bestGameTurns = population.bestIndividual.game.turns; //Array of boards
for (let turn = 0; turn < bestGameTurns.length; turn++) {
// Don't wait on first iteration
await new Promise(resolve => setTimeout(resolve, 500 * (turn ? 0 : 1 )));
drawBoard(bestGameTurns[turn]);
}
}
}
Original idea (discarded)
You can create a short function like that:
function pause(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Then in any async function you can call it like that:
async function () {}
// something happening
await pause(500);
// continue
}
The other idea
Now, the code in your question is not complete so this is kind of blind coding but.
So, first of all setInterval will be running the whole function every 1 millisecond (actually 4 ms, as this is the minimum in JS). Which means it will run those loops. I decided to focus on the part that was marked by you.
Instead of loop and trying to pause it, I ask that maybe rewriting the loop into function called each half second until condition is met would do?
Also, I move drawBoard outside
setInterval(async () => {
// ^^^^^^^^ <-- this should probably go
population.createNewGeneration();
console.log(i, population.avgFitness);
let bestGameTurns = population.bestIndividual.game.turns; //Array of boards
function tick(turn = 0) {
let board = bestGameTurns[turn];
function drawBoard(board) {
//Draw the board using p5.js rect()'s
}
drawBoard(board);
// here is "setTimeouted" loop
if (turn < bestGameTurns.length) {
setTimeout(tick, 500, turn + 1);
}
}
tick();
}, 1);
Thanks to everyone, your suggestions brought me to an idea. I found out that the problem was lying somewhere else. Because javascript only runs on the one thread (I think thats how its called), after we run over one generation, we have to stop that function to let another draw function, which runs every frame, draw the board. After it is drawn, the main function can continue. This is how it looks:
let isDrawn = false;
let currentBoard;
async function setup() {
for (let i = 0; i < 50; i++) {
population.createNewGeneration();
const bestGameTurns = population.bestIndividual.game.turns;
for (let turn = 0; turn < bestGameTurns.length; turn++) {
await step(bestGameTurns[turn], turn);
}
}
}
function step(board, turn) {
currentBoard = board;
isDrawn = false;
return new Promise(resolve => setTimeout(() => {
if (isDrawn) resolve();
}, 500));
}
setTimeout(() => {
if (currentBoard) {
drawBoard(currentBoard);
isDrawn = true;
currentBoard = undefined;
}
}, 1);
const nrOfCols = 10;
const nrOfRows = 10;
const fieldWidth = 20;
const nodeNrs = [24, 8, 8, 4];
const populationSize = 200;
const mutationRate = 0.01;
let population;
let game;
let isDrawn = false;
let currentBoard;
async function setup() {
createCanvas(500, 500);
population = new PopulationManager(populationSize);
for (let i = 0; i < 50; i++) {
population.createNewGeneration();
const bestGameTurns = population.bestIndividual.game.turns;
for (let turn = 0; turn < bestGameTurns.length; turn++) {
await step(bestGameTurns[turn]);
}
}
}
function step(board) {
currentBoard = board;
isDrawn = false;
return new Promise(resolve => setTimeout(() => {
if (isDrawn) resolve();
}, 500));
}
function draw() {
if (currentBoard) {
drawBoard(currentBoard);
isDrawn = true;
currentBoard = undefined;
}
}
function drawBoard(board) {
board.forEach((col, colNr) => {
col.forEach((field, rowNr) => {
fill(field.isSnake ? "green" : field.isFruit ? "red" : "black");
stroke(255);
rect(colNr*fieldWidth, rowNr*fieldWidth, fieldWidth, fieldWidth);
});
});
}
function play(game) {
setInterval(() => {
if (!game.lost) {
game.nextTurn();
drawBoard(game.board);
} else {
clearInterval(1);
}
}, 500);
}
class PopulationManager {
constructor(populationSize) {
this.population = createPopulation();
function createPopulation() {
let population = [];
for (let i = 0; i < populationSize; i++) {
let chromosomes = createRandomChromosomes();
let i = new Individual(chromosomes);
population.push(i);
}
return population;
function createRandomChromosomes() {
let arr = [];
let nrOfChromosomes = calcNrOfChromosomes();
for (let i = 0; i < nrOfChromosomes; i++)
arr.push(Math.random()*2-1);
return arr;
function calcNrOfChromosomes() {
let nr = 0;
for (let i = 0; i < nodeNrs.length - 1; i++)
nr += (nodeNrs[i] + 1)*nodeNrs[i + 1];
return nr;
}
}
};
}
createNewGeneration() {
let that = this;
getFitnessOfPop();
this.calcAvgFitness();
this.findBestIndividual();
let parents = selection();
breed(parents);
function getFitnessOfPop() {
that.population.forEach(iv => {
iv.fitness = iv.playGame();
});
that.population.sort((a, b) => a.fitness - b.fitness);
}
function selection() {
let totalFitness = that.population.map(iv => iv.fitness/* + 1 */).reduce((a,b) => a + b);
let allParents = [];
for (let i = 0; i < that.population.length/2; i++) {
allParents.push(selectRandomParents());
}
return allParents;
function selectRandomParents() {
let p1, p2;
do {
p1 = selectRandomParent();
p2 = selectRandomParent();
} while (p1 == p2);
return [p1, p2];
function selectRandomParent() {
let rdm = Math.random()*totalFitness;
return that.population.find((iv, i) => {
let sum = that.population.filter((iv2, i2) => i2 <= i).map(iv => iv.fitness /* + 1 */).reduce((a,b) => a + b);
return rdm <= sum;
});
}
}
}
function breed(allParents) {
that.population = [];
allParents.forEach(ps => {
let childChromosomes = crossOver(ps[0].chromosome, ps[1].chromosome);
childChromosomes = [mutate(childChromosomes[0]), mutate(childChromosomes[1])];
let child1 = new Individual(childChromosomes[0]);
let child2 = new Individual(childChromosomes[1]);
that.population.push(child1);
that.population.push(child2);
});
function crossOver(parent1Chromosome, parent2Chromosome) {
let crossingPoint = Math.round(Math.random()*parent1Chromosome.length);
let divided1 = divideChromosome(parent1Chromosome);
let divided2 = divideChromosome(parent2Chromosome);
let child1Chromosome = divided1[0].concat(divided2[1]);
let child2Chromosome = divided2[0].concat(divided1[1]);
return [child1Chromosome, child2Chromosome];
function divideChromosome(chromosome) {
let part1 = chromosome.filter((g, i) => i <= crossingPoint);
let part2 = chromosome.filter((g, i) => i > crossingPoint);
return [part1, part2];
}
}
function mutate(chromosome) {
chromosome = chromosome.map(g => {
if (Math.random() < mutationRate)
return Math.random()*2-1;
return g;
});
return chromosome;
}
}
}
calcAvgFitness() {
this.avgFitness = this.population.map(iv => iv.fitness).reduce((a, b) => a + b) / this.population.length;
}
findBestIndividual() {
let bestFitness = -1, bestIndividual;
this.population.forEach(i => {
if (i.fitness > bestFitness) {
bestFitness = i.fitness;
bestIndividual = i;
}
});
this.bestIndividual = bestIndividual;
}
}
class Individual {
constructor(chromosome) {
this.chromosome = chromosome;
this.fitness = 0;
this.game = createGame();
function createGame() {
let weights = convertChromosomeToWeights();
let game = new Game(weights);
return game;
function convertChromosomeToWeights() {
let weights = [];
for (let i = 0; i < nodeNrs.length - 1; i++) {
let lArr = [];
for (let j = 0; j < nodeNrs[i] + 1; j++) {
let nArr = [];
lArr.push(nArr);
}
weights.push(lArr);
}
chromosome.forEach((gene, geneIdx) => {
let lIdx = -1, minIdx, maxIdx = 0;
for (let i = 0; i < nodeNrs.length - 1; i++) {
let nr = 0;
for (let j = 0; j <= i; j++)
nr += (nodeNrs[j] + 1)*nodeNrs[j + 1];
if (geneIdx < nr) {
lIdx = i;
break;
}
maxIdx = nr;
minIdx = maxIdx;
}
minIdx = maxIdx;
let nIdx = -1;
for (let i = 0; i < nodeNrs[lIdx] + 1; i++) {
let nr = minIdx + nodeNrs[lIdx + 1];;
if (geneIdx < nr) {
nIdx = i;
break;
}
maxIdx = nr;
minIdx = maxIdx;
}
minIdx = maxIdx;
let wIdx = -1;
for (let i = 0; i < nodeNrs[lIdx + 1]; i++) {
let nr = minIdx + 1;
if (geneIdx < nr) {
wIdx = i;
break;
}
maxIdx = nr;
minIdx = maxIdx;
}
weights[lIdx][nIdx][wIdx] = gene;
});
return weights;
}
}
}
playGame() {
while (!this.game.lost) {
this.game.nextTurn();
}
return this.game.score;
}
}
class Game {
constructor(weights) {
let that = this;
this.chromosome = flattenArray(weights);
this.nn = new NeuralNetwork(weights);
this.turnNr = 0;
this.score = 0;
this.lost = false;
this.board = createBoard();
this.snake = new Snake();
setupSnake();
this.createFruit();
this.turns = [JSON.parse(JSON.stringify(this.board))];
function createBoard() {
let board = [];
for (let colNr = 0; colNr < nrOfCols; colNr++) {
board[colNr] = [];
for (let rowNr = 0; rowNr < nrOfRows; rowNr++) {
let field = new Field(colNr, rowNr);
board[colNr][rowNr] = field;
}
}
return board;
}
function setupSnake() {
for (let i = 0; i < 4; i++)
that.addToTail([floor(nrOfCols/2) - i, floor(nrOfRows/2)]);
that.length = that.snake.body.length;
}
function flattenArray(arr) {
let flattened = [];
flatten(arr);
return flattened;
function flatten(arr) {
arr.forEach(e => {
if (Array.isArray(e))
flatten(e);
else
flattened.push(e);
});
}
}
}
addToTail(pos) {
this.snake.body.push(pos);
this.board[pos[0]][pos[1]].setSnake(true);
}
nextTurn() {
let that = this;
let direction = findDirection();
this.moveSnake(direction);
this.turns.push(JSON.parse(JSON.stringify(this.board)));
this.turnNr++;
checkEat();
function findDirection() {
let inputValues = [];
for (let i = 0; i < 8; i++) {
let distances = that.snake.look(i, that.board);
inputValues.push(distances.distToFruit);
inputValues.push(distances.distToWall);
inputValues.push(distances.distToBody);
}
let output = that.nn.getOutput(inputValues);
let probability = -1;
let direction = -1;
output.forEach((v, vIdx) => {
if (v > probability) {
probability = v;
direction = vIdx;
}
});
return direction;
}
function checkEat() {
let head = that.snake.body[0];
let headField = that.board[head[0]][head[1]];
if (headField.isFruit) {
that.snake.eat();
that.score++;
headField.setFruit(false);
that.createFruit();
}
}
}
createFruit() {
let field;
do {
let colNr = floor(random()*nrOfCols);
let rowNr = floor(random()*nrOfRows);
field = this.board[colNr][rowNr];
} while(field.isSnake);
field.setFruit(true);
}
moveSnake(newDirection) {
let that = this;
let oldBody = JSON.parse(JSON.stringify(that.snake.body));
moveTail();
makeSnakeLonger();
moveHead();
function moveTail() {
for (let i = oldBody.length - 1; i > 0; i--)
that.snake.body[i] = oldBody[i - 1];
}
function moveHead() {
let newHeadPosition = findNewHeadPos();
if (
newHeadPosition[0] >= nrOfCols || newHeadPosition[0] < 0 ||
newHeadPosition[1] >= nrOfRows || newHeadPosition[1] < 0
) {
that.lose();
return;
}
let newHeadField = that.board[newHeadPosition[0]][newHeadPosition[1]];
if (newHeadField.isSnake) {
that.lose();
return;
}
addNewHeadPos(newHeadPosition);
}
function findNewHeadPos() {
if (newDirection == 0) { //up
return [oldBody[0][0], oldBody[0][1] - 1];
} else if (newDirection == 1) { //right
return [oldBody[0][0] + 1, oldBody[0][1]];
} else if (newDirection == 2) { //down
return [oldBody[0][0], oldBody[0][1] + 1];
} else if (newDirection == 3) { //left
return [oldBody[0][0] - 1, oldBody[0][1]];
}
}
function makeSnakeLonger() {
if (that.snake.length > that.snake.body.length) {
that.addToTail(oldBody[oldBody.length - 1]);
} else {
removeFromTail(oldBody[oldBody.length - 1]);
}
}
function removeFromTail(pos) {
that.board[pos[0]][pos[1]].setSnake(false);
}
function addNewHeadPos(pos) {
that.snake.body[0] = pos;
that.board[pos[0]][pos[1]].setSnake(true);
}
}
lose() {
this.lost = true;
}
}
class Field {
constructor(col, row) {
this.col = col;
this.row = row;
this.isFruit = false;
this.isSnake = false;
}
setFruit(bool) {
this.isFruit = bool;
}
setSnake(bool) {
this.isSnake = bool;
}
}
class Snake {
constructor() {
this.body = [];
this.length = 4;
}
eat() {
this.length++;
}
look(direction, board) {
let distances = {distToFruit: 0, distToWall: 0, distToBody: 0};
let xDiff = getXDiff(direction), yDiff = getYDiff(direction);
let pos = [this.body[0][0] + xDiff, this.body[0][1] + yDiff];
let dist = 1;
while (pos[0] > 0 && pos[0] < nrOfRows && pos[1] > 0 && pos[1] < nrOfCols) {
if (board[pos[0]][pos[1]].isFruit && distances.distToFruit == 0) distances.distToFruit = dist;
if (board[pos[0]][pos[1]].isSnake && distances.distToBody == 0) distances.distToBody = dist;
pos[0] += xDiff, pos[1] += yDiff;
dist++;
}
distances.distToWall = dist;
return distances;
function getXDiff(direction) {
if (direction == 5 || direction == 6 || direction == 7) return -1;
else if (direction == 1 || direction == 2 || direction == 3) return 1;
return 0;
}
function getYDiff(direction) {
if (direction == 7 || direction == 0 || direction == 1) return -1;
else if (direction == 3 || direction == 4 || direction == 5) return 1;
return 0;
}
}
}
class NeuralNetwork {
constructor(weights) {
this.layers = createLayers();
this.layers = addWeights(this.layers, weights);
function createLayers() {
let layers = [];
let nrOfNodesGlobal;
nodeNrs.forEach((nrOfNodes, lNr) => {
nrOfNodesGlobal = nrOfNodes;
layers[lNr] = [];
for (let i = 0; i < nrOfNodes; i++) {
let node = createNode(lNr);
layers[lNr][i] = node;
}
if (lNr != nodeNrs.length - 1)
layers[lNr].push(new Bias());
});
return layers;
function createNode(lNr) {
if (lNr == 0) return new InputLayerNode();
else if (lNr == nrOfNodesGlobal - 1) return new OutputLayerNode();
else return new HiddenLayerNode();
}
}
function addWeights(layers, weights) {
for (let lNr = 0; lNr < layers.length - 1; lNr++) {
let l = layers[lNr];
l.forEach((n1, nNr) => {
for (let n2Nr = 0; n2Nr < layers[lNr+1].length - 1; n2Nr++) { //not including bias of next layer
let n2 = layers[lNr+1][n2Nr];
let weight = weights[lNr][nNr][n2Nr];
let w = new Weight(n1, n2, weight);
n1.addWeight(w);
}
});
}
return layers;
}
}
getOutput(inputValues) {
let output = [];
this.layers[0].forEach((inputNeuron, nNr) => {
if (nNr != this.layers[0].length - 1)
inputNeuron.addToInput(inputValues[nNr]);
});
this.layers.forEach((l, lNr) => {
calcOutputs(l);
if (lNr != this.layers.length - 1) {
l.forEach(n => {
n.feedForward();
});
} else {
output = l.map(n => n.output);
}
});
return output;
function calcOutputs(layer) {
layer.forEach(n => n.output = n.activationFunction(n.summedInput, layer.map(N => N.summedInput)));
}
}
log() {
console.log(this.weights, this.nodes);
}
}
class Node {
constructor() {
this.weights = [];
this.summedInput = 0;
}
addWeight(w) {
this.weights.push(w);
}
addToInput(input) {
if (input == NaN)
console.log("A");
this.summedInput += input;
}
feedForward() {
this.weights.forEach((w, wNr) => {
let input = w.weight*this.output;
w.to.addToInput(input);
});
}
}
class Bias extends Node {
constructor() {
super();
this.output = 1;
}
activationFunction(x, allXs) {
return x;
}
}
class InputLayerNode extends Node {
constructor() {
super();
}
activationFunction(x, allXs) {
return x;
}
}
class HiddenLayerNode extends Node {
constructor() {
super();
}
activationFunction(x, allXs) {
return leakyReLU(x);
}
}
class OutputLayerNode extends Node {
constructor() {
super();
}
activationFunction(x, allXs) {
return softmax(x, allXs);
}
}
class Weight {
constructor(from, to, weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
setWeight(newWeight) {
this.weight = weight;
}
}
function leakyReLU(x) {
if (x >= 0) return x;
else return 0.01*x;
}
function softmax(x, allXs) {
return Math.exp(x) / allXs.map(X => Math.exp(X)).reduce((a, b) => a+b);
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
It's not working that well but a few improvements should make it better...
If you have any suggestions for improvements of the code, please let me know!
I tried to fix it into steps as I said in comments,I hope I have no mistake :
let i = 0;
async function step(bestGameTurns, turn)
{
if (turn == bestGameTurns.length)
return;
let board = bestGameTurns[turn];
drawBoard(board);
let p = new Promise(resolve => setTimeout(() => step(bestGameTurns, turn+1), 500));
await p;
}
function drawBoard(board) {
//Draw the board using p5.js rect()'s
}
setInterval(async () => {
population.createNewGeneration();
console.log(i, population.avgFitness);
let bestGameTurns = population.bestIndividual.game.turns; //Array of boards
step(bestGameTurns, 0);
i++;
}, 1);

White page with loop loading in firefox

I have a problem only in Firefox. When I click a button in my application in Firefox the page is white with infinite loading, it's in a loop.
I have done a debugger on my code with dev console and I found where the function breaks. Note that there are no errors in the console.
function setSavedToSended() {
console.log('sono nella funzione')
if (projObjSave == undefined) {
projObjSave = projObj;
}
var items = $("td [id-status]"); //the problem starts here
for (var item in items) {
var _this = parseInt($(items[item] /* here it breaks item*/ ).attr("id-status"));
if (_this == 1) {
var tempId = $(items[item]).attr("id")
$("#" + tempId).attr("id-status", 2).addClass("sended");
var currProj = tempId.split("_");
var projIndex, taskIndex;
for (var i = 0; i < projObj.length; i++) {
if (currProj[0] == projObj[i].projectId) {
projIndex = i;
}
}
if (currProj.length == 3) {
if (currProj[1] == "ORD") {
projObjSave[projIndex].timeTrackingProjectList.timeTrackingOrdinario[currProj[2]]["idStatus"] = 2;
} else {
projObjSave[projIndex].timeTrackingProjectList.timeTrackingStraordinario[currProj[2]]["idStatus"] = 2;
}
} else {
for (var index = 0; index < projObj[projIndex].taskList.length; index++) {
if (currProj[1] == projObj[projIndex].taskList[index].taskId) {
taskIndex = index;
}
}
currProj[2] == "ORD" ? projObjSave[projIndex].taskList[taskIndex].timeTrackingTaskOrdinario[currProj[3]]["idStatus"] = 2 : projObjSave[projIndex].taskList[taskIndex].timeTrackingTaskStraordinario[currProj[3]]["idStatus"] = 2;
}
} else console.log('nothing done')
}
saveSendProject(2)
}

XML Javascript undefined error in ie9

I have a 'jargon buster' on my site that uses an xml file to load an A-Z of words which when clicked display a brief short explanation of each word. This works fine in all browsers bar the latest ie's which i get an 'undefined' error with. The jscript im using is below
Jargon = {
xmlfile: 'http://www.mysite.com/jargon.xml',
xml: null,
wordHolder: 'words',
defHolder: 'definition',
idprefix: 'jargon_',
selected: null,
init: function () {
var con = Jargon.xhcon();
Jargon.wordHolder = $(Jargon.wordHolder);
Jargon.defHolder = $(Jargon.defHolder);
if (!con || !Jargon.wordHolder || !Jargon.defHolder) {
return;
}
function conComplete(oXML) {
Jargon.xml = oXML.responseXML;
//Jargon.showWords('a');
}
con.connect(Jargon.xmlfile, 'GET', Math.random(), conComplete);
},
showWords: function (c) {
if (Jargon.selected) {
Jargon.selected.className = '';
}
var words = Jargon.getWords(c);
while (Jargon.wordHolder.childNodes.length > 0) {
Jargon.wordHolder.removeChild(Jargon.wordHolder.childNodes[0]);
}
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
for (var i = 0; i < words.length; i++) {
var o = document.createElement('a');
o.href = 'javascript:Jargon.showDef(\'' + words[i].id + '\');';
o.id = Jargon.idprefix + words[i].id;
//o.onclick = Jargon.showDef;
o.appendChild($t(words[i].name));
Jargon.wordHolder.appendChild(o);
Jargon.wordHolder.appendChild(document.createElement('br'));
}
if (!words.length) {
var o = document.createElement('p');
var s = 'There are no words for the letter ' + c.toUpperCase();
Jargon.wordHolder.appendChild(o.appendChild($t(s)));
}
},
showDef: function (id) {
var o = $(Jargon.idprefix + id);
if (Jargon.selected) {
Jargon.selected.className = '';
}
if (o) {
o.className = 'selected';
Jargon.selected = o;
}
var defobjs = Jargon.getDef(id);
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
var heading = document.createElement('span');
heading.className = "jargtitle";
heading.appendChild(document.createTextNode(defobjs[1][0].textContent));
Jargon.defHolder.appendChild(heading);
var definition = document.createElement('span');
definition.className = "jargdefinition";
definition.appendChild(document.createTextNode(defobjs[0][0].textContent));
Jargon.defHolder.appendChild(definition);
},
getWords: function(c) {
var x = Jargon.xml;
var letters = x.getElementsByTagName('letter');
var oLetter = null;
for (var i = 0; i < letters.length; i++) {
if (letters[i].getAttribute('id') == c) {
oLetter = letters[i];
break;
}
}
if (!oLetter) {
return [];
}
var words = [];
for (i = 0; i < oLetter.childNodes.length; i++) {
var oJargon = oLetter.childNodes[i];
if (oJargon.nodeName == 'jargon') {
var s = Jargon.getName(oJargon);
words[words.length] = {
id: oLetter.childNodes[i].getAttribute('id'),
name: s
};
}
}
return words;
},
getDef: function (id) {
var x = Jargon.xml;
var j = null;
var temp = new Array(2);
var jargons = x.getElementsByTagName('jargon');
for (var i = 0; i < jargons.length; i++) {
if (jargons[i].getAttribute('id') == id) {
j = jargons[i];
break;
}
}
if (!j) {
return [];
}
//return [];
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'name') {
temp[1] = j.childNodes[i].childNodes;
}
}
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'desc') {
temp[0] = j.childNodes[i].childNodes;
}
}
//return [];
return temp;
},
cloneNode: function (oldNode, deep) {
deep = (deep) ? true : false;
// a replacement to the normal dom clone node
// this will copy xml nodes to html nodes
// which can then be inserted into the document
// scope in all browsers
// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
var newNode = null;
if (oldNode.nodeType == '3') {
// textnode
newNode = $t(oldNode.nodeValue);
}
else if (oldNode.nodeType == '1') {
// element node
newNode = document.createElement(oldNode.nodeName);
if (deep) {
for (var i = 0; i < oldNode.childNodes.length; i++) {
newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
}
}
}
return newNode;
},
getName: function (oJargon) {
for (var i = 0; i < oJargon.childNodes.length; i++) {
if (oJargon.childNodes[i].nodeName == 'name') {
var oName = oJargon.childNodes[i];
var s = '';
for (var j = 0; j < oName.childNodes.length; j++) {
if (oName.childNodes[j].nodeType == 3) {
// text node
s += oName.childNodes[j].nodeValue;
}
}
return s;
}
}
return '';
},
xhcon: function () {
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) {
return null;
}
this.connect = function(sURL, sMethod, sVars, fnDone) {
if (!xmlhttp) {
return false;
}
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET") {
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else {
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && !bComplete) {
bComplete = true;
fnDone(xmlhttp);
}
};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
}
In terms of how im calling the jscript im using <li>a</li>
which loads a list of all items that begin with f then when i click one of items from that list say "Fiduciary" it triggers javascript:Jargon.showDef('f1'); which in turns loads the and into a definition div
however in ie9 it displays "undefined" . It works in all other browers
Example of the XML below:
<letter id="f"> -<jargon id="f1"> <name>Fiduciary</name> <desc>in a position of trust. This includes people such as trustees looking after trust assets for the beneficiaries and company directors running a company for the shareholders' benefit.</desc> </jargon> -<jargon id="f2"> <name>Forfeiture</name> <desc>the loss of possession of a property because the tenancy conditions have not been met by the tenant.</desc> </jargon> -<jargon id="f3"> <name>Freehold</name> <desc>describing land that only the owner has any rights over.</desc> </jargon> -<jargon id="f4"> <name>Free of encumbrances</name> <desc>no one else having any rights over something. When property is owned by someone and nobody else has any rights over it, it is owned free of encumbrances.</desc> </jargon> </letter>

Categories

Resources