Sure! Below is a simple Starfighter game with a comic book vibe, designed to run in a web browser on an Android smartphone. The game uses HTML, CSS, and JavaScript. It features a player-controlled spaceship, enemy ships, shooting mechanics, touch controls for movement and firing, and a scoring system.
Project Structure
Create a folder for your project and include the following files:
index.html — The main HTML file.
styles.css — The CSS file for styling.
game.js — The JavaScript file containing game logic.
images/ — A folder containing all the image assets.
Image Assets
Place the following images in the images/ folder:
-
Background Image
- Filename:
background.png
- Description: A vertical scrolling space background with a comic book art style, featuring stars and galaxies.
-
Player Spaceship
- Filename:
playerShip.png
- Description: A futuristic spaceship with sharp angles and bright colors, reminiscent of comic book illustrations.
-
Enemy Spaceship
- Filename:
enemyShip.png
- Description: An ominous-looking alien spaceship with a dark, bold outline, fitting the comic book theme.
-
Player Bullet
- Filename:
playerBullet.png
- Description: A bright laser beam or projectile with motion lines to emphasize movement.
-
Enemy Bullet
- Filename:
enemyBullet.png
- Description: A contrasting laser beam or projectile, possibly in a different color to differentiate from the player's bullets.
-
Explosion Sprite
- Filename:
explosion.png
- Description: A sprite sheet of an explosion animation in comic book style, with bold colors and lines.
Note: You can create these images yourself or find royalty-free images that match the descriptions.
Code Implementation
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Starfighter Comic Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas"></canvas>
<!-- Touch controls for mobile -->
<div id="controls">
<div id="leftBtn" class="control-btn">◄</div>
<div id="rightBtn" class="control-btn">►</div>
<div id="fireBtn" class="control-btn">FIRE</div>
</div>
<script src="game.js"></script>
</body>
</html>
2. styles.css
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
#gameCanvas {
display: block;
background-color: #000;
}
#controls {
position: fixed;
bottom: 10px;
width: 100%;
text-align: center;
}
.control-btn {
display: inline-block;
margin: 0 10px;
padding: 15px 25px;
background: rgba(255, 255, 255, 0.2);
color: #fff;
font-size: 18px;
border: 2px solid #fff;
border-radius: 5px;
user-select: none;
}
.control-btn:active {
background: rgba(255, 255, 255, 0.4);
}
3. game.js
// Get the canvas and context
const canvas = document.getElementById('gameCanvas');
const context = canvas.getContext('2d');
// Set canvas dimensions to fit the screen
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Load images
const images = {};
const loadImages = () => {
const imageSources = {
background: 'images/background.png',
playerShip: 'images/playerShip.png',
enemyShip: 'images/enemyShip.png',
playerBullet: 'images/playerBullet.png',
enemyBullet: 'images/enemyBullet.png',
explosion: 'images/explosion.png',
};
const totalImages = Object.keys(imageSources).length;
let loadedImages = 0;
return new Promise((resolve) => {
for (let key in imageSources) {
images[key] = new Image();
images[key].src = imageSources[key];
images[key].onload = () => {
loadedImages++;
if (loadedImages === totalImages) {
resolve();
}
};
}
});
};
// Game variables
let player, enemies, bullets, enemyBullets, explosions, score, gameOver;
let keys = {};
// Initialize the game
const init = () => {
player = {
x: canvas.width / 2 - 25,
y: canvas.height - 100,
width: 50,
height: 50,
speed: 5,
};
enemies = [];
bullets = [];
enemyBullets = [];
explosions = [];
score = 0;
gameOver = false;
// Spawn enemies
spawnEnemies();
// Event listeners for touch controls
document.getElementById('leftBtn').addEventListener('touchstart', () => {
keys['ArrowLeft'] = true;
});
document.getElementById('leftBtn').addEventListener('touchend', () => {
keys['ArrowLeft'] = false;
});
document.getElementById('rightBtn').addEventListener('touchstart', () => {
keys['ArrowRight'] = true;
});
document.getElementById('rightBtn').addEventListener('touchend', () => {
keys['ArrowRight'] = false;
});
document.getElementById('fireBtn').addEventListener('touchstart', () => {
keys['Space'] = true;
});
document.getElementById('fireBtn').addEventListener('touchend', () => {
keys['Space'] = false;
});
// Keyboard controls as fallback
window.addEventListener('keydown', (e) => {
keys[e.code] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.code] = false;
});
// Start the game loop
gameLoop();
};
// Spawn enemies function
const spawnEnemies = () => {
for (let i = 0; i < 5; i++) {
enemies.push({
x: i * 80 + 60,
y: 50,
width: 50,
height: 50,
speed: 2,
direction: 1,
});
}
};
// Game loop
const gameLoop = () => {
if (!gameOver) {
update();
render();
requestAnimationFrame(gameLoop);
} else {
// Display Game Over
context.fillStyle = '#fff';
context.font = '48px sans-serif';
context.textAlign = 'center';
context.fillText('Game Over', canvas.width / 2, canvas.height / 2);
context.font = '24px sans-serif';
context.fillText(`Score: ${score}`, canvas.width / 2, canvas.height / 2 + 50);
}
};
// Update game state
const update = () => {
// Move player
if (keys['ArrowLeft'] && player.x > 0) {
player.x -= player.speed;
}
if (keys['ArrowRight'] && player.x + player.width < canvas.width) {
player.x += player.speed;
}
// Fire bullet
if (keys['Space']) {
fireBullet();
}
// Update bullets
bullets.forEach((bullet, index) => {
bullet.y -= bullet.speed;
// Remove off-screen bullets
if (bullet.y < 0) {
bullets.splice(index, 1);
}
});
// Update enemies
enemies.forEach((enemy, index) => {
enemy.x += enemy.speed * enemy.direction;
// Change direction at edges
if (enemy.x <= 0 || enemy.x + enemy.width >= canvas.width) {
enemy.direction *= -1;
enemy.y += enemy.height; // Move down when changing direction
}
// Fire enemy bullet
if (Math.random() < 0.005) {
enemyFire(enemy);
}
});
// Update enemy bullets
enemyBullets.forEach((bullet, index) => {
bullet.y += bullet.speed;
// Remove off-screen bullets
if (bullet.y > canvas.height) {
enemyBullets.splice(index, 1);
}
});
// Check for collisions
checkCollisions();
// Update explosions
explosions.forEach((explosion, index) => {
explosion.frame++;
if (explosion.frame > 10) {
explosions.splice(index, 1);
}
});
// Check for game over
enemies.forEach((enemy) => {
if (enemy.y + enemy.height >= player.y) {
gameOver = true;
}
});
};
// Render game objects
const render = () => {
// Clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw background (optional: create scrolling background effect)
context.drawImage(images.background, 0, 0, canvas.width, canvas.height);
// Draw player
context.drawImage(images.playerShip, player.x, player.y, player.width, player.height);
// Draw bullets
bullets.forEach((bullet) => {
context.drawImage(images.playerBullet, bullet.x, bullet.y, bullet.width, bullet.height);
});
// Draw enemies
enemies.forEach((enemy) => {
context.drawImage(images.enemyShip, enemy.x, enemy.y, enemy.width, enemy.height);
});
// Draw enemy bullets
enemyBullets.forEach((bullet) => {
context.drawImage(images.enemyBullet, bullet.x, bullet.y, bullet.width, bullet.height);
});
// Draw explosions
explosions.forEach((explosion) => {
// Assuming explosion sprite sheet has 5 frames horizontally
const spriteWidth = images.explosion.width / 5;
context.drawImage(
images.explosion,
Math.floor(explosion.frame / 2) * spriteWidth,
0,
spriteWidth,
images.explosion.height,
explosion.x,
explosion.y,
explosion.width,
explosion.height
);
});
// Draw score
context.fillStyle = '#fff';
context.font = '24px sans-serif';
context.fillText(`Score: ${score}`, 10, 30);
};
// Fire a bullet from the player
const fireBullet = () => {
// Control firing rate
if (!player.canFire) return;
player.canFire = false;
bullets.push({
x: player.x + player.width / 2 - 5,
y: player.y,
width: 10,
height: 20,
speed: 7,
});
// Allow firing again after a short delay
setTimeout(() => {
player.canFire = true;
}, 300);
};
// Enemy fires a bullet
const enemyFire = (enemy) => {
enemyBullets.push({
x: enemy.x + enemy.width / 2 - 5,
y: enemy.y + enemy.height,
width: 10,
height: 20,
speed: 5,
});
};
// Check for collisions
const checkCollisions = () => {
// Player bullets and enemies
bullets.forEach((bullet, bIndex) => {
enemies.forEach((enemy, eIndex) => {
if (isColliding(bullet, enemy)) {
// Create explosion
explosions.push({
x: enemy.x,
y: enemy.y,
width: enemy.width,
height: enemy.height,
frame: 0,
});
// Remove enemy and bullet
enemies.splice(eIndex, 1);
bullets.splice(bIndex, 1);
score += 10;
}
});
});
// Enemy bullets and player
enemyBullets.forEach((bullet, index) => {
if (isColliding(bullet, player)) {
// Create explosion
explosions.push({
x: player.x,
y: player.y,
width: player.width,
height: player.height,
frame: 0,
});
enemyBullets.splice(index, 1);
gameOver = true;
}
});
};
// Collision detection
const isColliding = (a, b) => {
return (
a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y
);
};
// Start the game after loading images
loadImages().then(() => {
init();
});
Adjustments for Android Smartphones
- Responsive Canvas: The canvas size is set to match the window's width and height to utilize the full screen on any device.
- Touch Controls: On-screen buttons (
leftBtn, rightBtn, fireBtn) are added at the bottom of the screen for player movement and firing.
- Touch events are used (
touchstart, touchend) to handle input from mobile devices.
- Fallback Keyboard Controls: Keyboard event listeners are added to allow playing the game on desktop browsers.
Notes and Tips
- Image Sizes: Adjust the width and height values in the code to match the actual dimensions of your images or to scale them appropriately.
- Optimizing for Performance: For better performance on mobile devices, consider optimizing images and limiting the number of objects on the screen.
- Audio Effects: Enhance the game by adding sound effects for shooting and explosions using the HTML5 Audio API.
- Scoring and Levels: Expand the game by adding levels, different enemy types, power-ups, and a more sophisticated scoring system.
- Testing on Android: Host the game files on a web server or use a local server and access it through the Android device's browser to test the game.
Conclusion
You now have a basic Starfighter game with a comic book vibe that can be played on an Android smartphone. Feel free to expand upon this foundation by adding more features, refining the graphics, and improving gameplay to make the game even more engaging.