@noirrzz/spacecraft-control
Version:
A spacecraft control system with power management and sensor capabilities
264 lines (230 loc) • 7.86 kB
JavaScript
// Required packages
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
// Constants and configurations
const PORT = 3000;
const VALID_ACTIONS = {
MOVE: ['forward', 'backward', 'stop'],
SENSORS: ['on', 'off'],
POWER: ['sleep', 'wake'],
FUEL: ['refuel']
};
const POWER_SETTINGS = {
MOVE_CONSUMPTION: 5, // Moving consumes 5% battery
WAKE_CONSUMPTION: 2 // Waking up consumes 2% battery
};
const FUEL_SETTINGS = {
MOVE_CONSUMPTION: 2, // Moving consumes 2% fuel
REFUEL_AMOUNT: 25 // Refuel adds 25% fuel
};
const POSSIBLE_SUBSTANCES = [
'Water', 'Methane', 'Carbon', 'Nitrogen', 'Iron Oxide',
'Silica', 'Aluminum Oxide', 'Calcium', 'Sulfur', 'Salt'
];
// Initial spacecraft state
let spacecraftStatus = {
power: 100, // Starting with full battery
speed: 0, // Starting at rest
fuel: 100, // Starting with full fuel
minerals: [], // Array to store detected minerals
groundSubstances: [], // Array to store detected ground substances
isAwake: true, // Track if spacecraft is awake
direction: 'stopped' // Track movement direction
};
// Helper Functions
function getRandomSubstances() {
const numSubstances = Math.floor(Math.random() * 3) + 1;
const substances = [];
for (let i = 0; i < numSubstances; i++) {
const randomIndex = Math.floor(Math.random() * POSSIBLE_SUBSTANCES.length);
const substance = POSSIBLE_SUBSTANCES[randomIndex];
if (!substances.includes(substance)) {
substances.push(substance);
}
}
return substances;
}
function canMove() {
if (!spacecraftStatus.isAwake) {
return {
allowed: false,
reason: 'Spacecraft is in sleep mode. Please wake it up first.'
};
}
if (spacecraftStatus.power < POWER_SETTINGS.MOVE_CONSUMPTION) {
return {
allowed: false,
reason: 'Insufficient power to move. Please charge in sleep mode.'
};
}
return { allowed: true };
}
// Express App Setup
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
// Route Handlers
function handleMove(value) {
if (!VALID_ACTIONS.MOVE.includes(value)) {
return {
error: 'Invalid move command',
validValues: VALID_ACTIONS.MOVE,
showMessage: false
};
}
const moveCheck = canMove();
if (value !== 'stop' && !moveCheck.allowed) {
return {
error: moveCheck.reason,
currentPower: `${spacecraftStatus.power}%`,
status: spacecraftStatus.isAwake ? 'Awake' : 'Sleep mode',
showMessage: true
};
}
if (value !== 'stop' && spacecraftStatus.fuel < FUEL_SETTINGS.MOVE_CONSUMPTION) {
return {
error: 'Insufficient fuel. Please refuel.',
showMessage: true
};
}
if (value === 'forward' || value === 'backward') {
spacecraftStatus.speed = 200; // Always positive speed
spacecraftStatus.direction = value; // Store direction separately
spacecraftStatus.power = Math.max(0, spacecraftStatus.power - POWER_SETTINGS.MOVE_CONSUMPTION);
spacecraftStatus.fuel = Math.max(0, spacecraftStatus.fuel - FUEL_SETTINGS.MOVE_CONSUMPTION);
spacecraftStatus.groundSubstances = getRandomSubstances();
} else {
spacecraftStatus.speed = 0;
spacecraftStatus.direction = 'stopped';
}
return null;
}
function handleSensors(value) {
if (!VALID_ACTIONS.SENSORS.includes(value)) {
return {
error: 'Invalid sensors command',
validValues: VALID_ACTIONS.SENSORS
};
}
if (value === 'on') {
spacecraftStatus.minerals = ['Iron', 'Copper', 'Silicon'];
spacecraftStatus.groundSubstances = getRandomSubstances();
} else {
spacecraftStatus.minerals = [];
spacecraftStatus.groundSubstances = [];
}
return null;
}
function handlePower(value) {
if (!VALID_ACTIONS.POWER.includes(value)) {
return {
error: 'Invalid power command',
validValues: VALID_ACTIONS.POWER
};
}
if (value === 'sleep') {
spacecraftStatus.speed = 0;
spacecraftStatus.isAwake = false;
spacecraftStatus.power = 100;
return {
success: true,
message: 'Battery fully charged',
status: 'Sleep mode - Fully Charged'
};
} else {
spacecraftStatus.isAwake = true;
spacecraftStatus.power = Math.max(0, spacecraftStatus.power - POWER_SETTINGS.WAKE_CONSUMPTION);
}
return null;
}
function handleFuel(value) {
if (!VALID_ACTIONS.FUEL.includes(value)) {
return {
error: 'Invalid fuel command',
validValues: VALID_ACTIONS.FUEL
};
}
if (value === 'refuel') {
if (spacecraftStatus.fuel >= 100) {
return {
error: 'Fuel tank is already full',
showMessage: true
};
}
spacecraftStatus.fuel = Math.min(100, spacecraftStatus.fuel + FUEL_SETTINGS.REFUEL_AMOUNT);
}
return null;
}
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/status', (req, res) => {
const formattedStatus = {
battery: `${spacecraftStatus.power}%`,
speed: `${spacecraftStatus.speed} km/h ${spacecraftStatus.direction !== 'stopped' ?
`(${spacecraftStatus.direction})` : ''}`,
fuel: `${spacecraftStatus.fuel}%`,
minerals: spacecraftStatus.minerals.length > 0
? spacecraftStatus.minerals.join(', ')
: 'No minerals detected',
groundSubstances: spacecraftStatus.groundSubstances.length > 0
? spacecraftStatus.groundSubstances.join(', ')
: 'No substances detected',
status: spacecraftStatus.isAwake ? 'Awake' : 'Sleep mode'
};
res.json(formattedStatus);
});
app.post('/action', (req, res) => {
const { action, value } = req.body;
if (!action) {
return res.status(400).json({ error: 'Action is required' });
}
let result;
switch (action.toLowerCase()) {
case 'move':
result = handleMove(value);
break;
case 'sensors':
result = handleSensors(value);
break;
case 'power':
result = handlePower(value);
break;
case 'fuel':
result = handleFuel(value);
break;
default:
result = {
error: 'Invalid action',
validActions: Object.keys(VALID_ACTIONS)
};
}
if (result && result.error) {
return res.status(400).json(result);
}
if (result && result.success) {
return res.json({
message: result.message,
currentStatus: spacecraftStatus,
powerStatus: `Battery at ${spacecraftStatus.power}%`,
fuelStatus: `Fuel at ${spacecraftStatus.fuel}%`,
status: result.status,
showMessage: true
});
}
res.json({
message: `Action '${action}' with value '${value}' executed successfully`,
currentStatus: spacecraftStatus,
powerStatus: `Battery at ${spacecraftStatus.power}%`,
fuelStatus: `Fuel at ${spacecraftStatus.fuel}%`,
status: spacecraftStatus.isAwake ? 'Awake' : 'Sleep mode',
showMessage: false
});
});
// Start Server
app.listen(PORT, () => {
console.log(`Spacecraft backend is running on http://localhost:${PORT}`);
});