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 URLs 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 its URL and the proper URL extension.
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 esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM 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.
<head>
<link href='https://fonts.googleapis.com/css?family=Arimo|Montserrat' rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div id='selection'>
Play as:
<button class='hover'>X</button>
<button class='hover'>O</button>
</div>
<div id='result'>
</div>
<table>
<tr id='row0' class='row'>
<td id='00' class='spot'> </td>
<td id='01' class='spot'> </td>
<td id='02' class='spot'> </td>
</tr>
<tr id='row1' class='row'>
<td id='10' class='spot'> </td>
<td id='11' class='spot'> </td>
<td id='12' class='spot'> </td>
</tr>
<tr id='row2' class='row'>
<td id='20' class='spot'> </td>
<td id='21' class='spot'> </td>
<td id='22' class='spot'> </td>
</tr>
</table>
</body>
body {
background-color: #E0E4CC;
font-family: 'Montserrat', sans-serif;
margin: 0;
padding: 0;
text-align: center;
}
h1 {
font-size: 3em;
}
table {
width: 75%;
margin: auto;
margin-top: 20px;
font-family: 'Arimo', sans-serif;
font-size: 70px;
}
td {
display: inline-block;
width: 80px;
height: 80px;
line-height: 80px;
background-color: #69D2E7;
color: white;
border: none;
border-radius: 10%;
box-shadow: 0 .03em .08em rgba(0,0,0, 0.5);
margin: 8px;
transition: background-color 0.2s ease;
}
td:hover {
cursor: pointer;
background-color: #FA6900;
}
.selected {
background-color: #FA6900;
}
tr {
list-style-type: none;
width: 500px;
}
#selection {
height: 60px;
font-size: 1.5em;
}
button {
border: none;
background: transparent;
width: 50px;
height: 50px;
margin: .3em;
border-radius: 50%;
}
.hover:hover {
background: #F38630;
color: white;
}
:active {
outline: none;
}
:focus {
outline: none;
}
.seed {
background: #F38630;
color: white;
}
#result {
padding-top: 20px;
height: 40px;
font-size: 1.5em;
}
@media only screen and (min-device-width: 1000px) {
td {
width: 120px;
height: 120px;
line-height: 120px;
font-size: 120px;
}
}
var theboard = new Board();
var ai = new AI('O');
var selected, opponent;
$(document).ready(function(){
$('button').click(function(){
$(this).addClass('seed');
selected = $(this).text();
opponent = selected === 'X' ? 'O' : 'X';
ai = new AI('X');
$('button').attr('disabled', 'true').removeClass('hover');
if(opponent === 'X') {
//Make the computer's move
var move = ai.getBestMove(theboard);
var moveStr = move.join('');
$('#'+moveStr).text('X').addClass('selected').unbind( "click" );
theboard.makeMove('X', move);
}
//Handles clicking on a spot, only active after selecting which piece to play
$('.spot').click(handleClicks);
});
});
function handleClicks() {
if($('#result').text())
$('#result').empty();
//Make the players move.
$(this).text(selected);
$(this).addClass('selected').unbind( "click" );
var spotid = $(this).attr('id');
spotid = spotid.split('');
theboard.makeMove(selected, [spotid[0], spotid[1]]);
//Ensure that it is not time for gameOver
var winner = theboard.checkForWin();
if(winner || theboard.isFull())
gameOver(winner);
else {
//Make the computer's move
var move = ai.getBestMove(theboard);
console.log(move);
var moveStr = move.join('');
$('#'+moveStr).text(opponent).addClass('selected').unbind( "click" );
theboard.makeMove(opponent, move);
//Check again for game over.
winner = theboard.checkForWin();
if(winner || theboard.isFull())
gameOver(winner);
}
}
function gameOver(winner) {
//Notify the player of the status
if(winner)
$('#result').text(winner +' won the game!');
else
$('#result').text('The game was a draw!');
//Wait a second to show the move, then reset
setTimeout(function(){
//Reset the game
$('table').empty();
$('table').append("<tr id='row0' class='row'><td id='00' class='spot'> </td><td id='01' class='spot'> </td><td id='02' class='spot'> </td></tr><tr id='row1' class='row'><td id='10' class='spot'> </td><td id='11' class='spot'> </td><td id='12' class='spot'> </td></tr><tr id='row2' class='row'><td id='20' class='spot'> </td><td id='21' class='spot'> </td><td id='22' class='spot'> </td></tr>");
theboard = new Board();
$('.spot').click(handleClicks);
if(opponent === 'X') {
//Make the computer's move
var move = ai.getBestMove(theboard);
var moveStr = move.join('');
$('#'+moveStr).text(opponent).addClass('selected').unbind( "click" );
theboard.makeMove(opponent, move);
}
}, 1000);
}
//Implementation of the game AI
function AI(seed) {
this.marker = seed;
this.opponent = seed == 'X' ? 'O' : 'X';
this.max = 10;
this.min = -10;
this.minimax = function(board, player) {
var bestScore = -10,
currScore = 0,
moves = board.getAvailableMoves();
//Base case for finding leaf nodes
if(board.turnCnt >= 9 || board.checkForWin() || !moves)
return this.evaluate(board);
//Maximize
if(player === this.marker) {
bestScore = this.min;
for(var move in moves) {
var newBoard = board.clone();
newBoard.makeMove(this.marker, moves[move]);
currScore = this.minimax(newBoard, this.opponent);
if(currScore > bestScore) {
bestScore = currScore;
}
}
return bestScore;
}
//Minimize
if(player === this.opponent) {
bestScore = this.max;
for(var move in moves) {
var newBoard = board.clone();
newBoard.makeMove(this.opponent, moves[move]);
currScore = this.minimax(newBoard, this.marker);
if(currScore < bestScore) {
bestScore = currScore;
}
}
return bestScore;
}
};
//Gets the best move for this board configuration
this.getBestMove = function(board) {
var bestScore = this.min;
var currScore;
var bestMove = null;
var moves = board.getAvailableMoves();
var corners = [[0, 0], [0, 2], [2, 0], [2, 2]];
//Prunes a few options for the first few states
if(board.turnCnt === 0)
return [1, 1];
else if(board.turnCnt === 1 && board.gamestate[1][1] === '')
return [1, 1];
else if(board.turnCnt === 1)
return corners[Math.floor(Math.random() * 4)];
for(var move in moves) {
var newBoard = board.clone();
newBoard.makeMove(this.marker, moves[move]);
currScore = this.minimax(newBoard, this.opponent);
console.log('Current score: ' + currScore);
console.log('Current move: ' + moves[move]);
if(currScore > bestScore) {
bestScore = currScore;
bestMove = moves[move];
}
}
return bestMove;
};
//Evaluates the score for the board passed by checking each line
this.evaluate = function(board) {
var score = 0;
score += this.evaluateLine(board, 0, 0, 0, 1, 0, 2); // row 0
score += this.evaluateLine(board, 1, 0, 1, 1, 1, 2); // row 1
score += this.evaluateLine(board, 2, 0, 2, 1, 2, 2); // row 2
score += this.evaluateLine(board, 0, 0, 1, 0, 2, 0); // col 0
score += this.evaluateLine(board, 0, 1, 1, 1, 2, 1); // col 1
score += this.evaluateLine(board, 0, 2, 1, 2, 2, 2); // col 2
score += this.evaluateLine(board, 0, 0, 1, 1, 2, 2); // diagonal
score += this.evaluateLine(board, 0, 2, 1, 1, 2, 0); // alternate diagonal
return score;
};
//Scores the line by checking each cell for our marker, 1 point for 1, 10 point for 2, 100 for 3, opposite for opponent marker
this.evaluateLine = function(board, r1, c1, r2, c2, r3, c3) {
var score = 0;
//First cell
if(board.gamestate[r1][c1] === this.marker)
score = 1;
else if(board.gamestate[r1][c1] === this.opponent)
score = -1;
//Second cell
if(board.gamestate[r2][c2] === this.marker){
if(score == 1) //Cell 1 was my marker
score = 10;
else if (score === -1) // Cell 1 was my opponent
return 0;
else //Cell 1 was empty
score = 1;
}
else if(board.gamestate[r2][c2] === this.opponent){
if(score == -1) //Cell 1 was opponent
score = -10;
else if (score === 1) // Cell 1 was my marker
return 0;
else //Cell 1 was empty
score = -1;
}
//Final cell
if(board.gamestate[r3][c3] === this.marker){
if(score > 1) //Cell 1 and or 2 was my marker
score *= 10;
else if (score < 0) // Cell 1 and or 2 was my opponent
return 0;
else //Cell 1 and 2 are empty
score = 1;
}
else if(board.gamestate[r3][c3] === this.opponent){
if(score < 0) //Cell 1 and or 2 was my opponent
score *= 10;
else if (score > 1) // Cell 1 and or 2 was my marker
return 0;
else //Cell 1 and 2 are empty
score = -1;
}
return score;
};
}
//Implementation of the board object
function Board() {
this.turnCnt = 0;
this.gamestate = [['','',''],
['','',''],
['','','']];
//Returns the open positions on the board as an array of points as [row, column] or [y, x]
this.getAvailableMoves = function() {
var moves = [];
for(var row in this.gamestate)
for(var col in this.gamestate[row])
if(this.gamestate[row][col] === '')
moves.push([row, col]);
return moves;
};
this.clone = function() {
var newBoard = new Board();
//Copy over the positions of X's and O's and the turn number to the cloned board
for(var row = 0; row < 3; row++)
for(var col = 0; col < 3; col++)
newBoard.gamestate[row][col] = this.gamestate[row][col];
newBoard.turnCnt = this.turnCnt;
return newBoard;
};
//Will take in the player making the move as well as an [y, x] array of where to place the player's marker
this.makeMove = function(player, point) {
var row = parseInt(point[0]);
var col = parseInt(point[1]);
this.gamestate[row][col] = player;
this.turnCnt++;
};
this.isFull = function() {
return this.turnCnt === 9;
};
this.checkForWin = function() {
var boardState = this.gamestate;
var winner;
//checking the diagonals
if(boardState[1][1] !== '' &&
((boardState[0][0] === boardState[1][1]
&& boardState[2][2] === boardState[1][1])
|| (boardState[0][2] === boardState[1][1]
&& boardState[2][0] === boardState[1][1]))) {
winner = boardState[1][1];
return winner;
}
else {
//Checking the horizontals
for(var row in boardState) {
if(boardState[row][0] !== '' &&
boardState[row][0] === boardState[row][1]
&& boardState[row][2] === boardState[row][1]) {
winner = boardState[row][0];
return winner;
}
}
//Verticals
for(var col in boardState) {
if(boardState[0][col] !== '' &&
boardState[0][col] === boardState[1][col]
&& boardState[1][col] === boardState[2][col]) {
winner = boardState[0][col];
return winner;
}
}
}
};
}
Also see: Tab Triggers