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 class="container"></div>
$primary-color: #FF5400;
$secondary-color: #FFBF00;
$button-color: #DB4500;
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 16px;
color: #505050;
background: #F8F8F8;
}
h1 {
text-align: center;
font-size: 2em;
font-weight: 500;
}
td {
border: 1px solid #DDD;
height: 1em;
width: 1em;
&:hover:not(.alive):not(.new-born) {
background: #DDD;
}
}
/* Width to match app grid size */
.container {
margin: 1.5em auto;
max-width: 40em;
}
/* Grid styles */
table {
margin: 1em 0;
}
.alive {
background: $primary-color;
}
.new-born {
background: $secondary-color;
}
/* Controls and button styles */
.controls{
float: left;
user-select: none;
}
.button {
display: inline-block;
margin-right: 0.4em;
padding: 0.3em 0.7em;
font-size: 0.9em;
font-weight: 400;
line-height: 1.5em;
background: $button-color;
color: #fff;
cursor: pointer;
&:hover {
background: lighten($button-color, 10%);
}
}
.button-group {
display: inline-block;
.button {
border-right: 1px solid darken($button-color, 5%);
margin-right: 0px;
&:last-child {
border-right: 0
}
}
}
.fa-pause, .fa-play, .fa-step-forward {
width: 1em;
text-align: center;
}
.counter {
float: right;
}
//Game of Life React + Redux Implementation
//You may prefer to view the source here:
//https://github.com/thepeted/game-of-life-redux
//CONSTANTS
const GRID_HEIGHT = 25;
const GRID_WIDTH = 40;
//REACT & REDUX LIBRARIES SET UP
const { Component } = React;
const { createStore, applyMiddleware } = Redux;
const { Provider } = ReactRedux;
const { connect } = ReactRedux;
const { combineReducers } = Redux;
//HELPERS - generate the gamestate by constructing 2d arrays
const makeGrid = (height, width, makeRandom = false) => {
let grid = [];
for (var i = 0; i < height; i++){
var row = [];
for (var j = 0; j < width; j++){
let value;
if (makeRandom){
value = Math.random() > 0.85;
}
row.push({
status: value,
newBorn: value
});
}
grid.push(row);
}
return grid;
};
const advanceGrid = function(grid = []){
let gridHeight = grid.length;
let gridWidth = grid[0].length;
let calculateNeighbours = function(x,y) {
//since the world is toroidal: if the cell is at the edge of the grid we
//will reference the cell on the opposite edge
let topRow = x-1 < 0 ? (gridHeight - 1) : x-1;
let bottomRow = (x+1 === gridHeight) ? 0 : x+1;
let leftColumn = y-1 < 0 ? (gridWidth - 1) : y-1;
let rightColumn = (y+1 === gridWidth) ? 0 : y+1;
let total = 0;
total+= grid[topRow][leftColumn].status;
total+= grid[topRow][y].status;
total+= grid[topRow][rightColumn].status;
total+= grid[x][leftColumn].status;
total+= grid[x][rightColumn].status;
total+= grid[bottomRow][leftColumn].status;
total+= grid[bottomRow][y].status;
total+= grid[bottomRow][rightColumn].status;
return total;
};
//apply the rules of the game by comparing with the existing grid to build
//a new array
let gameState = [];
for (let i = 0; i < gridHeight; i++) {
let row = [];
for (let j = 0; j < gridWidth; j++) {
let cellIsAlive = grid[i][j].status;
let neighbours = calculateNeighbours(i,j);
if (cellIsAlive) {
if (neighbours < 2) {
row.push({ status: 0 });
} else if (neighbours > 3){
row.push({ status: 0 });
} else {
row.push({ status: 1 });
}
}
if (!cellIsAlive) {
if (neighbours === 3) {
row.push({
status: 1,
newBorn: true
});
} else {
row.push({ status: 0 });
}
}
}
gameState.push(row);
}
return gameState;
};
//ACTIONS
function toggleAlive(x,y) {
return {
type: 'TOGGLE_ALIVE',
x,
y
};
}
function makeRandomGrid() {
return {
type: 'MAKE_RANDOM'
};
}
function tick() {
return {
type: 'TICK'
};
}
function startPlaying(timerId) {
return {
type: 'PLAY',
timerId
};
}
function stopPlaying(timerId) {
return {
type: 'STOP',
timerId
};
}
function clear() {
return {
type: 'CLEAR',
};
}
//COMPONENTS - 'dumb' functional components only receive props. They don't need to dispatch actions nor to they care about the overall state of the app
const Button = ({title, icon, handleClick}) => (
<span onClick={handleClick} className="button">
<i className={icon}></i> {title}
</span>
)
const Cell = ({alive, newBorn, handleClick}) => (
<td
onClick={handleClick}
className={`${alive ? 'alive' : ''} ${newBorn ? 'new-born' : ''}`}
>
</td>
)
//CONTAINERS - define a React component and use React-Redux to connect up to the Redux store
class Board_ extends Component {
render(){
return (
<div>
<table>
<tbody>
{this.props.board.map((row,i) =>
<tr key={i}> {row.map((cell,j) =>
<Cell
key={j}
alive={cell.status}
newBorn={cell.newBorn}
handleClick={() => this.props.toggleAlive(i,j)}
/>)}
</tr> )}
</tbody>
</table>
</div>
);
}
}
const mapStateToProps_1 = ({ board }) => {
return { board } ;
}
const mapDispatchToProps_1 = (dispatch) => {
return { toggleAlive: (x,y) => dispatch(toggleAlive(x,y)) }
}
const Board = connect(mapStateToProps_1, mapDispatchToProps_1)(Board_);
//
class Control_ extends Component {
componentDidMount(){
this.props.random();
this.togglePlay();
}
render(){
return (
<div className="controls">
<div className="buttons">
<Button
handleClick={() => this.props.random()}
title={'Randomise'}
icon={'fa fa-random'}
/>
<Button
handleClick={() => this.clear()}
title={'Clear'}
icon={'fa fa-undo'}
/>
<div className="button-group">
<Button
icon={this.props.playState.isRunning ? 'fa fa-pause' : 'fa fa-play' }
handleClick={() => this.togglePlay()}
/>
<Button
handleClick={() => this.props.tick()}
icon={'fa fa-step-forward'}
/>
</div>
</div>
</div>
);
}
togglePlay(){
if (this.props.playState.isRunning) {
clearInterval(this.props.playState.timerId);
this.props.stopPlaying();
} else {
let interval = setInterval(this.props.tick,100);
this.props.startPlaying(interval);
}
}
clear(){
if (this.props.playState.isRunning) {
clearInterval(this.props.playState.timerId);
this.props.stopPlaying();
}
this.props.clear();
}
}
const mapStateToProps_2 = ({playState}) => {
return { playState };
}
const mapDispatchToProps_2 = (dispatch) => {
return {
random: () => dispatch(makeRandomGrid()),
tick: () => dispatch(tick()),
startPlaying: (timerId) => dispatch(startPlaying(timerId)),
stopPlaying: () => dispatch(stopPlaying()),
clear: () => dispatch(clear())
};
}
const Control = connect(mapStateToProps_2,mapDispatchToProps_2)(Control_)
//
class Counter_ extends Component {
render(){
return (
<div className="counter">
Generations: {this.props.generations}
</div>
);
}
}
const mapStateToProps_3 = ({counter}) => {
return { generations: counter }
};
const Counter = connect(mapStateToProps_3)(Counter_);
//
const App = () => (
<div>
<h1>Game of Life (React + Redux)</h1>
<Board />
<Control />
<Counter />
</div>
)
//REDUCERS
const initialGrid = makeGrid(GRID_HEIGHT,GRID_WIDTH);
const boardReducer = (state = initialGrid, action) => {
switch(action.type){
case 'TOGGLE_ALIVE':
let board = state.slice(0);
let cell = board[action.x][action.y];
cell.status = !cell.status;
cell.newBorn = !cell.newBorn;
return board;
case 'MAKE_RANDOM':
//true param requests a random grid from makeGrid method
return makeGrid(GRID_HEIGHT, GRID_WIDTH, true);
case 'CLEAR':
return makeGrid(GRID_HEIGHT,GRID_WIDTH);
case 'TICK':
return advanceGrid(state.slice(0));
default:
return state;
}
};
const generationCounterReducer = (state = 0, action) => {
switch(action.type){
case 'TICK':
return state + 1;
case 'CLEAR':
return 0;
case 'MAKE_RANDOM':
return 0;
default:
return state;
}
};
const playInitialState = {
timerId: null,
isRunning: false
};
const playStatusReducer = (state = playInitialState, action) => {
switch(action.type){
case 'PLAY':
return {
timerId: action.timerId,
isRunning: true
};
case 'STOP':
return {
timerId: null,
isRuninng: false
};
default:
return state;
}
};
//COMBINE REDUCERS
const reducers = combineReducers({
board: boardReducer,
playState: playStatusReducer,
counter: generationCounterReducer,
});
//APPLICATION WRAPPER - wrap the app with the redux store and render to the DOM
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
Also see: Tab Triggers