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.
<a id="youtube" target="_top" href="https://www.youtube.com/watch?v=ccYrSACDNsw">
<span>Learn React Three Fiber while building this game on YouTube</span>
</a>
<div id="youtube-card">
Learn React Three Fiber while building this game on YouTube
</div>
<div id="root" />
@import url("https://fonts.googleapis.com/css?family=Press+Start+2P");
body {
margin: 0;
display: flex;
min-height: 100vh;
}
#root {
width: 100%;
}
.game {
position: relative;
width: 100%;
height: 100%;
font-family: "Press Start 2P", cursive;
}
#controls {
position: absolute;
bottom: 20px;
min-width: 100%;
display: flex;
align-items: flex-end;
justify-content: center;
}
#controls div {
display: grid;
grid-template-columns: 50px 50px 50px;
gap: 10px;
}
#controls button {
width: 100%;
height: 40px;
background-color: white;
border: 1px solid lightgray;
box-shadow: 3px 5px 0px 0px rgba(0, 0, 0, 0.75);
cursor: pointer;
outline: none;
}
#controls button:first-of-type {
grid-column: 1/-1;
}
#score {
position: absolute;
top: 20px;
left: 20px;
font-size: 2em;
color: white;
}
#result-container {
position: absolute;
min-width: 100%;
min-height: 100%;
top: 0;
display: flex;
align-items: center;
justify-content: center;
#result {
display: flex;
flex-direction: column;
align-items: center;
background-color: white;
padding: 20px;
}
button {
background-color: red;
padding: 20px 50px 20px 50px;
font-family: inherit;
font-size: inherit;
cursor: pointer;
}
}
#youtube,
#youtube-card {
display: none;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
color: black;
}
@media (min-height: 425px) {
/** Youtube logo by https://codepen.io/alvaromontoro */
#youtube {
z-index: 50;
width: 100px;
display: block;
height: 70px;
position: fixed;
bottom: 20px;
right: 20px;
background: red;
border-radius: 50% / 11%;
transform: scale(0.8);
transition: transform 0.5s;
}
#youtube:hover,
#youtube:focus {
transform: scale(0.9);
color: black;
}
#youtube::before {
content: "";
display: block;
position: absolute;
top: 7.5%;
left: -6%;
width: 112%;
height: 85%;
background: red;
border-radius: 9% / 50%;
}
#youtube::after {
content: "";
display: block;
position: absolute;
top: 20px;
left: 40px;
width: 45px;
height: 30px;
border: 15px solid transparent;
box-sizing: border-box;
border-left: 30px solid white;
}
#youtube span {
font-size: 0;
position: absolute;
width: 0;
height: 0;
overflow: hidden;
}
#youtube:hover + #youtube-card {
z-index: 49;
display: block;
position: fixed;
bottom: 12px;
right: 10px;
padding: 25px 130px 25px 25px;
width: 300px;
background-color: white;
}
}
/*
Learn how to code this watch step by step on YouTube:
https://www.youtube.com/watch?v=ccYrSACDNsw
or on:
https://javascriptgametutorials.com/
*/
import React, { useRef, useEffect } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
import { Canvas, useFrame, useThree } from "https://esm.sh/@react-three/fiber";
import { Bounds } from "https://esm.sh/@react-three/drei";
import * as THREE from "https://esm.sh/three";
import { create } from "https://esm.sh/zustand";
const minTileIndex = -8;
const maxTileIndex = 8;
const tilesPerRow = maxTileIndex - minTileIndex + 1;
const tileSize = 42;
const playerState = {
currentRow: 0,
currentTile: 0,
movesQueue: [],
ref: null
};
function queueMove(direction) {
const isValidMove = endsUpInValidPosition(
{ rowIndex: playerState.currentRow, tileIndex: playerState.currentTile },
[...playerState.movesQueue, direction]
);
if (!isValidMove) return;
playerState.movesQueue.push(direction);
}
function stepCompleted() {
const direction = playerState.movesQueue.shift();
if (direction === "forward") playerState.currentRow += 1;
if (direction === "backward") playerState.currentRow -= 1;
if (direction === "left") playerState.currentTile -= 1;
if (direction === "right") playerState.currentTile += 1;
// Add new rows if the player is running out of them
if (playerState.currentRow === useMapStore.getState().rows.length - 10) {
useMapStore.getState().addRows();
}
useGameStore.getState().updateScore(playerState.currentRow);
}
function setPlayerRef(ref) {
playerState.ref = ref;
}
function resetPlayerStore() {
playerState.currentRow = 0;
playerState.currentTile = 0;
playerState.movesQueue = [];
if (!playerState.ref) return;
playerState.ref.position.x = 0;
playerState.ref.position.y = 0;
playerState.ref.children[0].rotation.z = 0;
}
const useGameStore = create((set) => ({
status: "running",
score: 0,
updateScore: (rowIndex) => {
set((state) => ({ score: Math.max(rowIndex, state.score) }));
},
endGame: () => {
set({ status: "over" });
},
reset: () => {
useMapStore.getState().reset();
resetPlayerStore();
set({ status: "running", score: 0 });
}
}));
const useMapStore = create((set) => ({
rows: generateRows(20),
addRows: () => {
const newRows = generateRows(20);
set((state) => ({ rows: [...state.rows, ...newRows] }));
},
reset: () => set({ rows: generateRows(20) })
}));
function Game() {
return (
<div className="game">
<Scene>
<Player />
<Map />
</Scene>
<Score />
<Controls />
<Result />
</div>
);
}
const Scene = ({ children }) => {
return (
<Canvas
orthographic={true}
shadows={true}
camera={{
up: [0, 0, 1],
position: [300, -300, 300]
}}
>
<ambientLight />
{children}
</Canvas>
);
};
function Controls() {
useEventListeners();
return (
<div id="controls">
<div>
<button onClick={() => queueMove("forward")}>▲</button>
<button onClick={() => queueMove("left")}>◀</button>
<button onClick={() => queueMove("backward")}>▼</button>
<button onClick={() => queueMove("right")}>▶</button>
</div>
</div>
);
}
function Score() {
const score = useGameStore((state) => state.score);
return <div id="score">{score}</div>;
}
function Result() {
const status = useGameStore((state) => state.status);
const score = useGameStore((state) => state.score);
const reset = useGameStore((state) => state.reset);
if (status === "running") return null;
return (
<div id="result-container">
<div id="result">
<h1>Game Over</h1>
<p>Your score: {score}</p>
<button onClick={reset}>Retry</button>
</div>
</div>
);
}
function Player() {
const player = useRef(null);
const lightRef = useRef(null);
const camera = useThree((state) => state.camera);
usePlayerAnimation(player);
useEffect(() => {
if (!player.current) return;
if (!lightRef.current) return;
// Attach the camera to the player
player.current.add(camera);
lightRef.current.target = player.current;
// Set the player reference in the store
setPlayerRef(player.current);
});
return (
<Bounds fit clip observe margin={10}>
<group ref={player}>
<group>
<mesh position={[0, 0, 10]} castShadow receiveShadow>
<boxGeometry args={[15, 15, 20]} />
<meshLambertMaterial color={0xffffff} flatShading />
</mesh>
<mesh position={[0, 0, 21]} castShadow receiveShadow>
<boxGeometry args={[2, 4, 2]} />
<meshLambertMaterial color={0xf0619a} flatShading />
</mesh>
</group>
<DirectionalLight ref={lightRef} />
</group>
</Bounds>
);
}
function DirectionalLight({ ref }) {
return (
<directionalLight
ref={ref}
position={[-100, -100, 200]}
up={[0, 0, 1]}
castShadow
shadow-mapSize={[2048, 2048]}
shadow-camera-left={-400}
shadow-camera-right={400}
shadow-camera-top={400}
shadow-camera-bottom={-400}
shadow-camera-near={50}
shadow-camera-far={400}
/>
);
}
function Map() {
const rows = useMapStore((state) => state.rows);
return (
<>
<Grass rowIndex={0} />
<Grass rowIndex={-1} />
<Grass rowIndex={-2} />
<Grass rowIndex={-3} />
<Grass rowIndex={-4} />
<Grass rowIndex={-5} />
<Grass rowIndex={-6} />
<Grass rowIndex={-7} />
<Grass rowIndex={-8} />
{rows.map((rowData, index) => (
<Row key={index} rowIndex={index + 1} rowData={rowData} />
))}
</>
);
}
function Row({ rowIndex, rowData }) {
switch (rowData.type) {
case "forest": {
return <Forest rowIndex={rowIndex} rowData={rowData} />;
}
case "car": {
return <CarLane rowIndex={rowIndex} rowData={rowData} />;
}
case "truck": {
return <TruckLane rowIndex={rowIndex} rowData={rowData} />;
}
}
}
function Forest({ rowIndex, rowData }) {
return (
<Grass rowIndex={rowIndex}>
{rowData.trees.map((tree, index) => (
<Tree key={index} tileIndex={tree.tileIndex} height={tree.height} />
))}
</Grass>
);
}
function CarLane({ rowIndex, rowData }) {
return (
<Road rowIndex={rowIndex}>
{rowData.vehicles.map((vehicle, index) => (
<Car
key={index}
rowIndex={rowIndex}
initialTileIndex={vehicle.initialTileIndex}
direction={rowData.direction}
speed={rowData.speed}
color={vehicle.color}
/>
))}
</Road>
);
}
function TruckLane({ rowIndex, rowData }) {
return (
<Road rowIndex={rowIndex}>
{rowData.vehicles.map((vehicle, index) => (
<Truck
key={index}
rowIndex={rowIndex}
color={vehicle.color}
initialTileIndex={vehicle.initialTileIndex}
direction={rowData.direction}
speed={rowData.speed}
/>
))}
</Road>
);
}
function Grass({ rowIndex, children }) {
return (
<group position-y={rowIndex * tileSize}>
<mesh receiveShadow>
<boxGeometry args={[tilesPerRow * tileSize, tileSize, 3]} />
<meshLambertMaterial color={0xbaf455} flatShading />
</mesh>
<mesh receiveShadow position-x={tilesPerRow * tileSize}>
<boxGeometry args={[tilesPerRow * tileSize, tileSize, 3]} />
<meshLambertMaterial color={0x99c846} flatShading />
</mesh>
<mesh receiveShadow position-x={-tilesPerRow * tileSize}>
<boxGeometry args={[tilesPerRow * tileSize, tileSize, 3]} />
<meshLambertMaterial color={0x99c846} flatShading />
</mesh>
{children}
</group>
);
}
function Road({ rowIndex, children }) {
return (
<group position-y={rowIndex * tileSize}>
<mesh receiveShadow>
<planeGeometry args={[tilesPerRow * tileSize, tileSize]} />
<meshLambertMaterial color={0x454a59} flatShading />
</mesh>
<mesh receiveShadow position-x={tilesPerRow * tileSize}>
<planeGeometry args={[tilesPerRow * tileSize, tileSize]} />
<meshLambertMaterial color={0x393d49} flatShading />
</mesh>
<mesh receiveShadow position-x={-tilesPerRow * tileSize}>
<planeGeometry args={[tilesPerRow * tileSize, tileSize]} />
<meshLambertMaterial color={0x393d49} flatShading />
</mesh>
{children}
</group>
);
}
function Tree({ tileIndex, height }) {
return (
<group position-x={tileIndex * tileSize}>
<mesh position-z={height / 2 + 20} castShadow receiveShadow>
<boxGeometry args={[30, 30, height]} />
<meshLambertMaterial color={0x7aa21d} flatShading />
</mesh>
<mesh position-z={10} castShadow receiveShadow>
<boxGeometry args={[15, 15, 20]} />
<meshLambertMaterial color={0x4d2926} flatShading />
</mesh>
</group>
);
}
function Car({ rowIndex, initialTileIndex, direction, speed, color }) {
const car = useRef(null);
useVehicleAnimation(car, direction, speed);
useHitDetection(car, rowIndex);
return (
<group
position-x={initialTileIndex * tileSize}
rotation-z={direction ? 0 : Math.PI}
ref={car}
>
<mesh position={[0, 0, 12]} castShadow receiveShadow>
<boxGeometry args={[60, 30, 15]} />
<meshLambertMaterial color={color} flatShading />
</mesh>
<mesh position={[-6, 0, 25.5]} castShadow receiveShadow>
<boxGeometry args={[33, 24, 12]} />
<meshLambertMaterial color={0xffffff} flatShading />
</mesh>
<Wheel x={-18} />
<Wheel x={18} />
</group>
);
}
function Truck({ rowIndex, initialTileIndex, direction, speed, color }) {
const truck = useRef(null);
useVehicleAnimation(truck, direction, speed);
useHitDetection(truck, rowIndex);
return (
<group
position-x={initialTileIndex * tileSize}
rotation-z={direction ? 0 : Math.PI}
ref={truck}
>
<mesh position={[-15, 0, 25]} castShadow receiveShadow>
<boxGeometry args={[70, 35, 35]} />
<meshLambertMaterial color={0xb4c6fc} flatShading />
</mesh>
<mesh position={[35, 0, 20]} castShadow receiveShadow>
<boxGeometry args={[30, 30, 30]} />
<meshLambertMaterial color={color} flatShading />
</mesh>
<Wheel x={-35} />
<Wheel x={5} />
<Wheel x={37} />
</group>
);
}
function Wheel({ x }) {
return (
<mesh position={[x, 0, 6]}>
<boxGeometry args={[12, 33, 12]} />
<meshLambertMaterial color={0x333333} flatShading />
</mesh>
);
}
function useVehicleAnimation(ref, direction, speed) {
useFrame((state, delta) => {
if (!ref.current) return;
const vehicle = ref.current;
const beginningOfRow = (minTileIndex - 2) * tileSize;
const endOfRow = (maxTileIndex + 2) * tileSize;
if (direction) {
vehicle.position.x =
vehicle.position.x > endOfRow
? beginningOfRow
: vehicle.position.x + speed * delta;
} else {
vehicle.position.x =
vehicle.position.x < beginningOfRow
? endOfRow
: vehicle.position.x - speed * delta;
}
});
}
function useEventListeners() {
useEffect(() => {
const handleKeyDown = (event) => {
if (event.key === "ArrowUp") {
event.preventDefault();
queueMove("forward");
} else if (event.key === "ArrowDown") {
event.preventDefault();
queueMove("backward");
} else if (event.key === "ArrowLeft") {
event.preventDefault();
queueMove("left");
} else if (event.key === "ArrowRight") {
event.preventDefault();
queueMove("right");
}
};
window.addEventListener("keydown", handleKeyDown);
// Cleanup function to remove the event listener
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
}
function usePlayerAnimation(ref) {
const moveClock = new THREE.Clock(false);
useFrame(() => {
if (!ref.current) return;
if (!playerState.movesQueue.length) return;
const player = ref.current;
if (!moveClock.running) moveClock.start();
const stepTime = 0.2; // Seconds it takes to take a step
const progress = Math.min(1, moveClock.getElapsedTime() / stepTime);
setPosition(player, progress);
setRotation(player, progress);
// Once a step has ended
if (progress >= 1) {
stepCompleted();
moveClock.stop();
}
});
}
function setPosition(player, progress) {
const startX = playerState.currentTile * tileSize;
const startY = playerState.currentRow * tileSize;
let endX = startX;
let endY = startY;
if (playerState.movesQueue[0] === "left") endX -= tileSize;
if (playerState.movesQueue[0] === "right") endX += tileSize;
if (playerState.movesQueue[0] === "forward") endY += tileSize;
if (playerState.movesQueue[0] === "backward") endY -= tileSize;
player.position.x = THREE.MathUtils.lerp(startX, endX, progress);
player.position.y = THREE.MathUtils.lerp(startY, endY, progress);
player.children[0].position.z = Math.sin(progress * Math.PI) * 8;
}
function setRotation(player, progress) {
let endRotation = 0;
if (playerState.movesQueue[0] == "forward") endRotation = 0;
if (playerState.movesQueue[0] == "left") endRotation = Math.PI / 2;
if (playerState.movesQueue[0] == "right") endRotation = -Math.PI / 2;
if (playerState.movesQueue[0] == "backward") endRotation = Math.PI;
player.children[0].rotation.z = THREE.MathUtils.lerp(
player.children[0].rotation.z,
endRotation,
progress
);
}
function calculateFinalPosition(currentPosition, moves) {
return moves.reduce((position, direction) => {
if (direction === "forward")
return {
rowIndex: position.rowIndex + 1,
tileIndex: position.tileIndex
};
if (direction === "backward")
return {
rowIndex: position.rowIndex - 1,
tileIndex: position.tileIndex
};
if (direction === "left")
return {
rowIndex: position.rowIndex,
tileIndex: position.tileIndex - 1
};
if (direction === "right")
return {
rowIndex: position.rowIndex,
tileIndex: position.tileIndex + 1
};
return position;
}, currentPosition);
}
function endsUpInValidPosition(currentPosition, moves) {
// Calculate where the player would end up after the move
const finalPosition = calculateFinalPosition(currentPosition, moves);
// Detect if we hit the edge of the board
if (
finalPosition.rowIndex === -1 ||
finalPosition.tileIndex === minTileIndex - 1 ||
finalPosition.tileIndex === maxTileIndex + 1
) {
// Invalid move, ignore move command
return false;
}
// Detect if we hit a tree
const finalRow = useMapStore.getState().rows[finalPosition.rowIndex - 1];
if (
finalRow &&
finalRow.type === "forest" &&
finalRow.trees.some((tree) => tree.tileIndex === finalPosition.tileIndex)
) {
// Invalid move, ignore move command
return false;
}
return true;
}
function generateRows(amount) {
const rows = [];
for (let i = 0; i < amount; i++) {
const rowData = generateRow();
rows.push(rowData);
}
return rows;
}
function generateRow() {
const type = randomElement(["car", "truck", "forest"]);
if (type === "car") return generateCarLaneMetadata();
if (type === "truck") return generateTruckLaneMetadata();
return generateForesMetadata();
}
function randomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
function generateForesMetadata() {
const occupiedTiles = new Set();
const trees = Array.from({ length: 4 }, () => {
let tileIndex;
do {
tileIndex = THREE.MathUtils.randInt(minTileIndex, maxTileIndex);
} while (occupiedTiles.has(tileIndex));
occupiedTiles.add(tileIndex);
const height = randomElement([20, 45, 60]);
return { tileIndex, height };
});
return { type: "forest", trees };
}
function generateCarLaneMetadata() {
const direction = randomElement([true, false]);
const speed = randomElement([125, 156, 188]);
const occupiedTiles = new Set();
const vehicles = Array.from({ length: 3 }, () => {
let initialTileIndex;
do {
initialTileIndex = THREE.MathUtils.randInt(minTileIndex, maxTileIndex);
} while (occupiedTiles.has(initialTileIndex));
occupiedTiles.add(initialTileIndex - 1);
occupiedTiles.add(initialTileIndex);
occupiedTiles.add(initialTileIndex + 1);
const color = randomElement([0xa52523, 0xbdb638, 0x78b14b]);
return { initialTileIndex, color };
});
return { type: "car", direction, speed, vehicles };
}
function generateTruckLaneMetadata() {
const direction = randomElement([true, false]);
const speed = randomElement([125, 156, 188]);
const occupiedTiles = new Set();
const vehicles = Array.from({ length: 2 }, () => {
let initialTileIndex;
do {
initialTileIndex = THREE.MathUtils.randInt(minTileIndex, maxTileIndex);
} while (occupiedTiles.has(initialTileIndex));
occupiedTiles.add(initialTileIndex - 2);
occupiedTiles.add(initialTileIndex - 1);
occupiedTiles.add(initialTileIndex);
occupiedTiles.add(initialTileIndex + 1);
occupiedTiles.add(initialTileIndex + 2);
const color = randomElement([0xa52523, 0xbdb638, 0x78b14b]);
return { initialTileIndex, color };
});
return { type: "truck", direction, speed, vehicles };
}
function useHitDetection(vehicle, rowIndex) {
const endGame = useGameStore((state) => state.endGame);
useFrame(() => {
if (!vehicle.current) return;
if (!playerState.ref) return;
if (
rowIndex === playerState.currentRow ||
rowIndex === playerState.currentRow + 1 ||
rowIndex === playerState.currentRow - 1
) {
const vehicleBoundingBox = new THREE.Box3();
vehicleBoundingBox.setFromObject(vehicle.current);
const playerBoundingBox = new THREE.Box3();
playerBoundingBox.setFromObject(playerState.ref);
if (playerBoundingBox.intersectsBox(vehicleBoundingBox)) {
endGame();
}
}
});
}
const root = createRoot(document.getElementById("root"));
root.render(<Game />);
Also see: Tab Triggers