// ===================== 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;
}
}
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.