JavaScript preprocessors can help make authoring JavaScript easier and more convenient. For instance, CoffeeScript can help prevent easy-to-make mistakes and offer a cleaner syntax and Babel can bring ECMAScript 6 features to browsers that only support ECMAScript 5.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
HTML Settings
Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog" role="document">
<div class="modal-content text-center">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Choose your symbol</h4>
</div>
<button type="button" class="btn btn-info" data-dismiss="modal" id="buttonX">X</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="button0">O</button>
</div>
</div>
</div>
<!-- End of the modal -->
<div class="container-fluid">
<div class="row">
<div class="col-xs-3 square" id="b0"></div>
<div class="col-xs-3 square" id="b1"></div>
<div class="col-xs-3 square" id="b2"></div>
</div>
<div class="row">
<div class="col-xs-3 square" id="b3"></div>
<div class="col-xs-3 square" id="b4"></div>
<div class="col-xs-3 square" id="b5"></div>
</div>
<div class="row text-center">
<div class="col-xs-3 square" id="b6"></div>
<div class="col-xs-3 square" id="b7"></div>
<div class="col-xs-3 square" id="b8"></div>
</div>
<div class="row text-center"><br>
<div class="winner text-center"></div><br>
<button type="button" class="btn btn-primary" id="reset">Let me try it again !</button>
</div><br>
</div>
<link href='https://fonts.googleapis.com/css?family=Corben:700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Sigmar+One' rel='stylesheet' type='text/css'>
body {
background: #1F282B;
width: 100%;
heigth: 100%;
}
#button1,
#button0 {
margin: 20px 0 20px 0;
}
.modal-dialog {
/* Choice box*/
margin: auto;
margin-top: 20vh;
width: 250px;
}
.col-xs-3 {
background: #1CD46B;
max-width: 150px;
width: 25vw;
min-height: 100px;
margin-left: 3vw;
margin-top: 3vh;
border-radius: 10px;
cursor: pointer;
text-align: center;
font-family: 'Corben', cursive;
}
.row {
margin: auto;
max-width: 600px;
width: 90vw;
}
.winner {
margin: auto;
max-width: 300px;
width: 50vw;
border-radius: 20px;
font-size: 20px;
background-color: #F01823;
color: white;
font-family: 'Sigmar One', cursive;
}
.userClicked {
background: #34C2AF;
}
.aiClicked {
background: #EB5454;
}
$(document).ready(function() {
clearBoard();
});
$('#myModal').modal('show'); // Show choices when page loads
$('#reset').hide();
var userSign, aiSign;
var movesSign = []; // Keep track of the sign of the moves made
function clearBoard() {
for (var i = 0; i < 9; i++) {
movesSign[i] = "";
$("#b" + i).text("");
}
$(".square").removeClass("clicked"); // Make boxes clickable again
$(".square").removeClass("aiClicked"); // Remove the red background from AI clicked boxes
$(".square").removeClass("userClicked"); // Remove the blue background from user clicked boxes
$(".winner").text("");
}
//Assign signs according to user's choice
$("#button0").on("click", function() {
userSign = "O";
aiSign = "X";
});
$("#buttonX").on("click", function() {
userSign = "X";
aiSign = "O";
});
//When there is a click on the board
$(".square").on("click", function() {
var position = parseInt($(this).attr("id")[1]);
userTurn(position);
});
//When the user clicks on the board
function userTurn(pos) {
if ($("#b" + pos).hasClass("clicked")) { // Square is filled
//do nothing
} else {
if (!boardFull(movesSign) && !score(movesSign)) {
takeTurn(pos, userSign); //Make the user's move
$("#b" + pos).addClass("userClicked"); // Add blue background to user clicked boxes
if(!boardFull(movesSign)){
aiTurn(); //Switch to AI to take it's turn
}
}
}
};
//AI's turn to make a move
function aiTurn() {
var move = miniMax(movesSign, aiSign)[1];
takeTurn(move, aiSign);
$("#b" + move).addClass("aiClicked"); // Add red background to AI clicked boxes
};
//Add the X or O on the board
function takeTurn(position, sign) {
movesSign[position] = sign;
$("#b" + position).append("<h1>" + sign + "</h1>");
$("#b" + position).addClass("clicked");
if (gameOver(movesSign, sign)) { // Check if the game is over
if (sign == aiSign)
$(".winner").append("<p>Guess you're not that smart !</p>"); // AI wins
else
$(".winner").append("<p>You Win</p>"); // Never gonna happen
setTimeout(function() {
$('#reset').trigger('click');
}, 2000);
} else if (boardFull(movesSign)) { // Show draw game message
$(".winner").append("<p>Draw Game!</p>");
setTimeout(function() {
$('#reset').trigger('click');
}, 2000);
}
};
//Minimax algorithm
function miniMax(board, sign, pos) {
var scoreGame = score(board); // Score board for every recursion
if (boardFull(board) || scoreGame) { // If the game has been scored or the board is full, exit
return [scoreGame, pos]; // Return score and the positon
}
var multi = sign === aiSign ? 1 : -1; // AI will look for the best score and user for the worst
var moves = possibleMoves(board); // Find out the free boxes for every recursion
var bestScore = -100;
var positions = [pos];
var thisScore;
var oppSign = sign === "O" ? "X" : "O"; // Opponent's sign
while (moves.length > 0) {
var newPosition = moves.pop(); // Pop the last number from the array of possible moves
var newBoard = board.slice(); // Make a copy of the current board
newBoard[newPosition] = sign; // Push the the new sign to the new board. Sign changes with every recrusion
var result = miniMax(newBoard, oppSign, newPosition); // Recursively call the function with new board and position
thisScore = multi * result[0]; // "thisScore" will be +ve for AI and -ve for user
// Choose the best possible move
if (thisScore === bestScore) {
positions.push(newPosition);
} else if (thisScore > bestScore) {
bestScore = thisScore;
positions = [newPosition];
}
}
// Choose a move at random from the best moves
var randomMove = Math.floor(Math.random() * positions.length);
return [multi * bestScore, positions[randomMove]];
};
// Score the game with every turn
function score(board) {
var emptyBox = board.filter(function(square) { // Returns array for element returning true for the condition
return square === "";
}).length;
if (win(board, aiSign)) {
return 10 + emptyBox; // AI wins the move
} else if (win(board, userSign)) {
return -10 - emptyBox; // User wins the move
} else {
return 0; // Draw
}
};
// Get the number of free squares available
function possibleMoves(board) { // For the arguement "board", check if it has free spaces
var freeMoves = [];
for (var i = 0; i < 9; i++) {
if (board[i] === "") {
freeMoves.push(i);
}
}
return freeMoves;
};
// Check whether the game is over or not
function gameOver(board, winSign) {
if (win(board, winSign)) {
return true;
}
};
// Check if somebody has won the game or not
function win(board, sign) {
var winCombo = [ // Winning combinations
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
return winCombo.some(function(subVal) { // Check the sub arrays
return subVal.every(function(val) { // Check all the elements in the subarrays
return board[val] === sign; // Check the position against the sign stored
});
});
};
// Check if the board has any space left to fill or not
function boardFull(board) {
return !board.some(function(square) {
return square === "";
});
};
//Reset the game. Reloads the page and erases the board
$("#reset").on("click", function() {
clearBoard(); // Erase all the boxes
$('#myModal').modal('show'); // Give the user the choice again
$("#reset").hide();
});
Also see: Tab Triggers