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 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.
<div id="errors" style="
background: #c00;
color: #fff;
display: none;
margin: -20px -20px 20px;
padding: 20px;
white-space: pre-wrap;
"></div>
<div id="root"></div>
<script>
window.addEventListener('mousedown', function(e) {
document.body.classList.add('mouse-navigation');
document.body.classList.remove('kbd-navigation');
});
window.addEventListener('keydown', function(e) {
if (e.keyCode === 9) {
document.body.classList.add('kbd-navigation');
document.body.classList.remove('mouse-navigation');
}
});
window.addEventListener('click', function(e) {
if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
e.preventDefault();
}
});
window.onerror = function(message, source, line, col, error) {
var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
errors.textContent += text + '\n';
errors.style.display = '';
};
console.error = (function(old) {
return function error() {
errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
errors.style.display = '';
old.apply(this, arguments);
}
})(console.error);
</script>
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
function Square({ value, onClick, backgroundColor }) {
return (
<button
className="square"
onClick={onClick}
style={{backgroundColor}}>
{value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
const isWinningIndex = this.props.winningIndex && this.props.winningIndex.indexOf(i) !== -1
return (
<Square
key={`button-${i}`}
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
backgroundColor={isWinningIndex && "deepskyblue"}
/>
);
}
render() {
// 3. 사각형들을 만들 때 하드코딩 대신에 두 개의 반복문을 사용하도록 Board를 다시 작성해주세요.
const boardRows = [];
for(let i = 0, len = Math.sqrt(this.props.squares.length); i < len; i++) {
const innerCols = [];
for(let j = 0; j < len; j++) {
innerCols.push(this.renderSquare((i * len) + j));
}
boardRows.push(
<div className="board-row" key={`row-${i}`}>
{innerCols}
</div>
);
}
return (
<div>
{boardRows}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
currentSquareIndex: null, // question 1
}],
stepNumber: 0,
xIsNext: true,
isDisplayOrderByAsc: true, // question 4
}
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
// square 배열의 복사본 생성 (불변성)
const squares = current.squares.slice();
if(calculateWinner(squares) || squares[i]) {
return
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares,
currentSquareIndex: i
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
// 1. 이동 기록 목록에서 특정 형식(행, 열)으로 각 이동의 위치를 표시해주세요.
const { x, y } = getCoordBySquareIndex(step.currentSquareIndex); // 1
const desc = move ?
`Go to move #${move} - (${x}, ${y})` :
'Go to game start';
// *2. 이동 목록에서 현재 선택된 아이템을 굵게 표시해주세요.
return (
<li key={move}>
<button
onClick={() => this.jumpTo(move)}
style={ {"fontWeight": (this.state.stepNumber === move ? "bold" : "normal")} }>
{desc}
</button>
</li>
);
});
if(!this.state.isDisplayOrderByAsc) {
moves.reverse()
}
// 4. 오름차순이나 내림차순으로 이동을 정렬하도록 토글버튼을 추가해주세요.
const toggleMoves = () => {
this.setState({
isDisplayOrderByAsc: !this.state.isDisplayOrderByAsc
})
}
let status;
let winningIndex; // 이기게 된 원인이 된 스퀘어 번호들
// null 아니고 O, X 인 경우
// 6. 승자가 없는 경우 무승부라는 메시지를 표시해주세요.
if (winner) {
status = `Winner: ${winner.player}`;
// 5. 승자가 정해지면 승부의 원인이 된 세 개의 사각형을 강조해주세요.
winningIndex = winner.winningIndex
} else if (this.state.stepNumber !== current.squares.length) {
status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`
} else {
status = "Draw game!"
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
winningIndex={winningIndex}
/>
</div>
<div className="game-info">
<div>{status}</div>
<div>
<button onClick={toggleMoves}>
{this.state.isDisplayOrderByAsc ? "오름차순 ▲" : "내림차순 ▼"}
</button>
</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
// 한 라인이 O , X 일치하는 경우
if (squares[a] &&
squares[a] === squares[b] &&
squares[a] === squares[c]) {
return {
player: squares[a],
winningIndex: [a, b, c]
};
}
}
return null;
}
// 문제 1
function getCoordBySquareIndex(i) {
return {
x: Math.floor(i / 3),
y: i % 3,
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
Also see: Tab Triggers