JSFiddle - React, Tailwind, and code Playground

by CommandLineDesign

HTML

<div id="gameBoard"></div>

JavaScript

// ===================== Init: =====================

/* Config input schema: {
	"rows": 6,
	"cols": 7,
	"moves": [0,0,1,1,2,2,3]
}*/

var ConnectFour = function(config) {

  Object.assign(this, config);

  this.winner = false;

  this.content = [];
  this.virtualBoard = [];
  this.buildGameBoard();

  this.currentMove = {};
  console.log(this.doMoves())
}

// ===================== Actions: =====================

ConnectFour.prototype.doMoves = function() {
  var result = 'Draw!';
  var moveCount = 0;
  for (var i in this.moves) {
    if (this.winner === false) {
      moveCount = this.doMove(this.moves[i], i);
    }
    if (this.winner !== false && this.winner < 3) {
      result = 'Player ' + this.winner + ' won! ' + (Number(moveCount) + 1) + ' pieces played.';
      break;
    }
  }
  this.logBoard();
  return result
}


ConnectFour.prototype.doMove = function(col, moveCount) {
	// Param current move, useful for catching illegal moves	
  this.currentMove = false;

  // Verify col is in range before attempting loop
	if(col > this.cols || col < 0){
  	return false;
  }
  
  
  
	// Use even vs odd move count to determine player 
  var player = moveCount % 2 ? 2 : 1;
  //Count backwards down row count to find the next possible move.
  for (var i = this.rows - 1; i > 1; i--) {
    if (this.virtualBoard[i][col] === false) {
      this.virtualBoard[i][col] = player;
      this.currentMove = {row: i, col: col, player: player
      };
      this.renderMove();
      //break out of the loop, move was found
      break;
    } else {
      //this square is occupied, move up another row
      continue;
    }
  }
  //check winCondition (Note, win is only possible after 7 moves)
  if (moveCount >= 6) {
    this.checkWinCondition();
  }
  return moveCount;
}

ConnectFour.prototype.checkWinCondition = function() {
  if (this.currentMove.row <= (this.rows - 4)) {
    //Vertical win is only possible when row > 4 deep.
    if (this.checkVertical()) {
      return true;
    }
  }
...