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.
<body>
<div id="root"></div>
</body>
html {
box-sizing: border-box;
}
html * {
box-sizing: inherit;
}
body {
background-color: grey;
}
#root {
display: inline-block;
}
.main {
position: relative;
min-width: 300px;
margin: 0 auto;
border-radius: 10px;
border: solid silver;
display: grid;
grid: "info info"
"options board";
grid-auto-columns: min-content;
background-color: black;
}
.info {
position: relative;
color: greenyellow;
grid-area: info;
min-height: 50px;
min-width: 400px;
}
.board {
box-sizing: content-box;
position: relative;
border: solid green;
border-radius: 5px;
align-self: center;
grid-area: board;
display: flex;
flex-wrap: wrap;
min-height: 10px;
}
.filling {
cursor: url("https://github.com/DavidKrpt/react-game-of-life/blob/master/src/images/pencil2.png?raw=true"), pointer
}
.erasing {
cursor: url("https://github.com/DavidKrpt/react-game-of-life/blob/master/src/images/eraser2.png?raw=true"), pointer
}
.controls {
color: greenyellow;
align-self: start;
width: 200px;
grid-area: options;
flex-basis: 200px;
background-color: black;
border: solid green;
}
.info__heading {
max-width: 1000px;
font-size: 30px
}
.heading {
text-align: center;
}
.info__body {
font-size: 20px;
display: flex;
max-width: 1000px;
justify-content: space-around;
}
.controls__buttons {
display: flex;
height: 150px;
padding: 0 20px;
flex-direction: column;
justify-content: space-evenly;
box-shadow: none;
}
.button {
border-radius: 7px;
font-size: 20px;
height: 40px;
font-weight: bold;
border: none;
box-shadow: 2px 2px green;
cursor: pointer;
}
.message {
color: lime;
background-color: #071305;
position: absolute;
max-width: 600px;
max-height: 100px;
left: 205px;
top: 147px;
transition-duration: 500ms;
border-right: dotted lime;
border-bottom: dotted lime;
}
.message_fading {
opacity: 0;
}
.message_hidden {
visibility: hidden;
}
.options {
display: flex;
flex-direction: column;
height: 300px;
justify-content: space-evenly;
}
.stats__value {
display: inline-block;
font-family: monospace;
font-weight: bold;
width: 100px;
}
.option {
margin-left: 10%;
}
.option__label {
display: block;
font-size: 20px;
}
.option__input {
width: 80%;
height: 30px;
font-size: 25px;
}
.help__item {
cursor: pointer;
}
.tool {
font-size: 20px;
margin-left: 20px;
}
.square {
box-sizing: border-box;
border-top: solid 1px green;
border-left: solid 1px green;
}
.square_type-life {
background-color: lime;
}
.square_type-death {
background-color: #071305;
}
.link:visited {
color: green;
}
class App extends React.Component {
constructor() {
super();
this.state = {
rows: 30,
cols: 30,
squareSize: 20,
squares: makeFalsyArray(30, 30),
intervalId: null,
genNumber: 1,
deathCount: 0,
tool: "filler",
message: {
text: null, //2 timeouts for smooth messages
timer1: null, //set opacity to 0
timer2: null //remove from the DOM
}
};
this.isDown = false;
}
displayMessage = (text, timer) => {
const delay = this.hideMessage() ? 500 : 0; //remove previous message
setTimeout(() => {
this.setState({
message: {
text: text,
timer1: setTimeout(this.hideMessage, timer),
timer2: null
}
});
}, delay);
};
hideMessage = () => {
if (this.state.message.text) {
clearTimeout(this.state.message.timer1);
this.setState({
message: {
text: this.state.message.text,
timer1: null,
timer2: setTimeout(
() =>
this.setState({
message: { text: null, timer1: null, timer2: null }
}),
500
)
}
});
return true;
}
};
handleSizeChange = event => {
const newSize = validateNumber(event.target.value) || 1;
this.setState({
squareSize: newSize
});
};
handleHelpClick = () => {
const text = `Click and drag or hit randomize to populate the board and press play.
Bright green color represents live cells. If a cell has more than 3 or
less than 2 neighbours it dies. If a dead cell has exactly 3 live
neighbours, it becomes alive.`;
if ((this.state.message.text === text)) return this.hideMessage();
return this.displayMessage(text, 10000);
};
handleRowChange = event => {
const rows = validateNumber(event.target.value) || 1;
const newSquares = makeFalsyArray(rows, this.state.cols);
this.handleReset();
this.setState({
rows: rows,
squares: newSquares
});
};
handleColChange = event => {
const cols = validateNumber(event.target.value) || 1;
const newSquares = makeFalsyArray(this.state.rows, cols);
this.handleReset();
this.setState({
cols: cols,
squares: newSquares
});
};
handleReset = () => {
const { rows, cols } = this.state;
const newSquares = makeFalsyArray(rows, cols);
clearInterval(this.state.intervalId);
this.setState({
squares: newSquares,
genNumber: 1,
deathCount: 0,
intervalId: null
});
};
handleToolChange = (event) => {
this.setState({
tool: event.target.value
})
}
handleMouseMove = (i, j) => {
if (!this.isDown) return;
if ((this.state.squares[i][j] && this.state.tool === "filler")||
(!this.state.squares[i][j] && this.state.tool === "eraser")) return;
const squares = copyArray(this.state.squares);
squares[i][j] = this.state.tool ==="filler";
this.setState({
squares: squares
});
};
handleClick = (i,j) => {
this.isDown = true;
this.handleMouseMove(i,j);
this.isDown = false
}
handleStartPause = () => {
let intervalId;
if (this.state.intervalId) {
clearInterval(this.state.intervalId);
intervalId = null;
} else {
if (arrIsFalsy(this.state.squares))
return this.displayMessage(
"There are no live cells, try randomizing or drawing some",
2000
);
intervalId = setInterval(this.makeNextGeneration, 100);
}
this.setState({
intervalId: intervalId
});
};
handleRandomize = () => {
const randomSquares = [];
randomSquares.length = this.state.rows;
for (let i = 0; i < this.state.squares.length; i++) {
randomSquares[i] = [];
randomSquares[i].length = this.state.cols;
for (let j = 0; j < this.state.squares[0].length; j++) {
randomSquares[i][j] = Math.random() > 0.7;
}
}
this.setState({
squares: randomSquares
});
};
handleMouseDown = () => {
this.isDown = true;
};
handleMouseUp = () => {
this.isDown = false;
};
makeNextGeneration = () => {
const currentSquares = this.state.squares;
if (
currentSquares.filter(
row => row.filter(square => square === true).length > 0
).length === 0
) {
this.displayMessage("Everyone died on day " + this.state.genNumber, 2000);
return this.handleStartPause();
}
const nextSquares = makeFalsyArray(this.state.rows, this.state.cols);
let deathCount = this.state.deathCount;
for (let i = 0; i < currentSquares.length; i++) {
for (let j = 0; j < currentSquares[i].length; j++) {
let neighbourNum = currentSquares[i][j] ? -1 : 0;
for (let m = i - 1; m <= i + 1; m++) {
if (m >= 0 && m < currentSquares.length) {
for (let n = j - 1; n <= j + 1; n++) {
if (n >= 0 && n < currentSquares[i].length) {
if (currentSquares[m][n]) {
neighbourNum++;
}
}
}
}
}
if (currentSquares[i][j]) {
if (neighbourNum > 1 && neighbourNum < 4) {
nextSquares[i][j] = true;
} else {
deathCount++;
}
} else if (neighbourNum === 3) {
nextSquares[i][j] = true;
}
}
}
this.setState({
squares: nextSquares,
genNumber: this.state.genNumber + 1,
deathCount: deathCount
});
};
render() {
return (
<main className="main">
<Info
onHelpClick={this.handleHelpClick}
genNumber={this.state.genNumber}
deathCount={this.state.deathCount}
/>
<Controls
rows={this.state.rows}
cols={this.state.cols}
intervalId={this.state.intervalId}
squareSize={this.state.squareSize}
tool = {this.state.tool}
onStartPause={this.handleStartPause}
onRandomize={this.handleRandomize}
onReset={this.handleReset}
onRowChange={this.handleRowChange}
onColChange={this.handleColChange}
onSizeChange={this.handleSizeChange}
onToolChange = {this.handleToolChange}
/>
<Board
tool = {this.state.tool}
squareSize={this.state.squareSize}
squares={this.state.squares}
onMouseUp={this.handleMouseUp}
onMouseMove={this.handleMouseMove}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
/>
<Message message={this.state.message} />
</main>
);
}
}
function copyArray(array) {
//deep copy array of arrays
const copy = [];
const [rows, cols] = [array.length, array[0].length];
copy.length = rows;
for (let i = 0; i < rows; i++) {
copy[i] = [];
copy[i].length = cols;
for (let j = 0; j < cols; j++) {
copy[i][j] = array[i][j];
}
}
return copy;
}
function validateNumber(num) { // 101>num>0
if (!Number(num)) return false;
num = Math.round(Number(num));
return Math.max(Math.min(Number(num), 100), 1);
}
function arrIsFalsy(arr) {
//checks if there are no true values in nested arrays
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i][j]) return false;
}
}
return true;
}
function makeFalsyArray(rows, cols) {
//nested arrays of false values
const arr = [];
arr.length = rows;
for (let i = 0; i < rows; i++) {
arr[i] = [];
arr[i].length = cols;
for (let j = 0; j < cols; j++) {
arr[i][j] = false;
}
}
return arr;
}
const Board = props => {
const squares = props.squares;
const [rows, cols] = [squares.length, squares[0].length];
const squareElements = Array(rows * cols);
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const className =
"square square_type-" + (squares[i][j] ? "life" : "death");
squareElements[i * cols + j] = (
<div
key={"square" + i + "-" + j}
className={className}
style={{ width: props.squareSize, height: props.squareSize }}
onMouseMove={() => props.onMouseMove(i, j)}
onClick={() => props.onClick(i, j)}
/>
);
}
}
return (
<div
className={"board " + (props.tool === "eraser" ? "erasing" : "filling")}
style={{ width: props.squares[0].length * props.squareSize + "px" }}
onMouseDown={event => {
event.preventDefault();
return props.onMouseDown();
}}
onMouseUp={props.onMouseUp}
onMouseLeave={props.onMouseUp}
>
{squareElements}
</div>
);
};
const Buttons = props => {
return (
<div className="controls__buttons">
<button className="button" onClick={props.onStartPause}>
{props.playOrPause}
</button>
<button className="button" onClick={props.onRandomize}>Randomize</button>
<button className="button" onClick={props.onReset}>Reset</button>
</div>
);
};
const Controls = props => {
return (
<section className="controls">
<Buttons
playOrPause = {props.intervalId ? "Pause" : "Play"}
onStartPause={props.onStartPause}
onRandomize={props.onRandomize}
onReset = {props.onReset}
/>
<Options
rows = {props.rows}
cols = {props.cols}
squareSize = {props.squareSize}
onRowChange={props.onRowChange}
onColChange={props.onColChange}
onSizeChange={props.onSizeChange}
/>
<Tools tool = {props.tool} onToolChange = {props.onToolChange} />
</section>
);
};
const Info = props => {
return (
<section className="info">
<h1 className="heading info__heading">Conway's Game Of Life</h1>
<div className="info__body">
<div className="info__section stats">
<div className="stats__label">
Day: <span className="stats__value">{props.genNumber}</span>{" "}
</div>
<div className="stats__label">
Death count:{" "}
<div className="stats__value">{props.deathCount}</div>{" "}
</div>
</div>
<div className="info__section help">
<span onClick={props.onHelpClick} className="help__item rules">
Help
</span>
<div className="help__item more">
<a
className="link"
target="_blank"
href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life"
>
More Info (Wikiedia)
</a>
</div>
</div>
</div>
</section>
);
};
const Message = props => {
let className = "";
console.log(props.message)
if (!props.message.timer1) {
if (!props.message.timer2) className = " message_hidden"
className = " message_fading"
}
return (
<div className={"message" + className}>
{props.message.text}
</div>
);
};
const Options = props => {
return (
<section className="options">
<h2 className="heading options__heading">Options</h2>
<div className="option">
<label className="option__label" htmlFor="rowNum">
Rows
</label>
<input
className="option__input"
id="rowNum"
type="number"
name="rows"
min="1"
max="100"
value={props.rows}
onChange={props.onRowChange}
/>
</div>
<div className="option">
<label className="option__label" htmlFor="colNum">
Columns
</label>
<input
className="option__input"
id="colNum"
type="number"
name="cols"
min="1"
max="100"
value={props.cols}
onChange={props.onColChange}
/>
</div>
<div className="option">
<label className="option__label" htmlFor="squareSize">
Cell size (px)
</label>
<input
className="option__input"
id="squareSize"
type="number"
name="size"
min="1"
value={props.squareSize}
onChange={props.onSizeChange}
/>
</div>
</section>
);
};
const Tools = props => {
return (
<div className="tools">
<h2 className="heading options__heading">Tools</h2>
<div className="tool">
<div className="tool__option">
<input
id="filler"
type="radio"
name="tool"
value="filler"
checked={props.tool==="filler"}
onChange={props.onToolChange}
/>
<label htmlFor="filler">Filler</label>
</div>
<div className="tool__option">
<input
id="eraser"
type="radio"
name="tool"
value="eraser"
checked={props.tool==="eraser"}
onChange={props.onToolChange}
/>
<label htmlFor="eraser">Eraser</label>
</div>
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"))
Also see: Tab Triggers