1

I am trying to write a tic tac toe game for free code camp.

I want to implement the minimax algorithm.

I found this: https://jsfiddle.net/9486vod0/1/ which is as bad as my code right now.

I believe the problem lies in the way the recursion works, but I am not sure.

This is the full project so far: http://codepen.io/periman/pen/rWovrm?editors=0010

function max(gameb) {

  if (checkboard(gameb) !== 'next') {
    return gameb;
  }

  var bestscore = -1000;
  var bestmove = [];
  var newscore;
  var posmoves = possibleMoves(gameb);

  for(var i = 0; i < posmoves.length; i++) {
    var newboard = gameb.slice();
    newboard[posmoves[i]] = true;
    newscore = scoresofar(min(newboard));

    if (newscore > bestscore) {
      bestscore = newscore;
      bestmove = newboard;
    }
  }
  return bestmove;
}

function min(gameb) {

  if (checkboard(gameb) !== 'next') {
    return [gameb, scoresofar(gameb)];
  }
  var badscore = 1000;
  var worstmove = [];
  var newscore;
  var posmoves = possibleMoves(gameb);

  for(var i = 0; i < posmoves.length; i++) {
    var newboard = gameb.slice();
    newboard[posmoves[i]] = false;
    newscore = scoresofar(max(newboard));

    if (newscore < badscore) {
      badscore = newscore;
      worstmove = newboard;
    }
  }
  return worstmove;
}
jwpfox
  • 5,124
  • 11
  • 45
  • 42
  • Welcome to Stack Overflow. Please read http://stackoverflow.com/help/how-to-ask and then look at your question again, you will probably be able to edit it and get some help – Mikkel Dec 17 '16 at 07:34
  • What errors, if any, is your code producing. What does it do that you don't want? What dies it not do that you do want? You say your code has one or more problems but you need to tell us what they are. You need to give us details if you want help. – jwpfox Dec 19 '16 at 08:06
  • Possible duplicate of [minimax for tic-tac-toe](http://stackoverflow.com/questions/10248451/minimax-for-tic-tac-toe) – Oliver Dec 19 '16 at 08:07
  • Have a look at [this implementation in JavaScript](https://stackoverflow.com/questions/64882717/solving-tictactoe-with-minimax-algorithm-in-javascript/65417503#65417503) – trincot Dec 23 '20 at 00:20

0 Answers0