Function not returning properly when set to a variable but is when console.logged - javascript

The problem is in this function:
function minimax(newBoard,player, depth = 0) {
const availableSpots = emptySquares();
// console.log(availableSpots)
// console.log((checkGameStatus(newBoard,player) ? 'true' : 'false'))
let score = {};
if (checkGameStatus(newBoard, computerSymbol)) {
console.log("Are we hitting here? 1")
// console.log((onCheckWin(newBoard) === false))
// console.log(newBoard,"o")
score = { "score": (-100 + depth)}
return score
} else if (checkGameStatus(newBoard, playerSymbol)) {
console.log("Are we hitting here? 2")
// console.log(checkGameStatus(newBoard))
// console.log(newBoard,"o")
score = { "score": (100 - depth)}
return score
} else if (availableSpots.length === 0) {
console.log("Are we hitting here? 3")
score = { "score": 0 }
return score
}
let moves = [];
for (let i=0; i<availableSpots.length; i++) {
let move = {};
move.index = newBoard[availableSpots[i]];
newBoard[availableSpots[i]] = player;
console.table(newBoard)
if (player === computerSymbol) {
let result = minimax(newBoard, playerSymbol , depth++);
console.log(newBoard,"first");
console.log(result)
move.score = result["score"];
} else {
let result = minimax(newBoard, computerSymbol, (depth + 1));
console.log(newBoard,"first");
move.score = result.score;
}
console.log(moves,move)
newBoard[availableSpots[i]] = move.index;
moves.push(move);
console.log(moves,move)
} // end of for look
let bestMove;
if (player === computerSymbol) {
let bestScore = -10000;
for (let i=0; i<moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
// console.log(bestMove)
}
// end of for loop
}
if (player === playerSymbol) {
let bestScore = 10000;
for (let i=0; i<moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
// console.log(bestMove)
}
}
}
}
return moves[bestMove];
}
When I console.log the function inside of it, it returns an object, but when I set that function call to "result" like here:
if (player === computerSymbol) {
let result = minimax(newBoard, playerSymbol , depth++);
console.log(newBoard,"first");
console.log(result)
move.score = result["score"];
I get undefined as the result and that I can't access property of undefined. Also, I seem to have a problem with my minimax algorithm where it's just constantly choosing the next open square. This might be because I am only using an empty board at the moment. I can add more code if need be, but it seems to me that the problem exists inside the function and not from one of my external or helper functions

Related

Why are my functions executing out of order at the end of this Connect Four game? It works in some browsers

I'm having two timing issues here, both involving the process in this game once the winning move has been made: https://codepen.io/acchang/pen/XWePpWB
Ideally, I should (1) pick the winning space (2) see the winning space filled (3) have the alert proclaim the winner.
What I see and do not like is:
*checkForWinners() runs
winDeclared() runs and the alert "winner" pop up first
Then after the alert is cleared, drawboard() runs, adding the winning piece to the gameboard.
This does not happen as badly in Firefox. The piece is added at the same time the alert pops up.
Then, in winDeclared(), I also change the display in the top right to also indicate the winner. But swapTurns() seems to execute before winDeclared().
Is that because winDeclared() is two functions deep into checkForWinners()? Is there a way to delay it?
Thanks!
let gameboard = [
[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14],
[15,16,17,18,19,20,21],
[22,23,24,25,26,27,28],
[29,30,31,32,33,34,35],
[36,37,38,39,40,41,42]
];
let playerOne
let playerTwo
let indexPick
let availableSpots
let gameType
let playerOneTurn = true
document.getElementsByName("announcements")[0].innerHTML = "Current Player: " + whosPlaying() + " "
let itsAOnePlayerGame = true
let isThereAWinner = false
let mainDiv = document.createElement("div");
mainDiv.setAttribute('class', 'mainDiv')
document.body.append(mainDiv);
let selectorHolder = document.createElement("div")
selectorHolder.setAttribute('class', 'selectorHolder')
selectorHolder.setAttribute('id', 'selectorHolder')
mainDiv.append(selectorHolder)
let selectorTable = document.createElement("table")
selectorTable.setAttribute('class', 'selectorTable')
selectorTable.setAttribute('id', 'selectorTable')
selectorHolder.append(selectorTable)
function drawSelector() {
let selectorRow = document.createElement("tr")
selectorRow.setAttribute('class', 'selectorRow')
selectorTable.append(selectorRow)
for (i=0; i<7; i++){
let selectorCell = document.createElement("td")
selectorCell.setAttribute('class', 'selectorCell')
let innerSelectorCell = document.createElement("div")
innerSelectorCell.setAttribute('class', 'innerSelectorCell')
innerSelectorCell.setAttribute('id', [i])
selectorCell.append(innerSelectorCell)
innerSelectorCell.addEventListener("mouseover", function(event) {
if (playerOneTurn == true) {
innerSelectorCell.classList.add('yellowBG')}
else {innerSelectorCell.classList.add('redBG')
}
})
innerSelectorCell.addEventListener("mouseout", function(event) {
if (playerOneTurn == true) {
innerSelectorCell.classList.remove('yellowBG')}
else {innerSelectorCell.classList.remove('redBG')
}
})
innerSelectorCell.onclick = function(){
if (isThereAWinner == true){return}
else {
indexPick = parseInt(this.id)
console.log(indexPick)
claimSpot()
}
}
selectorRow.append(selectorCell)
}
};
drawSelector()
// Draw Main Gameboard
let mainTable = document.createElement("table");
mainTable.setAttribute('class', 'mainTable')
mainDiv.append(mainTable)
function drawBoard() {
for (i=0; i<gameboard.length; i++){
let row = document.createElement("tr")
mainTable.append(row)
for (j=0; j<gameboard[i].length; j++){
let outerCell = document.createElement('td')
outerCell.setAttribute('class', 'outerCell')
row.append(outerCell)
let innerCell = document.createElement('div')
innerCell.setAttribute('class', 'innerCell')
innerCell.classList.add(gameboard[i][j])
innerCell.setAttribute('innerHTML', gameboard[i][j])
outerCell.append(innerCell)
}
}
};
drawBoard()
function validateRadio() {
let ele = document.getElementsByName('gameType');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked){
gameType = (ele[i].value)
beginGame()
}
}
};
function beginGame() {
if (gameType == "1PEasy"){
itsAOnePlayerGame = true
resetBoard()
onePlayerPickSides()
play1PGame()
}
else if (gameType == "1PHard"){
itsAOnePlayerGame = true
resetBoard()
onePlayerPickSides()
play1PGame()
}
else if (gameType == "2P"){
itsAOnePlayerGame = false
resetBoard()
twoPlayerPickSides()
play2PGame()
}
};
function resetBoard() {
playerOneTurn = true
isThereAWinner = false
gameboard = [
[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14],
[15,16,17,18,19,20,21],
[22,23,24,25,26,27,28],
[29,30,31,32,33,34,35],
[36,37,38,39,40,41,42]
];
}
function swapTurns() {
selectorTable.innerHTML = ""
drawSelector()
playerOneTurn = !playerOneTurn
document.getElementsByName("announcements")[0].innerHTML = "Current Player: " + whosPlaying() + " "
};
// GAMEPLAY
function playerSelects2P() {
findAvailableSpots()
// put an eventListener here?
columnPick = prompt(whosPlaying() + ', choose which column 1-7')
if (availableSpots.includes(parseInt(columnPick)))
{console.log(columnPick)}
else {
alert("not available")
playerSelects2P()}
};
function playerSelects1P() {
if (whosPlaying() == playerTwo) {
findAvailableSpots()
columnPick = availableSpots[Math.floor(Math.random() * availableSpots.length)]
return
}
else {playerSelects2P()}
};
function whosPlaying() {
if (playerOneTurn) {
return "Yellow"
} else {
return "Red"
}
};
// starts from the bottom row and claims spot when there it is a number (unoccupied)
function claimSpot(){
findAvailableSpots()
if (availableSpots.includes(indexPick+1)) {
let i;
for (i = 5; i > -1; i--)
{if (Number.isInteger(gameboard[i][indexPick])) {
gameboard[i].splice((indexPick), 1, whosPlaying())
mainTable.innerHTML = ""
drawBoard()
checkForWinners()
// do I need to put some sort of delay here for it not to go to swap turns right away?
swapTurns()
return
}
}
}
else {
console.log(availableSpots)
alert("Forbidden")
}
};
// if there is a string in row[0], that column is no longer available.
// the cells are numbered from 1 to 7, not per index so you need to add one to indexPick to identify
function findAvailableSpots() {
availableSpots = gameboard[0].filter(x => Number.isInteger(x) == true)
};
function checkForWinners() {
horizontalCheck()
verticalCheck()
downrightCheck()
uprightCheck()
}
// WIN CHECKERS
// a forloop evaluates a section of the matrix, moving through it and seeing if the 3 ahead match.
// it stops before going out of bounds
function findFour(w,x,y,z) {
// Checks first cell against current player and all cells match that player
return ((w == whosPlaying()) && (w === x) && (w === y) && (w === z));
};
function winDeclared() {
isThereAWinner = true
alert("winner")
document.getElementsByName("announcements")[0].innerHTML = whosPlaying() + " wins! "
// this does not show, it snaps to swap places
};
function uprightCheck() {
for (r=5; r>2; r--) {
for (c=0; c<4; c++){
if (findFour(gameboard[r][c], gameboard[r-1][c+1], gameboard[r-2][c+2], gameboard[r-3][c+3])) {
winDeclared()
return
}
}
}
};
function downrightCheck() {
for (r=0; r<3; r++) {
for (c=0; c<4; c++){
if (findFour(gameboard[r][c], gameboard[r+1][c+1], gameboard[r+2][c+2], gameboard[r+3][c+3])) {
winDeclared()
return
}
}
}
};
function verticalCheck() {
for (r=5; r>2; r--) {
for (c=0; c<7; c++){
if (findFour(gameboard[r][c], gameboard[r-1][c], gameboard[r-2][c], gameboard[r-3][c])) {
winDeclared()
return
}
}
}
};
function horizontalCheck() {
for (r=0; r<6; r++) {
for (c=0; c<4; c++){
if (findFour(gameboard[r][c], gameboard[r][c+1], gameboard[r][c+2], gameboard[r][c+3])) {
winDeclared()
return
}
}
}
};
When you manipulate the DOM, the operation itself is syncrhonous but the browser decides when the user will actually see the changes. Sometimes, the broswer will not have time to redraw before the prompt appears. To get around this, you can wrap the alert in a setTimeout() to delay the alert.
setTimeout(
function() {
alert("winner")
}, 10)

In JavaScript class method, Unable to use 'this' inside addEventListener() even using arrow functions. how to solve this issue

I have written a class for Tic Tac Toe game. the code works fine, but i had to use object name inside class definition to call some of the methods instead of 'this' keyword. the problem occurs when method is passed as callbacks to addEventListener().
I tried to solve it by defining the the methods using arrow functions. But JS shows error "can not read property of undefined" error.
How would i overcome this situation.
here is the class implementation. you can see i used game.turnClick instead of this.turnClick
class TicTacToe{
constructor(aiPlayer,humanPlayer){
this.aiPlayer=aiPlayer;
this.humanPlayer=humanPlayer;
this.winCombos=[
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
];
this.originalBoard=Array.from(Array(9).keys());
this.gameWon=null;
this.cells=document.querySelectorAll('.cell');
}
startGame(){
//const cells=document.querySelectorAll('.cell');
this.cells.forEach(function(cell){
cell.innerHTML="";
cell.addEventListener('click',game.turnClick);
})
}
turnClick(e){
game.turn(e.target.id,game.humanPlayer);
if(!game.isTie()&&!game.gameWon){
window.setTimeout(function(){
game.turn(game.bestSquare(),game.aiPlayer);
game.isTie();
},1500);
}
}
turn(squareId,player){
this.originalBoard[squareId]=player;
const square=document.getElementById(squareId);
square.innerHTML=player;
document.querySelector('#click').play();
square.removeEventListener('click',game.turnClick);
this.gameWon=this.checkWin(this.originalBoard,player);
if(this.gameWon){
this.gameOver();
}
}
checkWin(board,player){
let playedSquares=[];
board.forEach(function(el,i){
if(el===player){
playedSquares.push(i);
}
})
console.log(playedSquares);
for(let [index,win] of this.winCombos.entries()){
if(win.every((el)=>{return playedSquares.includes(el)})){
return {index,player};
break;
}
}
return null;
}
gameOver(){
for(let index of this.winCombos[this.gameWon.index] ){
const square=document.getElementById(index);
square.style.backgroundColor= this.gameWon.player===this.humanPlayer?"blue":"red";
}
//const cells=document.querySelectorAll('button.cell');
this.cells.forEach(function(cell){
cell.removeEventListener('click',game.turnClick);
});
this.declareWin(this.gameWon.player===this.humanPlayer?'You Won !!! Hurray...':'You loose,AI beat you...');
}
emptySquares(){
return this.originalBoard.filter((el)=>typeof el==='number');
}
bestSquare(){
//return this.emptySquares()[0];
return this.minimax(this.originalBoard, this.aiPlayer).index;
}
isTie(){
if(this.emptySquares().length===0&& !this.gameWon){
this.cells.forEach(function(cell){
cell.style.backgroundColor='green';
cell.removeEventListener('click',game.turnClick);
});
this.declareWin(' You managed tie the game. congrats !!!');
return true;
}
else{
return false;
}
}
declareWin(msg){
if(msg.includes('won')||msg.includes('tie')){
document.querySelector('#winOrTie').play();
}
else{
document.querySelector('#lost').play();
}
document.querySelector('.endgame .message').innerText=msg;
document.querySelector('.endgame').classList.add('show');
}
minimax(newBoard,player){
let availSpots = this.emptySquares();
if (this.checkWin(newBoard, this.humanPlayer)) {
return {score: -10};
} else if (this.checkWin(newBoard, this.aiPlayer)) {
return {score: 10};
} else if (availSpots.length === 0) {
return {score: 0};
}
let moves = [];
for (let i = 0; i < availSpots.length; i++) {
let move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;
if (player === this.aiPlayer) {
let result = this.minimax(newBoard, this.humanPlayer);
move.score = result.score;
} else {
let result = this.minimax(newBoard, this.aiPlayer);
move.score = result.score;
}
newBoard[availSpots[i]] = move.index;
moves.push(move);
}
let bestMove;
if(player === this.aiPlayer) {
let bestScore = -10000;
for(let i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
let bestScore = 10000;
for(let i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}
}
here is the gitHub repository containing full code
https://github.com/harikrishnan-a-k/Tic_Tac_Toe
cell.addEventListener('click',game.turnClick.bind(game));
You probably need to bind the context of your callback method to the instance.

iframe element returns undefined after onload event?

EDIT: Is there no one who can shed some light on this issue? Anything would be appreciated. :)
I have a script that is supposed to check to see if an elements html contains a given string..
When these elements do exist, my code throws this error: Uncaught TypeError: Cannot read property 'outerHTML' of null
This is the line: let check = document.querySelector("#iframe_${globalI}").contentWindow.document.querySelector(".Row"+inc).outerHTML
I then check to see if the string includes a check string.. IE: check.includes("Pre Trip")
If I run this line directly in the console it works and returns true... So what is going on here..?? How can I get this check to pass..?
I have this check executing after a setTimeout of 20 seconds, then wrapped again in another setTimeout for 500ms as I was trying to figure this out..
Also, I need to note that there are no XSS / CORS issues.
Here is my code..
function checkRowCount(x){
console.log("Row count called on "+x);
let rowCount = 0;
for(let i = 0; i < 30; i++){
if(typeof(document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i)) != 'undefined' && document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i) != null){
rowCount++;
}
}
console.log(rowCount);
return rowCount;
}
let globalCompiler = []; //globalCompiler[globalI] = {unit: unitNumber[globalI], data: ["X", " ", "NO POST TRIP]}
let unitNumber = [1031,1743,1744,1986,3239,3256,3257,4024,4062,4063,4064,4065,4247,4309,4315,4326,4327,4334,4335,4337,4350,4382,4385,7166,7380,7381,8765,8823,8945,8950,8988,10720,17045,17163,40014,40069,40122,40380,80129,80188,80700,80701,80702,80728,80831,80852,80875,"80876","81027","81038","401288","401306","402409","60099T","CH889","CH890","SR31077","T19","U5509","U6660","U6667","U6675","U8854","US1025T"];
let url = "http://winweb.cleanharbors.com/Vehicle/VehicleTDSearch.aspx?SearchType=DVIR";
function iframeLoaded(selector, unit, setDate, callback){
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtStartDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtEndDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtVhcleNo").value = unit;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#btnRetrieve").click();
}
let loadFinished = {};
for(let dec = 0; dec < unitNumber.length; dec++){
loadFinished[unitNumber[dec]] = false;
}
console.log(loadFinished);
for(let globalI = 0; globalI < 3; globalI++){
globalCompiler[globalI] = {unit: unitNumber[globalI], data: []};
let iframeObj = document.createElement('iframe');
iframeObj.id = `iframe_${globalI}`;
iframeObj.hidden = false;
iframeObj.src = url;
iframeObj.onload = () => {
if (loadFinished[unitNumber[globalI]] == false) {
loadFinished[unitNumber[globalI]] = true;
let setDate = "11/01/2019";
iframeLoaded(globalI, unitNumber[globalI], setDate);
console.log("iframeloaded called on " + globalI);
setTimeout(() => {
setTimeout(() => {
let dateCheckObject = {}, rowCount = checkRowCount(globalI), trackingArr = [];
if (rowCount == 0) {
globalCompiler[globalI].data.push(" ");
} else {
for (let inc = 1; inc <= rowCount; inc++) {
//let check = $('#iframe_'+globalI).contents().find(`.Row` + inc).html().includes("Pre Trip");
let check = document.querySelector(`#iframe_${globalI}`).contentWindow.document.querySelector(".Row"+inc).outerHTML
if (check.includes("Pre Trip")) {
dateCheckObject.pre = true;
} else {
dateCheckObject.post = true;
}
}
if(dateCheckObject.pre && dateCheckObject.post) {
console.log("X");
globalCompiler[globalI].data.push("X");
dateCheckObject = {};
} else if (dateCheckObject.pre == 'undefined') {
console.log("NO PRE");
globalCompiler[globalI].data.push("NO PRE TRIP");
dateCheckObject = {};
} else {
console.log("NO POST");
globalCompiler[globalI].data.push("NO POST TRIP");
dateCheckObject = {};
}
}
},500);
}, 20000);
}
};
document.body.appendChild(iframeObj);
console.log("Global Loop called");
}
```
A for loop ran one count too far...
e.g.: for (let inc = 1; inc <= rowCount; inc++)
Should have been for (let inc = 1; inc < rowCount; inc++)

Is there a javascript library that does spreadsheet calculations without the UI

I am working on a project that needs an excel like calculation engine in the browser. But, it doesn't need the grid UI.
Currently, I am able to do it by hiding the 'div' element of Handsontable. But, it isn't elegant. It is also a bit slow.
Is there a client side spreadsheet calculation library in javascript that does something like this?
x = [ [1, 2, "=A1+B1"],
[2, "=SUM(A1,A2"),3] ];
y = CalculateJS(x);
##############
y: [[1, 2, 3],
[2,3,3]]
I'm not aware of any (although I haven't really looked), but if you wish to implement your own, you could do something along these lines (heavily unoptimized, no error checking):
functions = {
SUM: function(args) {
var result = 0;
for (var i = 0; i < args.length; i++) {
result += parseInt(args[i]);
}
return result;
}
};
function get_cell(position) {
// This function returns the value of a cell at `position`
}
function parse_cell(position) {
cell = get_cell(position);
if (cell.length < 1 || cell[0] !== '=')
return cell;
return parse_token(cell.slice(1));
}
function parse_token(tok) {
tok = tok.trim();
if (tok.indexOf("(") < 0)
return parse_cell(tok);
var name = tok.slice(0, tok.indexOf("("));
if (!(name in functions)) {
return 0; // something better than this?
}
var arguments_tok = tok.slice(tok.indexOf("(") + 1);
var arguments = [];
while (true) {
var arg_end = arguments_tok.indexOf(",");
if (arg_end < 0) {
arg_end = arguments_tok.lastIndexOf(")");
if (arg_end < 0)
break;
}
if (arguments_tok.indexOf("(") >= 0 && (arguments_tok.indexOf("(") < arg_end)) {
var paren_amt = 1;
arg_end = arguments_tok.indexOf("(") + 1;
var end_tok = arguments_tok.slice(arguments_tok.indexOf("(") + 1);
while (true) {
if (paren_amt < 1) {
var last_index = end_tok.indexOf(",");
if (last_index < 0)
last_index = end_tok.indexOf(")");
arg_end += last_index;
end_tok = end_tok.slice(last_index);
break;
}
if (end_tok.indexOf("(") > 0 && (end_tok.indexOf("(") < end_tok.indexOf(")"))) {
paren_amt++;
arg_end += end_tok.indexOf("(") + 1;
end_tok = end_tok.slice(end_tok.indexOf("(") + 1);
} else {
arg_end += end_tok.indexOf(")") + 1;
end_tok = end_tok.slice(end_tok.indexOf(")") + 1);
paren_amt--;
}
}
}
arguments.push(parse_token(arguments_tok.slice(0, arg_end)));
arguments_tok = arguments_tok.slice(arg_end + 1);
}
return functions[name](arguments);
}
Hopefully this will give you a starting point!
To test in your browser, set get_cell to function get_cell(x) {return x;}, and then run parse_cell("=SUM(5,SUM(1,7,SUM(8,111)),7,8)"). It should result in 147 :)
I managed to do this using bacon.js. It accounts for cell interdependencies. As of now, it calculates values for javascript formula instead of excel formula by using an eval function. To make it work for excel formulae, all one has to do is replace eval with Handsontable's ruleJS library. I couldn't find a URI for that library... hence eval.
https://jsfiddle.net/sandeep_muthangi/3src81n3/56/
var mx = [[1, 2, "A1+A2"],
[2, "A2", "A3"]];
var output_reference_bus = {};
var re = /\$?[A-N]{1,2}\$?[1-9]{1,4}/ig
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');
function convertToCellRef(rows, cols) {
var alphabet_index = rows+1,
abet = "";
while (alphabet_index>0) {
abet = alphabet[alphabet_index%alphabet.length-1]+abet;
alphabet_index = Math.floor(alphabet_index/alphabet.length);
}
return abet+(cols+1).toString();
}
function getAllReferences(value) {
if (typeof value != "string")
return null;
var references = value.match(re)
if (references.length == 0)
return null;
return references;
}
function replaceReferences(equation, args) {
var index = 0;
return equation.replace(re, function(match, x, string) {
return args[index++];
});
}
//Assign an output bus to each cell
mx.forEach(function(row, row_index) {
row.forEach(function(cell, cell_index) {
output_reference_bus[convertToCellRef(row_index, cell_index)] = Bacon.Bus();
})
})
//assign input buses based on cell references... and calculate the result when there is a value on all input buses
mx.forEach(function(row, row_index) {
row.forEach(function(cell, cell_index) {
if ((all_refs = getAllReferences(cell)) != null) {
var result = Bacon.combineAsArray(output_reference_bus[all_refs[0]]);
for (i=1; i<all_refs.length; i++) {
result = Bacon.combineAsArray(result, output_reference_bus[all_refs[i]]);
}
result = result.map(function(data) {
return eval(replaceReferences(cell, data));
})
result.onValue(function(data) {
console.log(convertToCellRef(row_index, cell_index), data);
output_reference_bus[convertToCellRef(row_index, cell_index)].push(data);
});
}
else {
if (typeof cell != "string")
output_reference_bus[convertToCellRef(row_index, cell_index)].push(cell);
else
output_reference_bus[convertToCellRef(row_index, cell_index)].push(eval(cell));
}
})
})
output_reference_bus["A2"].push(20);
output_reference_bus["A1"].push(1);
output_reference_bus["A1"].push(50);

Javascript: scope effect despite order of execution

Please note: This is not a question about scope, per se. I understand that in order to make the code work, I should make a deep copy of the variable board rather than assigning var tboard = board. However, I am not clear why making a shallow copy has the effect I describe below.
I am experiencing something I find baffling. Basically, a global variable (board) gets altered and I have no clue how. board is initialized in the function NewGame() (which is called from select()) as an empty array. After it is initialized, nothing else is called until the user clicks a square on the board (assuming the user has selected Xs for simplicity). When that happens, the function playerMove() is called. The baffling thing is that console.log(board) at the top of playerMove() prints out an array that has an x is the clicked position and os everywhere else (ie not empty). This is bizarre because the board is empty at the end of select() (which called NewGame()) and nothing else should happen in between. To demonstrate this, I print out the function name at the top of each function and I print out the board variable in the select() function and playerMove() function to show that it changes despite nothing else being called. Please note that to get this behavior, refresh the page (otherwise the board variable starts out full of os). I think this must be somewhat an issue of scope (because I am not making a deep copy of board) but it's strange because I have no clue what is being called that is changing the variable before it gets printed out at the top of playerMove().
Here is the link to my pen and the code: http://codepen.io/joshlevy89/pen/MKjxop?editors=101
$(document).ready(function() {
var pSym; // player's symbol
var cSym; // computer's symbol
var board;
var whosMove; // can be "player" or "computer" or "neither"
var gameOver;
setup();
$("#newgame").on('click', '#X', select);
$("#newgame").on('click', '#O', select);
$("#restart").on('click', setup);
$("table").on('click', 'td', playerMove);
function playerMove()
{
console.log('playerMove');
console.log(board);
if (whosMove === "player")
{
var val = $(this).data('value');
$('#g' + val).text(pSym);
var arr = PositionToCoords(val);
board[arr[0]][arr[1]] = pSym;
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0)
{
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "computer";
computerMove();
}
}
function computerMove() {
console.log('computerMove');
//var p1 = Math.floor(Math.random() * 3);
//var p2 = Math.floor(Math.random() * 3);
var tboard = board;
var pos = chooseMove(tboard);
var arr = PositionToCoords(pos);
board[arr[0]][arr[1]] = cSym;
DrawPosition(arr[0], arr[1], cSym);
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0) {
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "player";
}
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves=[];
var scores = [];
for (var i=1;i<10;i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}
function endGame(gc) {
console.log('endGame');
var str;
if (gc===1) { // somebody won
if (whosMove==="player"){
str = "You Won!"
}
else {
str = "You Lost :(";
}
}
else if (gc === 0){//draw
str = "It's a draw."
}
html = '<div id="closer">' + str + '</div>';
$('#endgame').html(html);
}
function gameCheck(tboard) {
console.log('gameCheck');
// get symbol to check for
var sym;
if (whosMove === "player") {
sym = pSym;
} else {
sym = cSym;
}
// check if in a row
var hrow;
var vrow;
// check for horizonal row
for (var i = 0; i < 3; i++) {
hrow = true;
vrow = true;
for (var j = 0; j < 3; j++) {
if (tboard[i][j] !== sym) {
hrow = false;
}
if (tboard[j][i] !== sym) {
vrow = false;
}
}
if ((hrow) || (vrow)) {
return 1;
}
}
var fdrow = true;
var bdrow = true;
for (var i = 0; i < 3; i++) {
if (tboard[i][i] !== sym) {
fdrow = false;
}
if (tboard[i][2 - i] !== sym) {
bdrow = false;
}
}
if ((fdrow) || (bdrow)) {
return 1;
}
// otherwise, check if board is full
var full = true;
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (tboard[arr[0]][arr[1]] === undefined) {
full = false;
break;
}
}
if (full === true) {
return 0;
}
// if neither 0 (tie) or win (1), return -1 (game not over)
return -1;
}
function select() {
console.log('select');
pSym = $(this).data('value');
$('#newgame').html('');
NewGame();
console.log(board);
}
function setup() {
console.log('select');
$('#endgame').html('');
html = '<div id="opener">Xs or Os? <div id="buttons">';
html += '<div id="X" data-value="X" class="btn btn-default">Xs</div>';
html += '<div id="O" data-value="O" class="btn btn-default">Os</div>';
html += '</div></div>';
$('#newgame').html(html);
}
function NewGame() {
console.log('NewGame');
$('td').empty();
board = new Array(3);
for (i = 0; i < 3; i++) {
board[i] = new Array(3)
};
if (pSym === "X") {
cSym = "O";
whosMove = "player";
} else {
cSym = "X";
whosMove = "computer";
computerMove();
}
}
function DrawPosition(p1, p2, sym) {
console.log('DrawPosition');
var pos = p1 * 3 + (p2 + 1);
$("#g" + pos).text(sym)
}
function PositionToCoords(pos) {
console.log('PositionToCoords');
var p1 = Math.ceil(pos / 3) - 1;
var p2 = ((pos - 1) % 3);
var arr = [p1, p2];
return arr;
}
});
Thanks in advance.
Simply add the break in the for loop fixes the problem. Am I missing anything?
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves = [];
var scores = [];
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
break; // <<<<<<<<<<<< This break guarantees that the computer only makes one move
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}

Categories

Resources