I'm trying to implement a Tic-Tac-Toe game using a minimax algorithm for n number of grid size in Javascript.
I have copied the algorithm from geeksforgeeks exactly, but in Javascript the result is not expected and something weird is happening beyond my understanding.
I'm calling the function computerTurn(moves) to make the computer move, and inside it calling the function getBestMove(gridArr, depth, isMax, moves) to get the best move via the minimax algorithm.
In both functions, I'm first checking the empty cell in the grid then assigning it with a specific turn, and then calling the getBestMove function with the new grid. However sometimes the assignment of the grid does not take place and the getBestMove method is called.
Secondly, when I'm printing the grid array in the getBestMove method, it's always printing the same array with only two elements like...
gridArr:- 0:-[1,2,0], 1:-[0,0,0], 2:-[0,0,0]
... and every time the next empty cell is returned as bestMove.
At first, I thought that the same array has been passed to every getBestMove function but when I log the score I'm getting results from the evaluateScore(grid) method (which returns 10 for win, -10 to lose and 0 for draw) returning 10 and -10 as well.
See code below.
In any case, what needs to happen is in each iteration of both functions, when an empty cell is detected the function makes a move i.e assignment of turn into the grid and then pass that grid into the function call.
I'm using 1 for 'X', 2 for '0' and 0 for empty cells in the grid. GRID_LENGTH is the size of row of Tic-Tac-Toe which is 3 for now, and grid is the 2d array for storing X and 0. In the evaluateScore function, WIN_LENGTH is the length to decide winning state, which 3 in this case
This is git repository, which creates the error(s) in question
Thank You all!!
function computerTurn(moves) {
let bestValue = -1000,
bestMove = [];
for (let row = 0; row < GRID_LENGTH; row++) {
for (let col = 0; col < GRID_LENGTH; col++) {
if (grid[row][col] == 0) {
// searching for empty cell
grid[row][col] = 2; // making move
moves++; // increment moves count
let moveValue = getBestMove(grid, 0, false, moves); // checking is this is the best move
moves--;
grid[row][col] = 0;
if (moveValue > bestValue) {
// updating values
bestMove[0] = row;
bestMove[1] = col;
bestValue = moveValue;
}
}
}
}
grid[bestMove[0]][bestMove[1]] = 2;
turn = 'X';
return bestMove;
}
function getBestMove(gridArr, depth, isMax, moves) {
let score = evaluateScore(gridArr);
let arr = gridArr;
if (score == 10 || score == -10) {
return score;
}
if (moves == totalMoves) {
return 0;
}
if (isMax) {
let best = -1000;
for (let i = 0; i < GRID_LENGTH; i++) {
for (let j = 0; j < GRID_LENGTH; j++) {
if (arr[i][j] == 0) {
arr[i][j] = 2;
moves++;
best = Math.max(best, getBestMove(arr, depth + 1, !isMax, moves));
arr[i][j] = 0;
moves--;
}
}
}
return best;
} else {
let best = 1000;
for (let i = 0; i < GRID_LENGTH; i++) {
for (let j = 0; j < GRID_LENGTH; j++) {
if (arr[i][j] == 0) {
arr[i][j] = 1;
moves++;
best = Math.min(best, getBestMove(arr, depth + 1, !isMax, moves));
arr[i][j] = 0;
moves--;
}
}
}
return best;
}
}
function evaluateScore(gridArr) {
let diff = GRID_LENGTH - WIN_LENGTH;
let len = WIN_LENGTH - 1;
for (let i = 0; i < GRID_LENGTH; i++) { // check win for different rows
if (diff == 0) {
let win = true;
for (let j = 0; j < len; j++) {
if (gridArr[i][j] != gridArr[i][j + 1]) {
win = false;
break;
}
}
if (win) {
if (gridArr[i][0] == 1) {
return -10;
} else if (gridArr[i][0] == 2) {
return 10;
}
}
} else {
for (let j = 0; j <= diff; j++) {
let count = 0;
for (let k = j; k < len; k++) {
if ((gridArr[i][k] != gridArr[i][k + 1])) {
count++;
}
if (count == len) {
if (gridArr[i][k] == 1) {
return -10;
} else if (gridArr[i][k] == 2) {
return 10;
}
}
}
}
}
}
for (let i = 0; i < GRID_LENGTH; i++) { // check win for different cols
if (diff == 0) {
let win = true;
for (let j = 0; j < len; j++) {
if (gridArr[j][i] != gridArr[j][i + 1]) {
win = false;
break;
}
}
if (win) {
if (gridArr[0][i] == 1) {
return -10;
} else if (gridArr[0][i] == 2) {
return 10;
}
}
} else {
for (let j = 0; j <= diff; j++) {
let count = 0;
for (let k = j; k < len; k++) {
if ((gridArr[k][i] != gridArr[k][i + 1])) {
count++;
}
if (count == len) {
if (gridArr[k][i] == 1) {
return -10;
} else if (gridArr[k][i] == 2) {
return 10;
}
}
}
}
}
}
let diagonalLength = GRID_LENGTH - WIN_LENGTH;
for (let i = 0; i <= diagonalLength; i++) { // diagonals from left to right
for (let j = 0; j <= diagonalLength; j++) {
let row = i,
col = j;
let win = true;
for (let k = 0; k < len; k++) {
if (gridArr[row][col] != gridArr[row + 1][col + 1]) {
win = false;
break;
}
row++;
col++;
}
if (win) {
if (gridArr[i][j] == 1) {
return -10;
} else if (gridArr[i][j] == 2) {
return 10;
}
}
}
}
let compLen = GRID_LENGTH - diagonalLength - 1;
for (let i = 0; i >= diagonalLength; i--) { // diagonals from right to left
for (let j = GRID_LENGTH - 1; j >= compLen; j--) {
let row = i,
col = j;
let win = true;
for (let k = 0; k < len; k++) {
if (gridArr[row][col] != gridArr[row + 1][col - 1]) {
win = false;
break;
}
row++;
col--;
}
if (win) {
if (gridArr[i][j] == 1) {
return -10;
} else if (gridArr[i][j] == 2) {
return 10;
}
}
}
}
return 0;
}
Related
I watched a coding train video about the game of life and i tried making a program but it doesn't work. It just generates random squares on the screen as a first image (the starting position) and then just generates another frame with the positive squares (white) disappearing and that's it. Only 2 frames. And it doesn't show an error. Can someone explain why?
function make2D(x, y) {
let arr = new Array(x);
for (let i = 0; i < x; i++) {
arr[i] = new Array(y);
}
return arr;
}
let grid;
let col;
let row;
let resolution = 20;
function setup() {
createCanvas(500, 500);
col = width / resolution;
row = height / resolution;
grid = make2D(col, row);
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
frameRate(1);
background(0);
//drawing
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j]) {
fill(255);
} else {
fill(0);
}
rect(x, y, resolution, resolution);
}
}
//processing
let next = make2D(col, row);
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
let nb = calculatePosition(grid, i, j);
//fill(255,0,0);
//text(grid[i][j],i*resolution+6,j*resolution+15);
if (grid[i][j] == 0 && nb == 3) {
next[i][j] == 1;
} else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
next[i][j] == 0;
} else {
next[i][j] = grid[i][j];
}
}
}
grid = next;
}
function calculatePosition(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let cols = (x + i + col) % col;
let rows = (y + j + row) % row;
sum += grid[cols][rows];
}
}
sum -= grid[x][y];
console.log(sum);
return sum;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
You accidentally are using equality (==) instead of assignment (=) here
if (grid[i][j] == 0 && nb == 3) {
next[i][j] == 1;
} else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
next[i][j] == 0;
} else {
next[i][j] = grid[i][j];
}
You should also move your frameRate call to setup().
function LCSubStr(X, Y) {
let m = X.length;
let n = Y.length;
let result = 0;
let end;
let len = new Array(4);
for (let i = 0; i < len.length; i++) {
len[i] = new Array(n);
for (let j = 0; j < n; j++) {
len[i][j] = 0;
}
}
let currRow = 0;
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
len[currRow][j] = 0;
}
else if (X[i - 1] == Y[j - 1]) {
len[currRow][j] = len[1 - currRow][j - 1] + 1;
if (len[currRow][j] > result) {
result = len[currRow][j];
end = i - 1;
}
}
else {
len[currRow][j] = 0;
}
}
currRow = 1 - currRow;
}
if (result == 0) {
return "-1";
}
return X.substr(end - result + 1, result);
}
// Driver Code
let X = "GeeksforGeeks";
let Y = "GeeksQuiz";
// function call
document.write(LCSubStr(X, Y));
How can I convert this code for multiple input?
I checked many lcs code but no one works with
ABCQEFDEFGHIJ BCXEFGYZBCDEWEFGHU > EFGH
This one just works good without any problem. I should convert this one for multiple input in Javascript.
Now we have X,Y but it shoulde be with multiple inputs.
I've implemented Conway's game of life in p5.js.
I have a function which counts the number of alive neighbours of a given cell, it appears from the tests I did that it works perfectly. That being said I'm having unexpected behaviour when it comes to simulating : it's not following the correct patterns. I start here with 3 aligned squares (a blinker) and it's supposed to rotate but for some reason they just all die.
Wikipedia shows how a blinker should behave : https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Examples_of_patterns
You can copy paste the source below into https://editor.p5js.org/ and see for yourself.
I'm suspecting the issue has got something to do with copying of the board (matrice of cells), because an update has to be simultaneous for all cells, hence we keep in memory the previous board and update the current board based on the previous board.
Source :
//size of cell in pixels.
const size = 20;
const canvasWidth = 400;
const canvasHeight = 400;
const n = canvasWidth / size;
const m = canvasHeight / size;
class Cell {
constructor(status, position) {
this.status = status;
this.position = position;
}
}
let board = [];
function setup() {
//initialise matrix.
for(let i=0; i < m; i++) {
board[i] = new Array(n);
}
//fill matrix of cells.
for(let i=0; i < m; i++ ) {
for(let j=0; j < n; j++ ) {
board[i][j] = new Cell(false, [i*size, j*size]);
}
}
console.log("start", floor(m /2), floor(n / 2))
//[x, y] positions.
board[floor(m /2)][floor(n / 2)].status = true;
board[floor(m /2)+1][floor(n / 2)].status = true;
board[floor(m /2)+2][floor(n / 2)].status = true;
createCanvas(canvasWidth, canvasHeight);
frameRate( 1 )
}
//I'm 99.99% sure this function works, all the tests shows it does.
function updateCell(i, j, previousBoard) {
let count = 0;
//check neighbourgh cells.
for(let k=-1; k < 2; k++) {
for(let p=-1; p < 2; p++) {
if( !(i + k < 0 || j + p < 0 || j + p >= n || i + k >= m) ) {
if(k != 0 || p != 0) {
if(previousBoard[i+k][j+p].status === true) {
count++;
}
}
}
}
}
console.log(count)
if((previousBoard[i][j].status === true) && (count < 2 || count > 3)) {
//console.log("false", i, j, count)
board[i][j].status = false;
} else if((count === 3) && (previousBoard[i][j].status === false)) { //if dead but 3 alive neighbours.
//alive
console.log("true", i, j, count)
board[i][j].status = true;
} else if((previousBoard[i][j].status === true) && (count === 2 || count === 3)) {
console.log("true", i, j, count)
board[i][j].status = true;
}
}
function copyMatrix() {
let newMatrix = []
for(let i=0; i < m; i++) {
//console.log(board[i])
newMatrix[i] = board[i].slice()
}
//console.log(newMatrix)
return newMatrix
}
function draw() {
background(220);
//draw rectangles.
for(let i=0; i < m; i++) {
for(let j=0; j < n; j++) {
if (board[i][j].status === true) {
fill('black');
} else {
fill('white');
}
rect(board[i][j].position[0], board[i][j].position[1], size, size);
}
}
//slice copies previous array into a new reference, previousBoard and board are
//now independent.
let previousBoard = copyMatrix();
//updateCell(11, 9, previousBoard) //uncommenting this line creates weird results...
//console.log(previousBoard)
//update all cells based on previousBoard. (we'll modify board based on previous)
for(let i=0; i < m; i++) {
for(let j=0; j < n; j++) {
updateCell(i, j, previousBoard);
}
}
}
<html>
<head>
<Title>Gordon's Game of Life</Title>
<script src = "p5.js"></script>
<script src = "sketch.js"></script>
</head>
<body>
<h1>Gordon's Game of Life</h1>
</body>
</html>
The issue is that copyMatrix needs to do a deep copy.
Change copy matrix to this:
function copyMatrix() {
let newMatrix = []
for(let i=0; i < m; i++) {
newMatrix[i] = [];
for (let j=0;j< n;j++){
newMatrix[i][j] = new Cell(board[i][j].status, board[i][j].position);
}
}
return newMatrix
}
Here is your code with the copyMatrix change and an added glider to help demonstrate behavior.
//size of cell in pixels.
const size = 20;
const canvasWidth = 400;
const canvasHeight = 400;
const n = canvasWidth / size;
const m = canvasHeight / size;
class Cell {
constructor(status, position) {
this.status = status;
this.position = position;
}
}
let board = [];
function setup() {
//initialise matrix.
for(let i=0; i < m; i++) {
board[i] = new Array(n);
}
//fill matrix of cells.
for(let i=0; i < m; i++ ) {
for(let j=0; j < n; j++ ) {
board[i][j] = new Cell(false, [i*size, j*size]);
}
}
board[floor(m /2)][floor(n / 2)].status = true;
board[floor(m /2)+1][floor(n / 2)].status = true;
board[floor(m /2)+2][floor(n / 2)].status = true;
// glider
board[0][0].status = true;
board[0][2].status = true;
board[1][1].status = true;
board[1][2].status = true;
board[2][1].status = true;
createCanvas(canvasWidth, canvasHeight);
frameRate( 1 )
}
function updateCell(i, j, previousBoard) {
let count = 0;
//check neighbourgh cells.
for(let k=-1; k < 2; k++) {
for(let p=-1; p < 2; p++) {
if( !(i + k < 0 || j + p < 0 || j + p >= n || i + k >= m) ) {
if(k != 0 || p != 0) {
if(previousBoard[i+k][j+p].status === true) {
count++;
}
}
}
}
}
if((previousBoard[i][j].status) && (count < 2 || count > 3)) {
board[i][j].status = false;
} else if((count === 3) && (!previousBoard[i][j].status)) { //if dead but 3 alive neighbours.
board[i][j].status = true;
} else if((previousBoard[i][j].status) && (count === 2 || count === 3)) {
board[i][j].status = true;
}
}
function copyMatrix() {
let newMatrix = []
for(let i=0; i < m; i++) {
newMatrix[i] = [];
for (let j=0;j< n;j++){
newMatrix[i][j] = new Cell(board[i][j].status, board[i][j].position);
}
}
return newMatrix
}
function draw() {
background(220);
//draw rectangles.
for(let i=0; i < m; i++) {
for(let j=0; j < n; j++) {
if (board[i][j].status === true) {
fill('black');
} else {
fill('white');
}
rect(board[i][j].position[0], board[i][j].position[1], size, size);
}
}
let previousBoard = copyMatrix();
//updateCell(11, 9, previousBoard) //uncommenting this line creates weird results...
//console.log(previousBoard)
//update all cells based on previousBoard. (we'll modify board based on previous)
for(let i=0; i < m; i++) {
for(let j=0; j < n; j++) {
updateCell(i, j, previousBoard);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
With the glider this setup demonstrates all three possible patterns. We start with a moving spaceship glider and an oscillator and when the glider runs into the oscillator we have a few iterations that break both patterns and then it settles down into a 2x2 still life.
Ok so i tried to make conway's game of life in p5.js and i am stuck in some wierd bug .
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = x + i;
let row = y + i;
if (grid[col][row] === undefined){
sum += grid[col][row];
}
}
}
sum-=grid[x][y]
return sum;
}
let grid;
let next;
let cols;
let rows;
let resolution = 20;
let fr = 15;
function setup() {
createCanvas(600, 400);
frameRate(fr);
cols = width / resolution;
rows = height / resolution;
next = make2DArray(cols, rows);
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
fill(0);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
} else {
fill(255);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
}
}
}
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
}
Soo basically i have function countNeighbors and i think that bug is in there , i tried checking if col and row are i boundaries of array
like this
if (col>-1 && col <grid.length && row>-1 && row < grid[0].length){
//increase sum
}
but its even worse. I am new to js so i figured out that if for example
let x=new Array(10);
//and then when i try this
console.log(c[-1])
//it should give undefined
but program still wont work :(
Thanks!
With a few changes you can make it work:
1) Replace let row = y + i; by let row = y + j; That typo was making most of the counts off.
2) Replace the condition
if (grid[col][row] === undefined){
by
if (0 <= col && col < cols && 0 <= row && row < rows){
The problem with your original condition is that if grid[col] is undefined then grid[col][row] is undefined[row], which doesn't make sense.
3) For consistency sake, add a semicolon to the end of sum-=grid[x][y]
4) Finally, so as to not create an unintended alias, you need to replace grid = next by something like:
for(let i = 0; i < grid.length; i++){
grid[i] = next[i].slice();
}
Alternatively, make next a variable which is local to draw() and place the line let next = make2DArray(cols, rows); to the beginning of draw().
Im trying to solve problem #4 on project Euler,im using a simple for-loop to sift through each element of the array and "missing ) after for-loop control"
Code below
var palidrome = function (num) {
var numstr = (num).toString().split("");
var count = 0;
for (var i = 0, i2 = numstr.length - 1; i < numstr.length / 2 && i2 >= numstr.length / 2; i++, i2--) {
if (numstr[i] !== numstr[i2]) {
return 0;
} else {
if (count == 3) {
return numstr.join("");
}
}
count++;
}
};
for (var i = 999; i >= 100; i--) {
for (var j = 100; j = < i; j++) {
if (palidrome(i * j) !== 0) {
alert(palidrome(i * j));
break;
}
}
}
Thank you for the assistance,much appreciated.
In for loop you have error: j = < i must be j <= i
for (var i = 999; i >= 100; i--) {
for (var j = 100; j <= i; j++) {
if (palidrome(i * j) !== 0) {
alert(palidrome(i * j));
break;
}
}
}