Creating a fully-featured 2D space simulation game as described is a substantial project. Below is a simplified version to get you started. This version includes:
- Land Mode: Player starts on a desert junkyard planet, can move using WASD.
- Scavenging Mechanism: Collect parts from old ships.
- Purchasing a Ship: Buy a ship after accumulating enough parts/money.
- Space Mode: Transition to space after purchasing a ship.
- Random Generation: Randomly generate planet and ship locations each game session.
- Save and Load Feature: Multiple save slots using
localStorage.
For simplicity, this example uses basic HTML, CSS, and vanilla JavaScript with the Canvas API. For a more advanced game, consider using game development libraries like Phaser.js.
Project Structure
space-sim-game/
│
├── index.html
├── styles.css
└── game.js
1. index.html
Set up the HTML structure with a canvas and basic UI elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Space Sim Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<!-- UI Elements -->
<div id="ui">
<div id="status">
<span id="mode">Mode: Land</span>
<span id="money">Money: $0</span>
<span id="parts">Parts: 0</span>
</div>
<div id="menu">
<button id="saveBtn">Save Game</button>
<button id="loadBtn">Load Game</button>
<select id="saveSlots">
<option value="slot1">Slot 1</option>
<option value="slot2">Slot 2</option>
<option value="slot3">Slot 3</option>
</select>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
2. styles.css
Basic styling for the canvas and UI elements.
body {
margin: 0;
overflow: hidden;
background-color: #000;
color: #fff;
font-family: Arial, sans-serif;
}
#gameCanvas {
display: block;
margin: 0 auto;
background-color: #222;
}
#ui {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
justify-content: space-between;
width: 800px;
}
#status {
display: flex;
gap: 20px;
}
#menu {
display: flex;
gap: 10px;
}
3. game.js
The core game logic handling rendering, controls, state management, and saving/loading.
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// UI Elements
const modeSpan = document.getElementById('mode');
const moneySpan = document.getElementById('money');
const partsSpan = document.getElementById('parts');
const saveBtn = document.getElementById('saveBtn');
const loadBtn = document.getElementById('loadBtn');
const saveSlots = document.getElementById('saveSlots');
// Game State
let gameState = {
mode: 'land', // 'land' or 'space'
money: 0,
parts: 0,
position: { x: 400, y: 300 },
shipOwned: false,
planet: {},
ships: [],
space: {
spaceStation: { x: 700, y: 100 }
}
};
// Keys Pressed
const keys = {};
// Initialize Game
function init() {
generatePlanet();
generateShips();
loadUI();
requestAnimationFrame(gameLoop);
}
// Generate Random Planet Parameters
function generatePlanet() {
gameState.planet = {
name: 'Desert Junkyard',
resources: Math.floor(Math.random() * 100),
// Add more planet-specific properties
};
}
// Generate Random Ships on Planet
function generateShips() {
const shipCount = Math.floor(Math.random() * 5) + 5; // 5-10 ships
gameState.ships = [];
for (let i = 0; i < shipCount; i++) {
gameState.ships.push({
id: i,
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
collected: false
});
}
}
// Handle Keyboard Input
window.addEventListener('keydown', (e) => {
keys[e.key.toLowerCase()] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.key.toLowerCase()] = false;
});
// Game Loop
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
// Update Game State
function update() {
// Movement
const speed = 2;
if (keys['w']) gameState.position.y -= speed;
if (keys['s']) gameState.position.y += speed;
if (keys['a']) gameState.position.x -= speed;
if (keys['d']) gameState.position.x += speed;
// Boundary Conditions
gameState.position.x = Math.max(0, Math.min(canvas.width, gameState.position.x));
gameState.position.y = Math.max(0, Math.min(canvas.height, gameState.position.y));
// Check for ship collision to collect parts
if (gameState.mode === 'land') {
gameState.ships.forEach(ship => {
if (!ship.collected) {
const dist = Math.hypot(gameState.position.x - ship.x, gameState.position.y - ship.y);
if (dist < 20) {
ship.collected = true;
gameState.parts += 10; // Each ship gives 10 parts
}
}
});
// Example condition to purchase ship
if (!gameState.shipOwned && gameState.parts >= 50) {
// Auto-purchase for demo purposes
gameState.shipOwned = true;
gameState.parts -= 50;
alert('You have purchased your own ship! Transitioning to space mode.');
transitionToSpace();
}
}
// Update UI
loadUI();
}
// Render Game
function render() {
// Clear Canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (gameState.mode === 'land') {
renderLand();
} else if (gameState.mode === 'space') {
renderSpace();
}
}
// Render Land Mode
function renderLand() {
// Draw Planet Background
ctx.fillStyle = '#8B4513'; // Desert color
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Ships
gameState.ships.forEach(ship => {
if (!ship.collected) {
ctx.fillStyle = 'gray';
ctx.beginPath();
ctx.arc(ship.x, ship.y, 10, 0, Math.PI * 2);
ctx.fill();
}
});
// Draw Player
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(gameState.position.x, gameState.position.y, 10, 0, Math.PI * 2);
ctx.fill();
}
// Render Space Mode
function renderSpace() {
// Draw Space Background
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Space Station
const station = gameState.space.spaceStation;
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(station.x, station.y, 20, 0, Math.PI * 2);
ctx.fill();
// Draw Player's Ship
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(gameState.position.x, gameState.position.y, 10, 0, Math.PI * 2);
ctx.fill();
// Example: Move Towards Space Station
const dx = station.x - gameState.position.x;
const dy = station.y - gameState.position.y;
const distance = Math.hypot(dx, dy);
if (distance > 20) {
gameState.position.x += (dx / distance) * 1; // Normalize and move
gameState.position.y += (dy / distance) * 1;
} else {
alert('Arrived at Space Station! You can take on more jobs.');
// Implement additional space station interactions here
}
}
// Transition to Space Mode
function transitionToSpace() {
gameState.mode = 'space';
gameState.position = { x: 400, y: 300 }; // Reset position or set to starting point in space
}
// UI Update
function loadUI() {
modeSpan.textContent = `Mode: ${gameState.mode.charAt(0).toUpperCase() + gameState.mode.slice(1)}`;
moneySpan.textContent = `Money: $${gameState.money}`;
partsSpan.textContent = `Parts: ${gameState.parts}`;
}
// Save and Load Features
saveBtn.addEventListener('click', () => {
const slot = saveSlots.value;
localStorage.setItem(slot, JSON.stringify(gameState));
alert(`Game saved to ${slot}`);
});
loadBtn.addEventListener('click', () => {
const slot = saveSlots.value;
const savedData = localStorage.getItem(slot);
if (savedData) {
gameState = JSON.parse(savedData);
alert(`Game loaded from ${slot}`);
} else {
alert(`No save found in ${slot}`);
}
});
// Initialize the Game on Page Load
window.onload = init;
Explanation and Features
-
Canvas Setup: The game uses HTML5 Canvas for rendering graphics. The canvas size is set to 800x600 pixels.
-
Game Modes: There are two modes—land and space. The player starts in land mode on a desert planet.
-
Player Movement: The player can move using W, A, S, D keys. Movement is handled by tracking key presses and updating the player's position accordingly.
-
Scavenging Ships: Randomly generated ships are scattered around the planet. When the player moves close to a ship (collision detection), they collect parts.
-
Purchasing a Ship: Once the player has enough parts (e.g., 50), they automatically purchase a ship and transition to space mode. You can enhance this by adding a shop interface.
-
Space Mode: In space mode, the player’s ship can move towards the space station. Upon arrival, you can implement additional interactions like taking jobs to earn money.
-
Random Generation: The planet's resources and ship positions are randomly generated each game session by using random numbers. This ensures a different experience each time.
-
Save and Load: The game state can be saved to and loaded from multiple slots using the browser’s localStorage. This allows players to have multiple saved games.
-
UI Elements: Basic UI displays the current mode, money, and parts. Buttons for saving and loading the game are provided, along with a dropdown to select save slots.
Enhancements and Next Steps
This is a foundational structure. To make the game more fully-featured and creative, consider implementing the following:
-
Enhanced Graphics: Use sprites or images instead of simple shapes for the player, ships, and space station.
-
Additional Game Mechanics:
- Economy: Implement buying and selling mechanics with fluctuating prices.
- Missions/Jobs: Add various missions in space to earn money.
- Inventory System: Allow players to manage collected parts and ship upgrades.
-
Multiple Planets: Generate multiple planets in the solar system with different environments and resources.
-
Animations: Add animations for movements, transitions, and interactions to make the game more visually appealing.
-
Sound Effects and Music: Incorporate sound to enhance the gaming experience.
-
Better Save System: Implement more robust save systems, possibly with serialization libraries or backend support for persistence across devices.
-
Responsive Design: Make the game responsive to different screen sizes and handle mobile controls if desired.
-
Error Handling: Add error checks, especially for saving and loading game state.
Using a Game Library
For a more scalable and feature-rich game, consider using a game development framework like Phaser.js. Phaser provides powerful tools for handling game physics, asset management, input, and more, significantly reducing the amount of boilerplate code you need to write.
Final Notes
Building a complete game involves iterative development, testing, and adding features incrementally. Start with the basic structure provided, then expand upon it by adding more features and refining the gameplay mechanics. Utilize version control (like Git) to track changes and collaborate if you're working with others.
Good luck with your game development journey!