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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space Shooter Game</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
canvas {
border: 2px solid #fff;
background-color: #000;
}
#game-container {
position: relative;
}
#score-display {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-size: 20px;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 40px;
text-align: center;
display: none;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 10px 2px;
cursor: pointer;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas" width="600" height="400"></canvas>
<div id="score-display">Score: 0</div>
<div id="game-over">
<h2>Game Over</h2>
<p>Your Score: <span id="final-score">0</span></p>
<button id="restart-button">Play Again</button>
</div>
</div>
<script>
// Game setup
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score-display');
const gameOverScreen = document.getElementById('game-over');
const finalScoreDisplay = document.getElementById('final-score');
const restartButton = document.getElementById('restart-button');
// Game variables
let score = 0;
let gameOver = false;
let animationId;
// Player setup
const player = {
x: canvas.width / 2,
y: canvas.height - 50,
width: 30,
height: 30,
color: '#00FF00',
speed: 5,
shooting: false,
shootingCooldown: 0
};
// Keys state
const keys = {
ArrowLeft: false,
ArrowRight: false,
ArrowUp: false,
ArrowDown: false,
Space: false
};
// Projectiles array
let projectiles = [];
// Enemies array
let enemies = [];
// Particles array (for explosions)
let particles = [];
// Game functions
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x - player.width / 2, player.y - player.height / 2, player.width, player.height);
// Draw a gun on top of the player
ctx.fillStyle = '#AAAAAA';
ctx.fillRect(player.x - 3, player.y - player.height / 2 - 10, 6, 10);
}
function movePlayer() {
if (keys.ArrowLeft && player.x > player.width / 2) {
player.x -= player.speed;
}
if (keys.ArrowRight && player.x < canvas.width - player.width / 2) {
player.x += player.speed;
}
if (keys.ArrowUp && player.y > player.height / 2) {
player.y -= player.speed;
}
if (keys.ArrowDown && player.y < canvas.height - player.height / 2) {
player.y += player.speed;
}
// Handle shooting
if (keys.Space && player.shootingCooldown <= 0) {
projectiles.push({
x: player.x,
y: player.y - player.height / 2,
radius: 3,
color: '#FFFF00',
speed: 8
});
player.shootingCooldown = 10; // Set cooldown to prevent rapid fire
}
// Reduce shooting cooldown
if (player.shootingCooldown > 0) {
player.shootingCooldown--;
}
}
function drawProjectiles() {
projectiles.forEach(projectile => {
ctx.beginPath();
ctx.arc(projectile.x, projectile.y, projectile.radius, 0, Math.PI * 2);
ctx.fillStyle = projectile.color;
ctx.fill();
ctx.closePath();
});
}
function moveProjectiles() {
projectiles.forEach((projectile, index) => {
projectile.y -= projectile.speed;
// Remove projectiles that are off screen
if (projectile.y + projectile.radius < 0) {
projectiles.splice(index, 1);
}
});
}
function createEnemy() {
const radius = Math.random() * 20 + 10;
const x = Math.random() * (canvas.width - radius * 2) + radius;
const speed = Math.random() * 2 + 1;
enemies.push({
x: x,
y: -radius,
radius: radius,
color: `hsl(${Math.random() * 360}, 50%, 50%)`,
speed: speed
});
}
function drawEnemies() {
enemies.forEach(enemy => {
ctx.beginPath();
ctx.arc(enemy.x, enemy.y, enemy.radius, 0, Math.PI * 2);
ctx.fillStyle = enemy.color;
ctx.fill();
ctx.closePath();
});
}
function moveEnemies() {
enemies.forEach((enemy, index) => {
enemy.y += enemy.speed;
// Check if enemy hit the bottom
if (enemy.y - enemy.radius > canvas.height) {
enemies.splice(index, 1);
score -= 10;
if (score < 0) score = 0;
updateScore();
}
// Check collision with player
const dist = Math.hypot(player.x - enemy.x, player.y - enemy.y);
if (dist - enemy.radius - player.width / 2 < 0) {
// Game over
endGame();
}
// Check collision with projectiles
projectiles.forEach((projectile, projectileIndex) => {
const dist = Math.hypot(projectile.x - enemy.x, projectile.y - enemy.y);
// If projectile hits enemy
if (dist - enemy.radius - projectile.radius < 0) {
// Create explosion
for (let i = 0; i < enemy.radius; i++) {
particles.push({
x: enemy.x,
y: enemy.y,
radius: Math.random() * 2,
color: enemy.color,
velocity: {
x: (Math.random() - 0.5) * 8,
y: (Math.random() - 0.5) * 8
},
alpha: 1
});
}
// Remove enemy and projectile
enemies.splice(index, 1);
projectiles.splice(projectileIndex, 1);
// Increase score
score += Math.floor(enemy.radius);
updateScore();
}
});
});
}
function drawParticles() {
particles.forEach((particle, index) => {
if (particle.alpha <= 0) {
particles.splice(index, 1);
return;
}
ctx.save();
ctx.globalAlpha = particle.alpha;
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
ctx.fillStyle = particle.color;
ctx.fill();
ctx.restore();
});
}
function moveParticles() {
particles.forEach(particle => {
particle.x += particle.velocity.x;
particle.y += particle.velocity.y;
particle.alpha -= 0.01;
});
}
function updateScore() {
scoreDisplay.textContent = `Score: ${score}`;
}
function endGame() {
gameOver = true;
finalScoreDisplay.textContent = score;
gameOverScreen.style.display = 'block';
cancelAnimationFrame(animationId);
}
// Game loop
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
movePlayer();
drawProjectiles();
moveProjectiles();
drawEnemies();
moveEnemies();
drawParticles();
moveParticles();
// Randomly spawn enemies
if (Math.random() < 0.02) {
createEnemy();
}
// Continue the game loop
if (!gameOver) {
animationId = requestAnimationFrame(gameLoop);
}
}
// Key event listeners
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft') keys.ArrowLeft = true;
if (event.key === 'ArrowRight') keys.ArrowRight = true;
if (event.key === 'ArrowUp') keys.ArrowUp = true;
if (event.key === 'ArrowDown') keys.ArrowDown = true;
if (event.key === ' ') keys.Space = true;
});
document.addEventListener('keyup', (event) => {
if (event.key === 'ArrowLeft') keys.ArrowLeft = false;
if (event.key === 'ArrowRight') keys.ArrowRight = false;
if (event.key === 'ArrowUp') keys.ArrowUp = false;
if (event.key === 'ArrowDown') keys.ArrowDown = false;
if (event.key === ' ') keys.Space = false;
});
// Restart button listener
restartButton.addEventListener('click', () => {
// Reset game variables
score = 0;
updateScore();
gameOver = false;
gameOverScreen.style.display = 'none';
// Reset player position
player.x = canvas.width / 2;
player.y = canvas.height - 50;
// Clear arrays
projectiles = [];
enemies = [];
particles = [];
// Start the game again
gameLoop();
});
// Start the game
gameLoop();
</script>
</body>
</html>
Also see: Tab Triggers