HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URL's added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<link href='https://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>
<div class="container">
<div class="header"></div>
<div class="title">Let's Play Tic Tac Toe!</div>
<div class="instruction">
<span class="switch-text">X plays first, and you will be X.</span>
<span class="switch-link"><a href="#">Play as O instead.</a></span>
</div>
<div class="board-container">
<!--<svg height="300" width="300">
<line x1="0" y1="0" x2="300" y2="300" style="stroke:rgb(0,0,0);stroke-width:10" />
</svg> -->
<div class="row row1">
<div class="cell col1" id="0-0"></div>
<div class="cell col2" id="0-1"></div>
<div class="cell col3" id="0-2"></div>
</div>
<div class="row row2">
<div class="cell col1" id="1-0"></div>
<div class="cell col2" id="1-1"></div>
<div class="cell col3" id="1-2"></div>
</div>
<div class="row row3">
<div class="cell col1" id="2-0"></div>
<div class="cell col2" id="2-1"></div>
<div class="cell col3" id="2-2"></div>
</div>
</div>
<div class="clippy hide">
<img src="https://d13yacurqjgara.cloudfront.net/users/12731/screenshots/193611/clippy_dribbble.png"/>
<div class="clippy-text"></div>
</div>
</div>
* {
bordr: 1px black solid;
}
body {
/*border: 1px black solid; */
font-family: sans-serif;
}
.header {
height: 50px;
}
.title {
font-size: 48pt;
margin: 0 auto;
width: 500px;
font-family: 'Bangers', cursive;
text-align: center;
}
.instruction {
font-size: 18pt;
margin: 0 auto;
width: 300px;
text-align: center;
margin-bottom: 30px;
}
.board-container {
width: 300px;
height: 300px;
margin: 0 auto;
}
.board-container svg {
position: absolute;
}
.row {
display: flex;
width: 100%;
height: 100px;
margin: 0;
}
.cell {
/* background: grey; */
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-size: 80pt;
cursor: pointer;
}
.row1 {
border-bottom: 5px black solid;
}
.row2 {
border-top: 5px black solid;
border-bottom: 5px black solid;
}
.row3 {
border-top: 5px black solid;
}
.col1 {
border-right: 5px black solid;
}
.col2 {
border-right: 5px black solid;
border-left: 5px black solid;
}
.col3 {
border-left: 5px black solid;
}
.messagebox {
font-size: 36pt;
width: 350px;
margin: 0 auto;
margin-top: 50px;
margin-bottom: 30px;
text-align: center;
font-family: 'Bangers', cursive;
}
.clippy {
width: 450px;
height: 100px;
margin: 0 auto;
display: flex;
justify-content: center;
font-size: 16pt;
margin-top: 20px;
}
.clippy img {
border-radius: 50%;
border: 1px black solid;
height: 60px;
width: 60px;
}
.clippy-text {
padding: 0 20px;
}
.highlight {
background-color: yellow;
z-index: -1;
}
.hide {
display: none;
height: 0;
}
.locked {
color: gray;
border-color: gray;
cursor: default;
}
@media (max-width: 540px) {
.header {
height: 30px;
}
.title {
font-size: 24pt;
margin: 0 auto;
width: 300px;
margin-bottom: 10px;
font-family: 'Bangers', cursive;
text-align: center;
}
.instruction {
font-size: 12pt;
margin: 0 auto;
width: 250px;
text-align: center;
margin-bottom: 30px;
}
.board-container {
width: 210px;
height: 210px;
margin: 0 auto;
display: flex;
flex-direction: column;
}
.row {
height: 70px;
border-width: 3pt;
}
.cell {
/* background: grey; */
width: 70px;
height: 70px;
line-height: 65px;
text-align: center;
border-width: 3pt;
font-size: 50pt;
}
.clippy {
width: 300px;
height: 70px;
}
}
var boardModel = (function() {
var board = [[],[],[]];
return {
init: function() {
board = [
["", "", ""],
["", "", ""],
["", "", ""]
];
},
getBoard: function() {
return board;
},
playSlot: function(piece, coords) {
if (!board[coords[0]][coords[1]]) {
board[coords[0]][coords[1]] = piece;
// update view
display(piece, coords);
return true;
}
console.log("space not empty!");
return false;
},
checkWin: function(piece) {
return checkIfWon(piece, board);
},
checkWinOrTie: function() {
// this will return "X","O","T",""
if (this.checkWin("X")) return "X";
else if (this.checkWin("O")) return "O";
else if (noEmptySlots(board)) return "T";
else return "";
}
};
})();
var checkIfWon = function(piece, b) {
// piece is either "X" or "O"
if (piece === "") return false;
var possibleWins = {
1: [[0,0], [0,1], [0,2]],
2: [[1,0], [1,1], [1,2]],
3: [[2,0], [2,1], [2,2]],
4: [[0,0], [1,0], [2,0]],
5: [[0,1], [1,1], [2,1]],
6: [[0,2], [1,2], [2,2]],
7: [[0,0], [1,1], [2,2]],
8: [[0,2], [1,1], [2,0]]
};
for (var el in possibleWins) {
var played = possibleWins[el].filter(function(el_sub){
return (b[el_sub[0]][el_sub[1]] === piece);
});
if (played.length === 3) return true;
}
return false;
}
function oppPiece(piece) {
// return opposite piece
return piece === "X" ? "O" : "X";
}
// player1 and player2 modules.
var humanStrategy = function() {
var moveCount = 0;
var control;
var piece; // who am I, "X" or "O"?
function _clicked(coords) {
control.play(coords);
}
function _yourTurn() {
moveCount++;
if (moveCount > 1) clippy.unhide();
if (moveCount > 2) clippy.advise(piece);
}
function _restart() {
moveCount = 0;
_yourTurn();
}
return {
restart: _restart,
yourTurn: _yourTurn,
clicked: _clicked,
init: function(c, p) {
control = c;
piece = p;
}
};
};
var cpuStrategy = function() {
var control;
var piece; // who am I, X or O?
var _yourTurn = function() {
// use setTimeout to allow DOM to refresh
lockBoard(true);
setTimeout(function() {
bestMove = minimax(boardModel.getBoard(), "", oppPiece(piece), piece, 0);
control.play(bestMove.coords);
lockBoard(false);
},10);
}
var _restart = function() {
_yourTurn();
}
return {
yourTurn: _yourTurn,
restart: _restart,
init: function(c, p) {
control = c;
piece = p;
}
};
};
// *** CLIPPY FUNCTIONS ***
var clippy = (function() {
return {
unhide: function() {
$(".clippy").removeClass("hide");
},
init: function() {
$(".clippy-text").text("Hi I'm Crappy! It looks like you're trying to win this game. Let me help!");
},
advise: function(piece) {
var worstMove = minimax(boardModel.getBoard(), "", oppPiece(piece), piece, 0, "sabotage");
$(".clippy-text").text("Try this space!");
$("#"+worstMove.coords[0]+"-"+worstMove.coords[1]).addClass("highlight");
setTimeout(function() {
$("#"+worstMove.coords[0]+"-"+worstMove.coords[1]).removeClass("highlight");
},500);
}
}
})();
// ** main control state machine **
var controller = function(X, O) {
var state = "";
function privateStartGame() {
boardModel.init();
clearBoard();
if (state === "") {
clippy.init();
}
X.init(this, "X");
O.init(this, "O");
X.restart();
state = "X"; // X always starts first
}
function privatePlay(coords) {
switch (state) {
case "X":
case "O":
// try to update model
var success = boardModel.playSlot(state, coords);
if (success) {
switch (boardModel.checkWinOrTie()) {
case state:
displayWin(state);
state = state + "win";
break;
case "T":
displayTie();
state = "TIE";
break;
default:
state = state === "X" ? "O" : "X";
if (state === "X") X.yourTurn();
else O.yourTurn();
}
}
break;
case "Xwin":
case "Owin":
case "TIE":
(privateStartGame.bind(this))();
break;
default:
console.log("Invalid State");
}
}
return {
startGame: privateStartGame,
play: privatePlay
};
};
// ** display routines **
function display(piece, coords) {
$("#"+coords[0]+"-"+coords[1]).text(piece);
}
function clearBoard() {
$(".cell").text("");
$(".title").text("LET'S PLAY TIC TAC TOE!");
$(".clippy-text").text("...");
}
function lockBoard(lock) {
// lock = true for lock screen, false for unlock
if (lock) {
$(".cell").addClass("locked");
$(".row").addClass("locked");
} else {
$(".cell").removeClass("locked");
$(".row").removeClass("locked");
}
}
function isBoardLocked() {
return $(".cell").hasClass("locked");
}
function displayWin(winner) {
$(".title").text(winner + " WON. TRY AGAIN?");
if (winner === "O") $(".clippy-text").text("Well crap. Sorry!");
else $(".clippy-text").text("You're welcome!");
}
function displayTie() {
$(".title").text("TIE. TRY AGAIN?");
$(".clippy-text").text("Hey a tie is more fun than losing!");
}
function displaySideLink(currentPiece) {
$(".switch-text").text('X plays first, and you will be '+currentPiece+'.');
$(".switch-link a").text('Play as '+oppPiece(currentPiece)+' instead.');
}
// *** MINIMAX ROUTINES ***
var emptySlots = function(b) {
// return a list of empty slots
var result = [];
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (!b[i][j]) result.push({
coords: [i, j],
score: 0
});
}
}
return result;
}
var noEmptySlots = function(b) {
if (emptySlots(b).length === 0) return true;
return false;
}
var score = function(lastPlayer, maxPlayer, won, depth) {
if (!won) return 0;
if (lastPlayer === maxPlayer) return 10 - depth;
return -10 + depth;
}
var returnMin = function(arr) {
var minChild = arr[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i].score < minChild.score) minChild = arr[i];
}
return minChild;
}
var returnMax = function(arr) {
var maxChild = arr[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i].score > maxChild.score) maxChild = arr[i];
}
return maxChild;
}
var copyBoard = function(oldArray) {
return oldArray.map(function(arr) {
return arr.slice();
});
}
var minimax = function(board, move, lastMovePiece, maxPlayer, depth, sabotage) {
// if won or tie, return score
depth++;
var won = checkIfWon(lastMovePiece, board);
if (noEmptySlots(board) || won || depth > 6) {
return {
score: score(lastMovePiece, maxPlayer, won, depth),
coords: move
}
}
// else recurse...
var possibleMoves = emptySlots(board);
var nextMovePiece = (lastMovePiece === "X") ? "O" : "X";
possibleMoves.forEach(function(el) {
var _b = copyBoard(board);
_b[el.coords[0]][el.coords[1]] = nextMovePiece;
el.score = minimax(_b, el.coords, nextMovePiece, maxPlayer, depth, sabotage).score;
});
// then return min or max
sabotage = typeof sabotage !== 'undefined' ? sabotage : false;
if ((nextMovePiece === maxPlayer) && !sabotage) {
return returnMax(possibleMoves);
} else {
return returnMin(possibleMoves);
}
}
// MAIN CODE
// default to human = X. create a new controller and change strategy if switch.
function switchSide(newSide) {
humanIs = newSide;
displaySideLink(newSide);
x = humanIs === "X" ? humanStrategy() : cpuStrategy();
o = humanIs === "O" ? humanStrategy() : cpuStrategy();
tttControl = new controller(x, o);
tttControl.startGame();
}
// start game first time, assign strategies accordingly
var humanIs = "X";
var x = humanIs === "X" ? humanStrategy() : cpuStrategy();
var o = humanIs === "O" ? humanStrategy() : cpuStrategy();
var tttControl = controller(x, o);
tttControl.startGame();
// set up click handlers for human player
$(".cell").click(function() {
if (!isBoardLocked()) {
var $id = $(this).attr("id");
var coords = $id.split("-").map(function(n) {
return Number.parseInt(n);
});
humanIs === "X" ? x.clicked(coords) : o.clicked(coords);
}
});
$(".switch-link a").click(function(e) {
e.preventDefault();
switchSide(oppPiece(humanIs));
});
Also see: Tab Triggers