snipercell_RL / gym /webXOS_snipercell_RL_gym.html
webxos's picture
Rename webXOS_snipercell_RL_gym (copy).html to gym/webXOS_snipercell_RL_gym.html
1e445bb verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XFORC3D: Snipercell RL by webXOS</title>
<!-- Load Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Load Line2 extensions for thick wireframes -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/lines/Line2.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/lines/LineGeometry.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/lines/LineMaterial.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/lines/LineSegments2.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/lines/LineSegmentsGeometry.js"></script>
<!-- JSZip for export functionality -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<!-- FileSaver for download -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<!-- 8-bit fonts -->
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Orbitron:wght@400;500;700&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #000;
overflow: hidden;
font-family: 'Press Start 2P', cursive;
color: #0f0;
cursor: crosshair;
image-rendering: pixelated;
}
#gameContainer {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
}
#gameCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}
/* 8-bit Loading Screen */
#loadingScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
z-index: 1000;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-family: 'Press Start 2P', cursive;
}
.loading-title {
font-size: 42px;
color: #0f0;
margin-bottom: 30px;
text-shadow:
0 0 10px #0f0,
0 0 20px #0f0;
animation: titleGlitch 3s infinite;
letter-spacing: 2px;
}
@keyframes titleGlitch {
0%, 100% { transform: translate(0, 0); }
2% { transform: translate(-2px, 1px); }
4% { transform: translate(2px, -1px); }
96% { transform: translate(0, 0); }
}
.loading-bar-container {
width: 400px;
height: 24px;
border: 4px solid #0f0;
background: #000;
margin: 20px 0;
position: relative;
overflow: hidden;
image-rendering: pixelated;
}
.loading-bar {
height: 100%;
width: 0%;
background: repeating-linear-gradient(
45deg,
#0f0,
#0f0 10px,
#0a0 10px,
#0a0 20px
);
transition: width 0.5s;
position: relative;
}
.loading-bar::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg,
transparent 0%,
rgba(255, 255, 255, 0.2) 50%,
transparent 100%);
animation: loadingShine 1.5s infinite;
}
@keyframes loadingShine {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
.loading-text {
font-size: 14px;
color: #0f0;
margin-top: 20px;
text-shadow: 0 0 5px #0f0;
}
.loading-dots {
display: inline-block;
width: 20px;
text-align: left;
}
.loading-dots::after {
content: '...';
animation: loadingDots 1.5s infinite;
}
@keyframes loadingDots {
0% { content: '.'; }
33% { content: '..'; }
66% { content: '...'; }
}
/* 8-bit Main Menu */
#mainMenu {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(circle at center, #001100 0%, #000 70%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 100;
font-family: 'Press Start 2P', cursive;
image-rendering: pixelated;
}
.menu-title {
font-size: 56px;
color: #0f0;
margin-bottom: 10px;
text-shadow:
0 0 10px #0f0,
0 0 20px #0f0,
0 0 30px #0f0;
letter-spacing: 4px;
animation: menuTitleGlow 2s infinite alternate;
margin-bottom: 30px;
}
@keyframes menuTitleGlow {
0% { text-shadow: 0 0 10px #0f0, 0 0 20px #0f0; }
100% { text-shadow: 0 0 15px #0f0, 0 0 30px #0f0, 0 0 40px #0f0; }
}
.menu-subtitle {
font-size: 14px;
color: #0f0;
margin-bottom: 60px;
opacity: 0.8;
letter-spacing: 1px;
text-shadow: 0 0 5px #0f0;
}
.menu-buttons {
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 40px;
}
.menu-btn {
padding: 16px 32px;
background: #000;
border: 3px solid #0f0;
color: #0f0;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
text-transform: uppercase;
letter-spacing: 2px;
font-family: 'Press Start 2P', cursive;
position: relative;
overflow: hidden;
image-rendering: pixelated;
}
.menu-btn::before {
content: '>';
position: absolute;
left: -20px;
opacity: 0;
transition: all 0.3s;
}
.menu-btn:hover::before {
left: 10px;
opacity: 1;
}
.menu-btn:hover {
background: #001100;
border-color: #0f0;
transform: scale(1.05);
box-shadow:
0 0 10px #0f0,
inset 0 0 10px #0f0;
}
.menu-btn:active {
transform: scale(0.95);
}
.menu-footer {
font-size: 10px;
color: #0a0;
opacity: 0.6;
margin-top: 20px;
text-align: center;
line-height: 1.5;
}
.menu-version {
font-size: 9px;
color: #090;
margin-top: 10px;
opacity: 0.5;
}
/* Clean Scope */
#scopeOverlay {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 320px;
transform: translate(-50%, -50%);
border-radius: 50%;
border: 4px solid #0f0;
box-shadow:
0 0 20px #0f0,
inset 0 0 20px #0f0;
z-index: 10;
display: none;
pointer-events: none;
overflow: hidden;
background: radial-gradient(
circle at center,
transparent 40%,
rgba(0, 20, 0, 0.95) 70%,
rgba(0, 5, 0, 0.99) 100%
);
image-rendering: pixelated;
}
.scope-reticle {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 260px;
height: 260px;
}
.reticle-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 6px;
height: 6px;
background: #0f0;
border-radius: 50%;
box-shadow: 0 0 10px #0f0;
}
.crosshair-line {
position: absolute;
background: #0f0;
box-shadow: 0 0 5px #0f0;
}
.crosshair-horizontal {
width: 220px;
height: 2px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.crosshair-vertical {
width: 2px;
height: 220px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 8-bit HUD - Reorganized */
.hud {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
pointer-events: none;
font-family: 'Press Start 2P', cursive;
image-rendering: pixelated;
}
/* Top Left Stats with EXP Bar */
.hud-top-left {
position: absolute;
top: 15px;
left: 15px;
display: flex;
flex-direction: column;
gap: 10px;
width: 320px;
}
/* Experience Bar - Top Left */
#experienceBar {
width: 100%;
height: 20px;
background: rgba(0, 5, 0, 0.95);
border: 3px solid #ff0;
overflow: hidden;
box-shadow: 0 0 15px rgba(255, 255, 0, 0.5);
position: relative;
}
.xp-fill {
height: 100%;
background: linear-gradient(90deg, #ff0 0%, #ffaa00 100%);
width: 0%;
transition: width 0.3s;
position: relative;
}
.xp-fill::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg,
transparent 0%,
rgba(255, 255, 255, 0.3) 50%,
transparent 100%);
animation: xpShine 2s infinite;
}
@keyframes xpShine {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
.xp-text {
position: absolute;
top: 50%;
left: 10px;
transform: translateY(-50%);
color: #000;
font-size: 10px;
white-space: nowrap;
text-shadow: 0 0 2px #fff;
font-weight: bold;
}
.xp-level {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
color: #000;
font-size: 10px;
text-shadow: 0 0 2px #fff;
font-weight: bold;
}
.level-up-glow {
animation: levelUpGlow 1s infinite;
box-shadow: 0 0 20px #ff0, 0 0 30px #ff0;
}
@keyframes levelUpGlow {
0%, 100% { box-shadow: 0 0 15px #ff0; }
50% { box-shadow: 0 0 30px #ff0, 0 0 40px #ff0; }
}
/* Stats below EXP bar */
.hud-stats-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin-top: 10px;
}
.hud-stat {
background: rgba(0, 10, 0, 0.9);
border: 3px solid #0f0;
padding: 8px 12px;
font-size: 11px;
color: #0f0;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
image-rendering: pixelated;
}
.hud-stat span {
color: #0ff;
text-shadow: 0 0 5px #0ff;
}
/* Top Right Stats */
.hud-right {
position: absolute;
top: 15px;
right: 15px;
display: flex;
flex-direction: column;
gap: 8px;
width: 320px;
}
/* Bottom Right Weapon Info */
.hud-weapon {
position: absolute;
bottom: 15px;
right: 15px;
background: rgba(0, 10, 0, 0.9);
border: 3px solid #0f0;
padding: 12px 18px;
font-size: 11px;
color: #0f0;
min-width: 220px;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
}
/* Crosshair */
.crosshair {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 24px;
height: 24px;
pointer-events: none;
z-index: 2;
}
.crosshair-dot {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 4px;
height: 4px;
background: #0f0;
border-radius: 50%;
box-shadow: 0 0 8px #0f0;
}
.crosshair-line {
position: absolute;
background: #0f0;
box-shadow: 0 0 3px #0f0;
}
.crosshair-line.horizontal {
width: 24px;
height: 2px;
top: 50%;
left: 0;
transform: translateY(-50%);
}
.crosshair-line.vertical {
width: 2px;
height: 24px;
top: 0;
left: 50%;
transform: translateX(-50%);
}
/* Hit Marker */
.hit-marker {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 30px;
height: 30px;
opacity: 0;
pointer-events: none;
z-index: 5;
transition: opacity 0.1s;
}
.hit-marker::before,
.hit-marker::after {
content: '';
position: absolute;
background: #f00;
box-shadow: 0 0 8px #f00;
}
.hit-marker::before {
width: 24px;
height: 3px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(45deg);
}
.hit-marker::after {
width: 24px;
height: 3px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-45deg);
}
/* Damage Text */
.damage-text {
position: absolute;
color: #ff0;
font-size: 16px;
font-weight: bold;
font-family: 'Press Start 2P', cursive;
opacity: 0;
pointer-events: none;
z-index: 6;
white-space: nowrap;
transition: all 0.5s;
text-shadow:
0 0 5px #ff0,
0 0 10px #ff0;
image-rendering: pixelated;
}
/* 8-bit Game Terminal */
#gameTerminal {
position: absolute;
bottom: 15px;
left: 15px;
width: 320px;
height: 160px;
background: rgba(0, 5, 0, 0.95);
border: 3px solid #0f0;
font-family: 'Press Start 2P', cursive;
font-size: 10px;
color: #0f0;
z-index: 10;
overflow: hidden;
box-shadow: 0 0 15px rgba(0, 255, 0, 0.3);
image-rendering: pixelated;
}
.terminal-header {
background: rgba(0, 20, 0, 0.95);
padding: 8px 12px;
border-bottom: 3px solid #0f0;
display: flex;
justify-content: space-between;
align-items: center;
}
.terminal-title {
color: #0f0;
font-size: 10px;
letter-spacing: 1px;
}
.terminal-status {
color: #0ff;
font-size: 9px;
text-shadow: 0 0 5px #0ff;
}
.terminal-content {
height: calc(100% - 35px);
padding: 10px;
overflow-y: auto;
line-height: 1.4;
}
.terminal-content::-webkit-scrollbar {
width: 6px;
}
.terminal-content::-webkit-scrollbar-track {
background: rgba(0, 20, 0, 0.5);
}
.terminal-content::-webkit-scrollbar-thumb {
background: #0f0;
border-radius: 0;
}
.terminal-entry {
margin-bottom: 6px;
padding: 4px 0;
border-bottom: 1px dashed rgba(0, 255, 0, 0.3);
animation: entrySlide 0.3s;
}
@keyframes entrySlide {
from { transform: translateX(-10px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.entry-time {
color: #0ff;
margin-right: 10px;
font-size: 8px;
}
.entry-type {
display: inline-block;
margin-right: 8px;
padding: 2px 6px;
background: rgba(0, 30, 0, 0.8);
border: 2px solid;
font-size: 8px;
}
.type-info { color: #0f0; border-color: #0f0; }
.type-warning { color: #ff0; border-color: #ff0; }
.type-error { color: #f00; border-color: #f00; }
.type-success { color: #0f0; border-color: #0f0; }
.type-level { color: #f0f; border-color: #f0f; }
.type-combat { color: #ff8800; border-color: #ff8800; }
/* Jetpack Bar */
.jetpack-bar {
position: absolute;
bottom: 50px;
left: 50%;
transform: translateX(-50%);
width: 220px;
height: 8px;
background: rgba(0, 5, 0, 0.95);
border: 2px solid #0f0;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
}
.jetpack-fill {
width: 100%;
height: 100%;
background: #0a0;
transition: width 0.1s;
}
.jetpack-label {
position: absolute;
top: -18px;
left: 0;
color: #0f0;
font-size: 9px;
opacity: 0.8;
}
/* Save Indicator */
.save-indicator {
position: absolute;
top: 15px;
left: 50%;
transform: translateX(-50%);
color: #0f0;
font-size: 11px;
background: rgba(0, 15, 0, 0.95);
padding: 8px 16px;
border: 2px solid #0f0;
opacity: 0;
transition: opacity 0.5s;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
}
/* Export Button */
#exportBtn {
margin-top: 20px;
padding: 10px 20px;
background: #000;
border: 3px solid #0ff;
color: #0ff;
font-size: 12px;
cursor: pointer;
font-family: 'Press Start 2P', cursive;
text-transform: uppercase;
transition: all 0.2s;
}
#exportBtn:hover {
background: #003333;
transform: scale(1.05);
box-shadow: 0 0 10px #0ff;
}
/* Mobile Warning */
.mobile-warning {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.95);
color: #f00;
padding: 30px;
border: 4px solid #f00;
text-align: center;
z-index: 1000;
font-size: 16px;
max-width: 80%;
line-height: 1.5;
font-family: 'Press Start 2P', cursive;
}
@media (max-width: 768px) {
.mobile-warning {
display: block;
}
#scopeOverlay {
width: 250px;
height: 250px;
}
.scope-reticle {
width: 180px;
height: 180px;
}
.crosshair-horizontal {
width: 140px;
}
.crosshair-vertical {
height: 140px;
}
.menu-title {
font-size: 32px;
}
#gameTerminal, #experienceBar {
width: 90%;
}
}
</style>
</head>
<body>
<!-- Loading Screen -->
<div id="loadingScreen">
<div class="loading-title">webXOS: Snipercell RL Gym v1.0</div>
<div class="loading-bar-container">
<div class="loading-bar" id="loadingBar"></div>
</div>
<div class="loading-text">
INITIALIZING SYSTEM<span class="loading-dots"></span>
</div>
</div>
<div id="gameContainer">
<!-- 8-bit Main Menu -->
<div id="mainMenu">
<div class="menu-title">webXOS: Snipercell RL Gym v1.0</div>
<div class="menu-subtitle">reinforcement learning based gaming.</div>
<div class="menu-buttons">
<button class="menu-btn" id="startBtn">START TRAINING</button>
<button class="menu-btn" id="continueBtn">CONTINUE</button>
<button class="menu-btn" id="controlsBtn">CONTROLS</button>
</div>
<div class="menu-footer">
> THREE JS GAMING <br>
> LEVEL 1-99 AND FIGHT DRONES<br>
> SURVIVE AND LEVEL UP
</div>
<div class="menu-version">v1.0 | webXOS Games 2025</div>
<button id="exportBtn">EXPORT TRAINING DATA</button>
</div>
<!-- Game Canvas -->
<canvas id="gameCanvas"></canvas>
<!-- Scope Overlay -->
<div id="scopeOverlay">
<div class="scope-reticle">
<div class="reticle-center"></div>
<div class="crosshair-line crosshair-horizontal"></div>
<div class="crosshair-line crosshair-vertical"></div>
<div class="scope-readout" id="scopeReadout">ZOOM: 4x</div>
</div>
</div>
<!-- HUD -->
<div class="hud">
<!-- Top Left Stats with EXP Bar -->
<div class="hud-top-left">
<!-- Experience Bar -->
<div id="experienceBar">
<div class="xp-fill" id="xpFill"></div>
<div class="xp-text" id="xpText">XP: 0/1000</div>
<div class="xp-level">Lv.<span id="currentLevel">1</span></div>
</div>
<!-- Stats Grid -->
<div class="hud-stats-container">
<div class="hud-stat">LEVEL: <span id="level">1</span></div>
<div class="hud-stat">WAVE: <span id="wave">1</span></div>
<div class="hud-stat">DRONES: <span id="drones">0</span>/<span id="maxDrones">4</span></div>
<div class="hud-stat">DMG: <span id="damage">100</span></div>
</div>
</div>
<!-- Top Right Stats -->
<div class="hud-right">
<div class="hud-stat">ACCURACY: <span id="accuracy">0%</span></div>
<div class="hud-stat">KILLS: <span id="dronesDestroyed">0</span></div>
<div class="hud-stat">SHOTS: <span id="shotsFired">0</span></div>
<div class="hud-stat">HITS: <span id="shotsHit">0</span></div>
</div>
<!-- Bottom Right Weapon -->
<div class="hud-weapon">
<span id="fireMode">NORMAL (LMB SHOOT)</span>
</div>
<!-- Game Terminal -->
<div id="gameTerminal">
<div class="terminal-header">
<div class="terminal-title">SYSTEM LOG</div>
<div class="terminal-status">ONLINE</div>
</div>
<div class="terminal-content" id="terminalContent">
<!-- Terminal entries will be added here -->
</div>
</div>
<!-- Crosshair -->
<div class="crosshair" id="crosshair">
<div class="crosshair-dot"></div>
<div class="crosshair-line horizontal"></div>
<div class="crosshair-line vertical"></div>
</div>
<!-- Hit Marker -->
<div class="hit-marker" id="hitMarker"></div>
<!-- Jetpack Bar -->
<div class="jetpack-bar">
<div class="jetpack-label">JETPACK</div>
<div class="jetpack-fill" id="jetpackFill"></div>
</div>
<!-- Save Indicator -->
<div class="save-indicator" id="saveIndicator">GAME SAVED</div>
<!-- Controls Info -->
<div style="position: absolute; bottom: 5px; right: 5px; font-size: 9px; color: #0f0; opacity: 0.5;">
WASD + MOUSE
</div>
</div>
<!-- Mobile Warning -->
<div class="mobile-warning">
DESKTOP ONLY<br>Requires mouse and keyboard<br>
<em>Click START MISSION then click game screen</em>
</div>
<!-- Damage Text Container -->
<div id="damageContainer"></div>
</div>
<script>
// ============================
// XFORC3D: TIERED DRONE SYSTEM
// ============================
// Game State
const GameState = {
LOADING: 0,
MENU: 1,
PLAYING: 2,
PAUSED: 3
};
let currentState = GameState.LOADING;
let mouseSensitivity = 0.002;
let zoomed = false;
let pointerLocked = false;
let canFire = true;
let sprinting = false;
let jetpackActive = false;
let jetpackFuel = 100;
let jetpackConsumption = 22;
let jetpackRefillRate = 28;
let isGrounded = false;
let lastFireTime = 0;
let lastSaveTime = 0;
let keyState = {};
let movementEnabled = true;
// Mouse button state
let mouseButtons = {
left: false,
right: false
};
// Physics
const GRAVITY = 9.8;
const JETPACK_FORCE = 16;
const SPRINT_MULTIPLIER = 2.4;
const BASE_SPEED = 12;
const AIR_CONTROL = 0.65;
const FRICTION = 0.86;
// Camera settings
const ZOOM_FOV = 75 / 3.5;
const NORMAL_FOV = 75;
let targetFOV = NORMAL_FOV;
// Three.js variables
let scene, camera, renderer;
let player, sniperRifle, drones = [], projectiles = [], particles = [];
let buildings = [], buildingColliders = [], buildingTops = [], grid = null;
// Line material for thick wireframes
let thickLineMaterial;
// XP System Variables
let level = 1;
let xp = 0;
let totalXP = 0;
let nextXp = 1000;
let wave = 1;
let droneKills = 0;
let dronesToNextWave = 6;
let dronesDestroyedTotal = 0;
// Weapon stats
let damage = 100;
let fireRate = 0.1;
let projectileSpeed = 400;
// Game stats
let stats = {
shotsFired: 0,
shotsHit: 0,
dronesDestroyed: 0,
totalDrones: 0,
accuracy: 0,
maxDrones: 4 // Start with 4 drones for level 1
};
// Training data collection
let trainingData = {
sessions: [],
shots: [],
hits: [],
levelUps: [],
waves: [],
currentSession: {
startTime: null,
endTime: null,
totalXP: 0,
levelsGained: 0,
wavesCompleted: 0
}
};
// XP Loss penalty rate - 25% of damage taken
const XP_LOSS_RATE = 0.25;
// Environment settings
const BUILDING_GRID_SIZE = 240;
const BUILDING_MIN_DISTANCE = 35;
const BUILDING_CELL_SIZE = 40;
const PLAYER_SPAWN_RADIUS = 20;
const DRONE_SPAWN_RADIUS = 80;
const PLAY_AREA_RADIUS = 150;
// Physics
let playerVelocity = new THREE.Vector3();
let playerCollider;
// Loading progress
let loadingProgress = 0;
let loadingSteps = 10;
let currentStep = 0;
// Calculate max drones based on level tier
function getMaxDronesForLevel(currentLevel) {
if (currentLevel <= 10) {
// Levels 1-10: 4-5 drones max
return currentLevel <= 5 ? 4 : 5;
} else if (currentLevel <= 20) {
// Levels 11-20: 6 drones max
return 6;
} else if (currentLevel <= 30) {
// Levels 21-30: 7 drones max
return 7;
} else if (currentLevel <= 40) {
// Levels 31-40: 8 drones max
return 8;
} else if (currentLevel <= 50) {
// Levels 41-50: 9 drones max
return 9;
} else {
// Levels 51-99: 10 drones max
return 10;
}
}
// Update loading screen
function updateLoadingScreen(step, message) {
currentStep = step;
loadingProgress = (step / loadingSteps) * 100;
const loadingBar = document.getElementById('loadingBar');
const loadingText = document.querySelector('.loading-text');
if (loadingBar) {
loadingBar.style.width = `${loadingProgress}%`;
}
if (message && loadingText) {
loadingText.innerHTML = `${message}<span class="loading-dots"></span>`;
}
}
// Simulate loading
function simulateLoading() {
const loadingMessages = [
"LOADING ENGINE",
"INITIALIZING GRAPHICS",
"GENERATING TERRAIN",
"BUILDING STRUCTURES",
"CALIBRATING WEAPONS",
"SPAWNING DRONES",
"SYNCHRONIZING HUD",
"ESTABLISHING CONNECTION",
"VERIFYING INTEGRITY",
"LAUNCHING SIMULATION"
];
let step = 0;
const interval = setInterval(() => {
if (step < loadingSteps) {
updateLoadingScreen(step + 1, loadingMessages[step]);
step++;
} else {
clearInterval(interval);
completeLoading();
}
}, 300);
}
// Complete loading
function completeLoading() {
setTimeout(() => {
const loadingScreen = document.getElementById('loadingScreen');
const mainMenu = document.getElementById('mainMenu');
if (loadingScreen) loadingScreen.style.display = 'none';
if (mainMenu) mainMenu.style.display = 'flex';
currentState = GameState.MENU;
logToTerminal('System fully operational', 'success');
}, 500);
}
// Terminal logging
function logToTerminal(message, type = 'info') {
const terminalContent = document.getElementById('terminalContent');
if (!terminalContent) return;
const entry = document.createElement('div');
entry.className = 'terminal-entry';
const time = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
const typeClass = `type-${type}`;
entry.innerHTML = `
<span class="entry-time">[${time}]</span>
<span class="entry-type ${typeClass}">${type.toUpperCase()}</span>
${message}
`;
terminalContent.appendChild(entry);
terminalContent.scrollTop = terminalContent.scrollHeight;
const maxEntries = 30;
if (terminalContent.children.length > maxEntries) {
terminalContent.removeChild(terminalContent.firstChild);
}
}
// Calculate XP required for a specific level (1-99)
function getXPForLevel(targetLevel) {
if (targetLevel <= 1) return 0;
let requiredXP = 0;
const baseXP = 1000;
const growthRate = 1.18;
for (let i = 1; i < targetLevel; i++) {
requiredXP += Math.floor(baseXP * Math.pow(growthRate, i - 1));
}
return requiredXP;
}
// Calculate XP needed for next level from current level
function getXPForNextLevel(currentLevel) {
const baseXP = 1000;
const growthRate = 1.18;
return Math.floor(baseXP * Math.pow(growthRate, currentLevel - 1));
}
// Check if position is valid for building
function isValidBuildingPosition(position, width, depth, existingBuildings) {
const distanceFromCenter = Math.sqrt(position.x * position.x + position.z * position.z);
if (distanceFromCenter < PLAYER_SPAWN_RADIUS) {
return false;
}
for (const building of existingBuildings) {
const dx = Math.abs(position.x - building.position.x);
const dz = Math.abs(position.z - building.position.z);
const minDistance = (width + building.width) * 0.5 + BUILDING_MIN_DISTANCE;
if (dx < minDistance && dz < minDistance) {
return false;
}
}
return true;
}
// Get a valid drone spawn position
function getValidDroneSpawnPosition() {
const maxAttempts = 50;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const angle = (Math.PI * 2 / Math.max(1, drones.length + 1)) * attempt + Math.random() * 0.5;
const distance = PLAY_AREA_RADIUS - 20 + Math.random() * 40;
const x = Math.cos(angle) * distance;
const z = Math.sin(angle) * distance;
const y = 35 + Math.random() * 40 + wave * 4;
const spawnPosition = new THREE.Vector3(x, y, z);
let isClear = true;
for (const collider of buildingColliders) {
const box = new THREE.Box3().setFromObject(collider);
const sphere = new THREE.Sphere(spawnPosition, 3.0);
if (box.intersectsSphere(sphere)) {
isClear = false;
break;
}
}
for (const drone of drones) {
if (spawnPosition.distanceTo(drone.position) < 25) {
isClear = false;
break;
}
}
if (player && spawnPosition.distanceTo(player.position) < DRONE_SPAWN_RADIUS * 0.6) {
isClear = false;
}
if (isClear) {
return spawnPosition;
}
}
const fallbackAngle = Math.random() * Math.PI * 2;
return new THREE.Vector3(
Math.cos(fallbackAngle) * 120,
60 + wave * 5,
Math.sin(fallbackAngle) * 120
);
}
// Check building collision with sphere
function checkBuildingCollision(position, radius) {
for (const collider of buildingColliders) {
const box = new THREE.Box3().setFromObject(collider);
const sphere = new THREE.Sphere(position, radius);
if (box.intersectsSphere(sphere)) {
return {
collided: true,
box: box,
building: collider
};
}
}
return { collided: false };
}
// Check if player is on top of a building
function checkBuildingTopCollision(position) {
for (let i = 0; i < buildingColliders.length; i++) {
const collider = buildingColliders[i];
const box = new THREE.Box3().setFromObject(collider);
if (position.x >= box.min.x && position.x <= box.max.x &&
position.z >= box.min.z && position.z <= box.max.z &&
position.y >= box.max.y - 0.5 && position.y <= box.max.y + 2.0) {
return {
onTop: true,
topY: box.max.y,
building: collider
};
}
}
return { onTop: false };
}
// Initialize the game - FIXED VERSION
function init() {
try {
// First, check if mobile
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
document.querySelector('.mobile-warning').style.display = 'block';
document.getElementById('loadingScreen').style.display = 'none';
return;
}
// Start loading simulation
simulateLoading();
// Setup event listeners first
setupEventListeners();
// Then load saved game
loadGame();
// Start animation loop
requestAnimationFrame(animate);
} catch (error) {
console.error("Initialization error:", error);
logToTerminal(`Error: ${error.message}`, 'error');
}
}
// Initialize Three.js scene - Separated from main init
function initThreeJS() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
scene.fog = new THREE.Fog(0x000000, 60, 500);
// Create main camera
camera = new THREE.PerspectiveCamera(NORMAL_FOV, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create main renderer
const canvas = document.getElementById('gameCanvas');
renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: false,
powerPreference: "high-performance",
alpha: false,
stencil: false,
depth: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1));
renderer.shadowMap.enabled = false;
// Create thick line material
thickLineMaterial = new THREE.LineMaterial({
color: 0x00ff00,
linewidth: 2,
vertexColors: false,
alphaToCoverage: false,
worldUnits: false,
dashed: false,
opacity: 1,
transparent: false,
resolution: new THREE.Vector2(window.innerWidth, window.innerHeight)
});
// Simple lighting
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
logToTerminal('Three.js initialized', 'success');
return true;
}
// Create thick wireframe box
function createThickWireframeBox(width, height, depth, color = 0x00ff00) {
const geometry = new THREE.BoxGeometry(width, height, depth);
const edges = new THREE.EdgesGeometry(geometry);
const positions = [];
const attrPos = edges.attributes.position;
for (let i = 0; i < attrPos.count; i += 2) {
positions.push(
attrPos.getX(i), attrPos.getY(i), attrPos.getZ(i),
attrPos.getX(i + 1), attrPos.getY(i + 1), attrPos.getZ(i + 1)
);
}
const lineGeometry = new THREE.LineSegmentsGeometry();
lineGeometry.setPositions(positions);
const material = thickLineMaterial.clone();
material.color.set(color);
material.linewidth = 2;
const line = new THREE.LineSegments2(lineGeometry, material);
return line;
}
// Create Halo-inspired sniper rifle
function createHaloSniperRifle() {
const rifle = new THREE.Group();
// Main body
const bodyGeometry = new THREE.CylinderGeometry(0.12, 0.12, 1.8, 10);
const bodyEdges = new THREE.EdgesGeometry(bodyGeometry);
const bodyPositions = [];
const bodyAttrPos = bodyEdges.attributes.position;
for (let i = 0; i < bodyAttrPos.count; i += 2) {
bodyPositions.push(
bodyAttrPos.getX(i), bodyAttrPos.getY(i), bodyAttrPos.getZ(i),
bodyAttrPos.getX(i + 1), bodyAttrPos.getY(i + 1), bodyAttrPos.getZ(i + 1)
);
}
const bodyLineGeometry = new THREE.LineSegmentsGeometry();
bodyLineGeometry.setPositions(bodyPositions);
const bodyMaterial = thickLineMaterial.clone();
bodyMaterial.color.set(0x00ff00);
bodyMaterial.linewidth = 2;
const body = new THREE.LineSegments2(bodyLineGeometry, bodyMaterial);
body.rotation.x = Math.PI / 2;
body.position.set(0, -0.2, -0.5);
rifle.add(body);
// Barrel
const barrelGeometry = new THREE.CylinderGeometry(0.06, 0.06, 3.0, 8);
const barrelEdges = new THREE.EdgesGeometry(barrelGeometry);
const barrelPositions = [];
const barrelAttrPos = barrelEdges.attributes.position;
for (let i = 0; i < barrelAttrPos.count; i += 2) {
barrelPositions.push(
barrelAttrPos.getX(i), barrelAttrPos.getY(i), barrelAttrPos.getZ(i),
barrelAttrPos.getX(i + 1), barrelAttrPos.getY(i + 1), barrelAttrPos.getZ(i + 1)
);
}
const barrelLineGeometry = new THREE.LineSegmentsGeometry();
barrelLineGeometry.setPositions(barrelPositions);
const barrelMaterial = thickLineMaterial.clone();
barrelMaterial.color.set(0x00ff00);
barrelMaterial.linewidth = 1.5;
const barrel = new THREE.LineSegments2(barrelLineGeometry, barrelMaterial);
barrel.rotation.x = Math.PI / 2;
barrel.position.set(0, -0.2, -2.0);
rifle.add(barrel);
// Scope base
const scopeBaseGeometry = new THREE.BoxGeometry(0.25, 0.15, 0.4);
const scopeBaseEdges = new THREE.EdgesGeometry(scopeBaseGeometry);
const scopeBasePositions = [];
const scopeBaseAttrPos = scopeBaseEdges.attributes.position;
for (let i = 0; i < scopeBaseAttrPos.count; i += 2) {
scopeBasePositions.push(
scopeBaseAttrPos.getX(i), scopeBaseAttrPos.getY(i), scopeBaseAttrPos.getZ(i),
scopeBaseAttrPos.getX(i + 1), scopeBaseAttrPos.getY(i + 1), scopeBaseAttrPos.getZ(i + 1)
);
}
const scopeBaseLineGeometry = new THREE.LineSegmentsGeometry();
scopeBaseLineGeometry.setPositions(scopeBasePositions);
const scopeBase = new THREE.LineSegments2(scopeBaseLineGeometry, thickLineMaterial.clone());
scopeBase.position.set(0, 0.25, -0.5);
rifle.add(scopeBase);
// Scope tube
const scopeTubeGeometry = new THREE.CylinderGeometry(0.08, 0.08, 0.6, 8);
const scopeTubeEdges = new THREE.EdgesGeometry(scopeTubeGeometry);
const scopeTubePositions = [];
const scopeTubeAttrPos = scopeTubeEdges.attributes.position;
for (let i = 0; i < scopeTubeAttrPos.count; i += 2) {
scopeTubePositions.push(
scopeTubeAttrPos.getX(i), scopeTubeAttrPos.getY(i), scopeTubeAttrPos.getZ(i),
scopeTubeAttrPos.getX(i + 1), scopeTubeAttrPos.getY(i + 1), scopeTubeAttrPos.getZ(i + 1)
);
}
const scopeTubeLineGeometry = new THREE.LineSegmentsGeometry();
scopeTubeLineGeometry.setPositions(scopeTubePositions);
const scopeTube = new THREE.LineSegments2(scopeTubeLineGeometry, thickLineMaterial.clone());
scopeTube.position.set(0, 0.25, -0.5);
scopeTube.rotation.x = Math.PI / 2;
rifle.add(scopeTube);
// Stock
const stockGeometry = new THREE.CylinderGeometry(0.15, 0.18, 0.8, 8);
const stockEdges = new THREE.EdgesGeometry(stockGeometry);
const stockPositions = [];
const stockAttrPos = stockEdges.attributes.position;
for (let i = 0; i < stockAttrPos.count; i += 2) {
stockPositions.push(
stockAttrPos.getX(i), stockAttrPos.getY(i), stockAttrPos.getZ(i),
stockAttrPos.getX(i + 1), stockAttrPos.getY(i + 1), stockAttrPos.getZ(i + 1)
);
}
const stockLineGeometry = new THREE.LineSegmentsGeometry();
stockLineGeometry.setPositions(stockPositions);
const stock = new THREE.LineSegments2(stockLineGeometry, thickLineMaterial.clone());
stock.position.set(0, -0.2, 0.4);
stock.rotation.x = Math.PI / 2;
rifle.add(stock);
// Magazine
const magGeometry = new THREE.BoxGeometry(0.2, 0.4, 0.15);
const magEdges = new THREE.EdgesGeometry(magGeometry);
const magPositions = [];
const magAttrPos = magEdges.attributes.position;
for (let i = 0; i < magAttrPos.count; i += 2) {
magPositions.push(
magAttrPos.getX(i), magAttrPos.getY(i), magAttrPos.getZ(i),
magAttrPos.getX(i + 1), magAttrPos.getY(i + 1), magAttrPos.getZ(i + 1)
);
}
const magLineGeometry = new THREE.LineSegmentsGeometry();
magLineGeometry.setPositions(magPositions);
const magazine = new THREE.LineSegments2(magLineGeometry, thickLineMaterial.clone());
magazine.position.set(0, -0.4, -0.3);
rifle.add(magazine);
// Trigger guard
const triggerGeometry = new THREE.BoxGeometry(0.15, 0.1, 0.08);
const triggerEdges = new THREE.EdgesGeometry(triggerGeometry);
const triggerPositions = [];
const triggerAttrPos = triggerEdges.attributes.position;
for (let i = 0; i < triggerAttrPos.count; i += 2) {
triggerPositions.push(
triggerAttrPos.getX(i), triggerAttrPos.getY(i), triggerAttrPos.getZ(i),
triggerAttrPos.getX(i + 1), triggerAttrPos.getY(i + 1), triggerAttrPos.getZ(i + 1)
);
}
const triggerLineGeometry = new THREE.LineSegmentsGeometry();
triggerLineGeometry.setPositions(triggerPositions);
const trigger = new THREE.LineSegments2(triggerLineGeometry, thickLineMaterial.clone());
trigger.position.set(0, -0.25, 0.1);
rifle.add(trigger);
// Final rifle positioning
rifle.position.set(0.5, -0.3, -1.0);
rifle.rotation.y = Math.PI;
return rifle;
}
// Create player
function createPlayer() {
player = new THREE.Object3D();
// Start in center with clear space
player.position.set(0, 5, 0);
player.rotation.y = Math.PI;
scene.add(player);
// Player collider
const playerColliderGeometry = new THREE.SphereGeometry(0.55, 8, 8);
const playerColliderMaterial = new THREE.MeshBasicMaterial({
color: 0x00ff00,
wireframe: true,
visible: false
});
playerCollider = new THREE.Mesh(playerColliderGeometry, playerColliderMaterial);
player.userData.collider = playerCollider;
player.add(player.userData.collider);
camera.position.set(0, 0, 0);
player.add(camera);
// Create Halo-inspired sniper rifle
sniperRifle = createHaloSniperRifle();
camera.add(sniperRifle);
updateHUD();
logToTerminal('Player spawned in clear area', 'success');
}
// Create environment with solid buildings
function createEnvironment() {
// Clear existing buildings
if (buildings.length > 0) {
buildings.forEach(b => scene.remove(b));
buildingColliders.forEach(c => scene.remove(c));
buildingTops.forEach(t => scene.remove(t));
buildings = [];
buildingColliders = [];
buildingTops = [];
}
// Create grid floor
const gridSize = 650;
const gridDivisions = 50;
const gridGeometry = new THREE.PlaneGeometry(gridSize, gridSize, gridDivisions, gridDivisions);
const edges = new THREE.EdgesGeometry(gridGeometry);
const gridPositions = [];
const attrPos = edges.attributes.position;
for (let i = 0; i < attrPos.count; i += 2) {
gridPositions.push(
attrPos.getX(i), attrPos.getY(i), attrPos.getZ(i),
attrPos.getX(i + 1), attrPos.getY(i + 1), attrPos.getZ(i + 1)
);
}
const lineGeometry = new THREE.LineSegmentsGeometry();
lineGeometry.setPositions(gridPositions);
const gridMaterial = thickLineMaterial.clone();
gridMaterial.color.set(0x00aa00);
gridMaterial.opacity = 0.1;
gridMaterial.transparent = true;
gridMaterial.linewidth = 1;
grid = new THREE.LineSegments2(lineGeometry, gridMaterial);
grid.rotation.x = -Math.PI / 2;
grid.position.y = 0;
scene.add(grid);
buildings.push(grid);
// Create buildings with solid collision
const buildingCount = 18 + wave * 2;
const placedBuildings = [];
for (let i = 0; i < buildingCount * 4; i++) {
if (placedBuildings.length >= buildingCount) break;
const cellX = Math.floor(Math.random() * BUILDING_GRID_SIZE / BUILDING_CELL_SIZE) - BUILDING_GRID_SIZE / (2 * BUILDING_CELL_SIZE);
const cellZ = Math.floor(Math.random() * BUILDING_GRID_SIZE / BUILDING_CELL_SIZE) - BUILDING_GRID_SIZE / (2 * BUILDING_CELL_SIZE);
const x = (cellX + (Math.random() * 0.6 - 0.3)) * BUILDING_CELL_SIZE;
const z = (cellZ + (Math.random() * 0.6 - 0.3)) * BUILDING_CELL_SIZE;
const width = 16 + Math.random() * 18;
const height = 45 + Math.random() * 55 + wave * 4;
const depth = 16 + Math.random() * 18;
const position = new THREE.Vector3(x, height / 2, z);
if (isValidBuildingPosition(position, width, depth, placedBuildings)) {
// Create building wireframe
const building = createThickWireframeBox(width, height, depth, 0x00ff00);
building.position.set(x, height / 2, z);
building.width = width;
building.depth = depth;
building.position = position;
scene.add(building);
buildings.push(building);
// Create SOLID collision box
const colliderGeometry = new THREE.BoxGeometry(width * 0.95, height * 0.95, depth * 0.95);
const colliderMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
wireframe: false,
transparent: true,
opacity: 0.0
});
const collider = new THREE.Mesh(colliderGeometry, colliderMaterial);
collider.position.set(x, height / 2, z);
collider.userData.type = 'building';
collider.userData.width = width;
collider.userData.height = height;
collider.userData.depth = depth;
scene.add(collider);
buildingColliders.push(collider);
// Create top surface indicator
const topGeometry = new THREE.BoxGeometry(width * 0.9, 0.5, depth * 0.9);
const topEdges = new THREE.EdgesGeometry(topGeometry);
const topPositions = [];
const topAttrPos = topEdges.attributes.position;
for (let j = 0; j < topAttrPos.count; j += 2) {
topPositions.push(
topAttrPos.getX(j), topAttrPos.getY(j), topAttrPos.getZ(j),
topAttrPos.getX(j + 1), topAttrPos.getY(j + 1), topAttrPos.getZ(j + 1)
);
}
const topLineGeometry = new THREE.LineSegmentsGeometry();
topLineGeometry.setPositions(topPositions);
const topMaterial = thickLineMaterial.clone();
topMaterial.color.set(0x00aa00);
topMaterial.opacity = 0.3;
topMaterial.transparent = true;
topMaterial.linewidth = 1;
const top = new THREE.LineSegments2(topLineGeometry, topMaterial);
top.position.set(x, height, z);
scene.add(top);
buildingTops.push(top);
placedBuildings.push({
position: position,
width: width,
depth: depth,
height: height
});
}
}
// Add distant buildings
for (let i = 0; i < 6; i++) {
const angle = Math.random() * Math.PI * 2;
const distance = 180 + Math.random() * 60;
const x = Math.cos(angle) * distance;
const z = Math.sin(angle) * distance;
const width = 25 + Math.random() * 30;
const height = 90 + Math.random() * 80;
const depth = 25 + Math.random() * 30;
const building = createThickWireframeBox(width, height, depth, 0x00aa00);
building.position.set(x, height / 2, z);
scene.add(building);
buildings.push(building);
const colliderGeometry = new THREE.BoxGeometry(width * 0.95, height * 0.95, depth * 0.95);
const colliderMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
wireframe: false,
transparent: true,
opacity: 0.0
});
const collider = new THREE.Mesh(colliderGeometry, colliderMaterial);
collider.position.set(x, height / 2, z);
collider.userData.type = 'building';
scene.add(collider);
buildingColliders.push(collider);
}
// Create stars
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({
color: 0x00ff00,
size: 0.6,
sizeAttenuation: true
});
const starVertices = [];
for (let i = 0; i < 600; i++) {
starVertices.push(
(Math.random() - 0.5) * 1500,
(Math.random() - 0.5) * 1500,
(Math.random() - 0.5) * 1500
);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
buildings.push(stars);
logToTerminal(`Environment created - ${placedBuildings.length} solid buildings`, 'info');
}
// Create spherical wireframe projectile
function createSphericalWireframe(radius, color = 0x00ff00, detail = 3) {
const geometry = new THREE.IcosahedronGeometry(radius, detail);
const edges = new THREE.EdgesGeometry(geometry);
const positions = [];
const attrPos = edges.attributes.position;
for (let i = 0; i < attrPos.count; i += 2) {
positions.push(
attrPos.getX(i), attrPos.getY(i), attrPos.getZ(i),
attrPos.getX(i + 1), attrPos.getY(i + 1), attrPos.getZ(i + 1)
);
}
const lineGeometry = new THREE.LineSegmentsGeometry();
lineGeometry.setPositions(positions);
const material = thickLineMaterial.clone();
material.color.set(color);
material.linewidth = 1.5;
const sphere = new THREE.LineSegments2(lineGeometry, material);
return sphere;
}
// Create drone with larger hitbox
function createDrone() {
const drone = new THREE.Group();
// Larger drone size for easier hitting
const body = createThickWireframeBox(2.8, 2.8, 2.8, 0xff0000);
drone.add(body);
const spawnPosition = getValidDroneSpawnPosition();
drone.position.copy(spawnPosition);
// DRONE PROPERTIES - 2 HIT SYSTEM
drone.health = damage * 2;
drone.maxHealth = damage * 2;
drone.speed = 1.2 + Math.random() * 1.5;
drone.lastFire = 0;
drone.fireRate = 2000 + Math.random() * 1000;
drone.projectileSpeed = 40;
drone.damage = 10 + wave * 3;
drone.id = drones.length;
drone.bobSpeed = 0.0005 + Math.random() * 0.001;
drone.bobHeight = 0.2;
drone.bobTime = Math.random() * 1000;
drone.rotationSpeeds = {
x: 0.2 + Math.random() * 0.3,
y: 0.3 + Math.random() * 0.3,
z: 0.1 + Math.random() * 0.2
};
drone.avoidanceRadius = 20;
drone.avoidanceForce = 3.0;
// LARGER hitbox for drone
drone.userData.collider = new THREE.Sphere(new THREE.Vector3(), 2.8);
scene.add(drone);
drones.push(drone);
stats.totalDrones++;
// Record drone creation in training data
trainingData.shots.push({
timestamp: Date.now(),
type: 'drone_spawn',
wave: wave,
level: level,
drone_id: drone.id,
position: {x: drone.position.x, y: drone.position.y, z: drone.position.z}
});
return drone;
}
// Update drones with solid building avoidance
function updateDrones(delta) {
for (let i = drones.length - 1; i >= 0; i--) {
const drone = drones[i];
if (!drone) continue;
drone.bobTime += delta * 1000;
drone.position.y += Math.sin(drone.bobTime * drone.bobSpeed) * drone.bobHeight * delta;
drone.rotation.x += drone.rotationSpeeds.x * delta;
drone.rotation.y += drone.rotationSpeeds.y * delta;
drone.rotation.z += drone.rotationSpeeds.z * delta;
// Update drone collider
drone.userData.collider.center.copy(drone.position);
// Building avoidance
let avoidanceVector = new THREE.Vector3();
let needsAvoidance = false;
for (const collider of buildingColliders) {
const box = new THREE.Box3().setFromObject(collider);
if (box.intersectsSphere(drone.userData.collider)) {
const center = box.getCenter(new THREE.Vector3());
const toDrone = new THREE.Vector3().subVectors(drone.position, center);
const dx = Math.abs(drone.position.x - center.x) - box.getSize(new THREE.Vector3()).x / 2;
const dy = Math.abs(drone.position.y - center.y) - box.getSize(new THREE.Vector3()).y / 2;
const dz = Math.abs(drone.position.z - center.z) - box.getSize(new THREE.Vector3()).z / 2;
if (dx < 0 && dy < 0 && dz < 0) {
if (dx > dy && dx > dz) {
toDrone.x = Math.sign(toDrone.x) * (box.getSize(new THREE.Vector3()).x / 2 + 2.0);
} else if (dy > dx && dy > dz) {
toDrone.y = Math.sign(toDrone.y) * (box.getSize(new THREE.Vector3()).y / 2 + 2.0);
} else {
toDrone.z = Math.sign(toDrone.z) * (box.getSize(new THREE.Vector3()).z / 2 + 2.0);
}
drone.position.copy(center).add(toDrone);
}
}
const distance = drone.position.distanceTo(box.getCenter(new THREE.Vector3()));
const minDistance = 15;
if (distance < minDistance) {
const away = new THREE.Vector3().subVectors(drone.position, box.getCenter(new THREE.Vector3()));
away.normalize().multiplyScalar(drone.avoidanceForce * (1 - distance / minDistance));
avoidanceVector.add(away);
needsAvoidance = true;
}
}
// Simple AI with building avoidance
if (player) {
const toPlayer = new THREE.Vector3();
toPlayer.subVectors(player.position, drone.position);
const distanceToPlayer = toPlayer.length();
const orbitSpeed = drone.speed * delta;
const orbitRadius = 75;
if (distanceToPlayer > orbitRadius * 1.3) {
toPlayer.normalize();
drone.position.add(toPlayer.multiplyScalar(orbitSpeed));
} else if (distanceToPlayer < orbitRadius * 0.7) {
toPlayer.normalize().negate();
drone.position.add(toPlayer.multiplyScalar(orbitSpeed));
}
const angle = drone.id * (Math.PI * 2 / drones.length) + Date.now() * 0.0002;
const targetX = Math.cos(angle) * orbitRadius;
const targetZ = Math.sin(angle) * orbitRadius;
const toTarget = new THREE.Vector3(targetX, 0, targetZ);
toTarget.normalize();
if (needsAvoidance) {
toTarget.add(avoidanceVector);
toTarget.normalize();
}
drone.position.add(toTarget.multiplyScalar(orbitSpeed * 0.3));
// Shoot at player
if (distanceToPlayer > 70 && distanceToPlayer < 250 &&
Date.now() - drone.lastFire > drone.fireRate) {
fireDroneProjectile(drone);
drone.lastFire = Date.now();
}
}
// Keep drones in bounds
const bounds = PLAY_AREA_RADIUS;
drone.position.x = THREE.MathUtils.clamp(drone.position.x, -bounds, bounds);
drone.position.z = THREE.MathUtils.clamp(drone.position.z, -bounds, bounds);
drone.position.y = THREE.MathUtils.clamp(drone.position.y, 25, 120);
}
}
// Fire drone projectile with building collision
function fireDroneProjectile(drone) {
if (!player) return;
const direction = new THREE.Vector3();
direction.subVectors(player.position, drone.position).normalize();
const spread = 0.03;
direction.x += (Math.random() - 0.5) * spread;
direction.y += (Math.random() - 0.5) * spread * 0.7;
direction.z += (Math.random() - 0.5) * spread;
direction.normalize();
createProjectile(
drone.position.clone().add(direction.clone().multiplyScalar(3.0)),
direction,
drone.projectileSpeed,
0xff0000,
drone.damage,
false
);
}
// Create spherical projectile
function createProjectile(position, direction, speed, color, damage, isPlayer = true) {
// Create spherical projectile instead of cylindrical
const projectile = createSphericalWireframe(0.8, color, 2);
projectile.position.copy(position);
// Trail
const trailGeometry = new THREE.BufferGeometry();
const trailPoints = [];
const trailLength = isPlayer ? 8 : 10;
for (let i = 0; i < trailLength; i++) {
trailPoints.push(position.x, position.y, position.z);
}
trailGeometry.setAttribute('position', new THREE.Float32BufferAttribute(trailPoints, 3));
const trailMaterial = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: 0.6
});
const trail = new THREE.Line(trailGeometry, trailMaterial);
scene.add(trail);
projectile.userData = {
direction: direction.clone().normalize(),
speed: speed,
damage: damage,
isPlayer: isPlayer,
trail: trail,
trailPoints: trailPoints,
lifetime: isPlayer ? 1.8 : 2.5,
velocity: direction.clone().multiplyScalar(speed),
spawnTime: Date.now(),
collider: new THREE.Sphere(position, 0.8)
};
scene.add(projectile);
projectiles.push(projectile);
if (isPlayer) {
stats.shotsFired++;
// Record shot in training data
trainingData.shots.push({
timestamp: Date.now(),
type: 'player_shot',
wave: wave,
level: level,
position: {x: position.x, y: position.y, z: position.z},
direction: {x: direction.x, y: direction.y, z: direction.z}
});
updateHUD();
}
return projectile;
}
// Update projectiles with solid building collision
function updateProjectiles(delta) {
for (let i = projectiles.length - 1; i >= 0; i--) {
const proj = projectiles[i];
if (!proj || !proj.userData) continue;
proj.position.add(proj.userData.velocity.clone().multiplyScalar(delta));
proj.userData.collider.center.copy(proj.position);
updateTrail(proj, delta);
proj.userData.lifetime -= delta;
if (proj.userData.lifetime <= 0) {
removeProjectile(i);
continue;
}
const collision = checkBuildingCollision(proj.position, 0.8);
if (collision.collided) {
createExplosion(proj.position, proj.userData.isPlayer ? 0x00ff00 : 0xff0000, 6);
removeProjectile(i);
continue;
}
if (proj.userData.isPlayer) {
for (let j = 0; j < drones.length; j++) {
const drone = drones[j];
if (drone && proj.position.distanceTo(drone.position) < 2.8) {
const dmg = damage;
drone.health -= dmg;
// XP FOR DAMAGE DONE - increased reward
const xpFromHit = Math.floor(dmg * 1.2 + level * 5);
addXP(xpFromHit);
createHitEffect(drone.position, proj.userData.color);
showDamageText(`+${xpFromHit} XP`, drone.position, 0xffff00);
if (drone.health <= 0) {
createExplosion(drone.position, proj.userData.color, 20);
showDamageText("DESTROYED!", drone.position, 0xff0000);
// Bonus XP for destruction - increased reward
const xpReward = Math.floor(200 + (level * 20));
addXP(xpReward);
droneKills++;
dronesDestroyedTotal++;
stats.dronesDestroyed++;
stats.shotsHit++;
// Record hit in training data
trainingData.hits.push({
timestamp: Date.now(),
type: 'drone_destroyed',
wave: wave,
level: level,
drone_id: drone.id,
xp_gained: xpReward,
position: {x: drone.position.x, y: drone.position.y, z: drone.position.z}
});
scene.remove(drone);
drones.splice(j, 1);
logToTerminal(`Drone destroyed! +${xpReward} XP`, 'combat');
saveGame();
setTimeout(() => spawnDrone(), 500);
if (droneKills >= dronesToNextWave) {
nextWave();
}
} else {
stats.shotsHit++;
// Record hit in training data
trainingData.hits.push({
timestamp: Date.now(),
type: 'drone_hit',
wave: wave,
level: level,
drone_id: drone.id,
xp_gained: xpFromHit,
damage_dealt: dmg,
drone_health_remaining: drone.health
});
logToTerminal(`Drone hit! +${xpFromHit} XP`, 'combat');
}
showHitMarker();
updateAccuracy();
removeProjectile(i);
break;
}
}
} else {
if (player && proj.position.distanceTo(player.position) < 1.5) {
const dmg = proj.userData.damage;
const xpLoss = Math.floor(dmg * XP_LOSS_RATE);
// Player cannot lose levels, only XP from current bar
loseXP(xpLoss);
createExplosion(proj.position, 0xff0000, 12);
showDamageText(`-${xpLoss} XP`, player.position, 0xff0000);
// Record player hit in training data
trainingData.shots.push({
timestamp: Date.now(),
type: 'player_hit',
wave: wave,
level: level,
damage_taken: dmg,
xp_lost: xpLoss
});
logToTerminal(`Player hit! -${xpLoss} XP`, 'error');
removeProjectile(i);
}
}
}
}
// Update projectile trail
function updateTrail(proj, delta) {
const trail = proj.userData.trail;
const points = proj.userData.trailPoints;
const trailLength = points.length / 3;
for (let i = (trailLength - 1) * 3; i >= 3; i -= 3) {
points[i] = points[i - 3];
points[i + 1] = points[i - 2];
points[i + 2] = points[i - 1];
}
points[0] = proj.position.x;
points[1] = proj.position.y;
points[2] = proj.position.z;
trail.geometry.setAttribute('position', new THREE.Float32BufferAttribute(points, 3));
trail.geometry.attributes.position.needsUpdate = true;
}
// Remove projectile
function removeProjectile(index) {
const proj = projectiles[index];
if (proj) {
if (proj.userData.trail) {
scene.remove(proj.userData.trail);
}
scene.remove(proj);
projectiles.splice(index, 1);
}
}
// Create hit effect
function createHitEffect(position, color) {
const flashGeometry = new THREE.OctahedronGeometry(2.0, 0);
const flashEdges = new THREE.EdgesGeometry(flashGeometry);
const flashMaterial = new THREE.LineBasicMaterial({
color: color,
linewidth: 1
});
const flash = new THREE.LineSegments(flashEdges, flashMaterial);
flash.position.copy(position);
scene.add(flash);
setTimeout(() => {
scene.remove(flash);
}, 60);
}
// Create explosion
function createExplosion(position, color, count) {
count = Math.min(count, 15);
for (let i = 0; i < count; i++) {
const particleGeometry = new THREE.TetrahedronGeometry(0.2 + Math.random() * 0.2);
const particleEdges = new THREE.EdgesGeometry(particleGeometry);
const particleMaterial = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: 0.6
});
const particle = new THREE.LineSegments(particleEdges, particleMaterial);
particle.position.copy(position);
particle.userData = {
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 15,
(Math.random() - 0.5) * 15,
(Math.random() - 0.5) * 15
),
lifetime: 0.6 + Math.random() * 0.4
};
scene.add(particle);
particles.push(particle);
}
}
// Update particles
function updateParticles(delta) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
if (!particle || !particle.userData) continue;
particle.userData.lifetime -= delta;
if (particle.userData.lifetime <= 0) {
scene.remove(particle);
particles.splice(i, 1);
continue;
}
particle.position.add(particle.userData.velocity.clone().multiplyScalar(delta));
particle.material.opacity = particle.userData.lifetime * 1.5;
}
}
// Spawn drone with valid position
function spawnDrone() {
if (drones.length < stats.maxDrones) {
createDrone();
updateHUD();
}
}
// Start game
function startGame() {
document.getElementById('mainMenu').style.display = 'none';
if (!loadGame()) {
level = 1;
xp = 0;
totalXP = 0;
nextXp = getXPForNextLevel(level);
wave = 1;
droneKills = 0;
dronesDestroyedTotal = 0;
dronesToNextWave = 6;
jetpackFuel = 100;
damage = 100;
stats = {
shotsFired: 0,
shotsHit: 0,
dronesDestroyed: 0,
totalDrones: 0,
accuracy: 0,
maxDrones: getMaxDronesForLevel(level)
};
// Start new training session
trainingData.currentSession = {
startTime: Date.now(),
endTime: null,
totalXP: 0,
levelsGained: 0,
wavesCompleted: 0
};
}
// Clear scene
if (scene) {
if (player) scene.remove(player);
drones.forEach(d => scene.remove(d));
projectiles.forEach(p => {
if (p.userData && p.userData.trail) scene.remove(p.userData.trail);
scene.remove(p);
});
particles.forEach(p => scene.remove(p));
buildings.forEach(b => scene.remove(b));
buildingColliders.forEach(c => scene.remove(c));
buildingTops.forEach(t => scene.remove(t));
}
drones = [];
projectiles = [];
particles = [];
buildings = [];
buildingColliders = [];
buildingTops = [];
// Initialize Three.js if not already
if (!scene) {
initThreeJS();
}
createPlayer();
createEnvironment();
// Spawn initial drones based on level tier
const initialDrones = Math.min(3, stats.maxDrones);
for (let i = 0; i < initialDrones; i++) {
setTimeout(() => spawnDrone(), i * 500);
}
currentState = GameState.PLAYING;
movementEnabled = true;
updateHUD();
logToTerminal('Mission started', 'success');
logToTerminal(`Level ${level}: ${stats.maxDrones} max drones`, 'info');
logToTerminal(`Wave ${wave} - ${initialDrones} drones`, 'warning');
const canvas = document.getElementById('gameCanvas');
canvas.focus();
}
// Handle shooting
function handleShooting() {
if (mouseButtons.left && canFire && Date.now() - lastFireTime > fireRate * 1000) {
fireSniper();
lastFireTime = Date.now();
}
}
// Get movement input
function getMovementInput() {
const move = {
forward: 0,
right: 0
};
if (keyState['KeyW']) move.forward = 1;
if (keyState['KeyS']) move.forward = -1;
if (keyState['KeyA']) move.right = -1;
if (keyState['KeyD']) move.right = 1;
return move;
}
// Update player with solid building collision
function updatePlayer(delta) {
if (!player || currentState !== GameState.PLAYING || !movementEnabled) return;
handleShooting();
const moveInput = getMovementInput();
if (keyState['ShiftLeft'] || keyState['ShiftRight']) {
if (jetpackFuel > 0) {
jetpackActive = true;
playerVelocity.y += JETPACK_FORCE * delta;
jetpackFuel = Math.max(0, jetpackFuel - jetpackConsumption * delta);
isGrounded = false;
} else {
jetpackActive = false;
}
} else {
jetpackActive = false;
}
sprinting = keyState['Space'] && isGrounded;
const speedMultiplier = sprinting ? SPRINT_MULTIPLIER : 1;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3();
right.crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
let moveDirection = new THREE.Vector3();
if (moveInput.forward !== 0 || moveInput.right !== 0) {
moveDirection.add(forward.clone().multiplyScalar(moveInput.forward));
moveDirection.add(right.clone().multiplyScalar(moveInput.right));
if (moveDirection.length() > 0) {
moveDirection.normalize();
const controlFactor = isGrounded ? 1.0 : AIR_CONTROL;
const targetVelocity = moveDirection.multiplyScalar(BASE_SPEED * speedMultiplier * controlFactor);
playerVelocity.x += (targetVelocity.x - playerVelocity.x) * 0.15;
playerVelocity.z += (targetVelocity.z - playerVelocity.z) * 0.15;
}
} else {
playerVelocity.x *= FRICTION;
playerVelocity.z *= FRICTION;
}
if (!isGrounded) {
playerVelocity.y -= GRAVITY * delta;
} else {
playerVelocity.y = Math.max(0, playerVelocity.y);
}
let newPosition = player.position.clone().add(playerVelocity.clone().multiplyScalar(delta));
const collision = checkBuildingCollision(newPosition, 0.6);
const topCollision = checkBuildingTopCollision(newPosition);
if (topCollision.onTop) {
isGrounded = true;
newPosition.y = topCollision.topY + 0.55;
playerVelocity.y = 0;
} else if (collision.collided) {
const box = collision.box;
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const dx = newPosition.x - center.x;
const dz = newPosition.z - center.z;
const pushDistance = 0.7;
if (Math.abs(dx) > Math.abs(dz)) {
newPosition.x = center.x + Math.sign(dx) * (size.x / 2 + pushDistance);
} else {
newPosition.z = center.z + Math.sign(dz) * (size.z / 2 + pushDistance);
}
playerVelocity.x = 0;
playerVelocity.z = 0;
} else {
const groundCheck = newPosition.clone();
groundCheck.y -= 0.7;
const groundCollision = checkBuildingCollision(groundCheck, 0.6);
isGrounded = (newPosition.y <= 0.7) || groundCollision.collided;
if (isGrounded && !jetpackActive) {
jetpackFuel = Math.min(100, jetpackFuel + jetpackRefillRate * delta);
}
}
player.position.copy(newPosition);
const bounds = PLAY_AREA_RADIUS - 5;
player.position.x = THREE.MathUtils.clamp(player.position.x, -bounds, bounds);
player.position.z = THREE.MathUtils.clamp(player.position.z, -bounds, bounds);
player.position.y = Math.max(0.7, player.position.y);
document.getElementById('jetpackFill').style.width = `${jetpackFuel}%`;
if (camera.fov !== targetFOV) {
camera.fov += (targetFOV - camera.fov) * 0.1;
camera.updateProjectionMatrix();
}
}
// Fire sniper with spherical projectile
function fireSniper() {
const barrelPos = new THREE.Vector3();
if (sniperRifle) {
const muzzlePos = new THREE.Vector3(0, -0.2, -2.2);
sniperRifle.localToWorld(muzzlePos);
barrelPos.copy(muzzlePos);
} else {
camera.getWorldPosition(barrelPos);
}
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
const spread = zoomed ? 0.0003 : 0.001;
direction.x += (Math.random() - 0.5) * spread;
direction.y += (Math.random() - 0.5) * spread;
direction.z += (Math.random() - 0.5) * spread;
direction.normalize();
const projectile = createProjectile(barrelPos, direction, projectileSpeed, 0x00ff00, damage, true);
if (projectile) {
// Recoil animation
sniperRifle.position.z += 0.04;
sniperRifle.rotation.x += 0.04;
sniperRifle.position.y -= 0.01;
setTimeout(() => {
sniperRifle.position.z -= 0.04;
sniperRifle.rotation.x -= 0.04;
sniperRifle.position.y += 0.01;
}, 40);
}
}
// Next wave
function nextWave() {
wave++;
droneKills = 0;
dronesToNextWave = 8 + wave * 1.5;
if (wave % 2 === 0) {
damage += 12;
}
createEnvironment();
const waveDrones = Math.min(stats.maxDrones, 3 + Math.floor(wave * 1.2));
for (let i = 0; i < waveDrones - drones.length; i++) {
setTimeout(() => spawnDrone(), i * 200);
}
// Record wave completion
trainingData.waves.push({
timestamp: Date.now(),
wave: wave - 1,
level: level,
drones_destroyed: dronesDestroyedTotal,
accuracy: stats.accuracy
});
trainingData.currentSession.wavesCompleted++;
logToTerminal(`Wave ${wave} cleared!`, 'success');
logToTerminal(`Damage: ${damage}`, 'info');
updateHUD();
saveGame();
}
// Add XP - Yellow bar, increased rewards
function addXP(amount) {
if (amount <= 0) return;
xp += amount;
totalXP += amount;
trainingData.currentSession.totalXP += amount;
logToTerminal(`+${amount} XP`, 'combat');
const xpForNextLevel = getXPForNextLevel(level);
while (xp >= xpForNextLevel && level < 99) {
xp -= xpForNextLevel;
level++;
trainingData.currentSession.levelsGained++;
const newXpForNextLevel = getXPForNextLevel(level);
// Damage increase on level up
damage += 12;
// Update max drones based on new level tier
stats.maxDrones = getMaxDronesForLevel(level);
// Record level up
trainingData.levelUps.push({
timestamp: Date.now(),
level: level,
wave: wave,
damage: damage,
max_drones: stats.maxDrones
});
logToTerminal(`LEVEL UP! Now level ${level}`, 'level');
logToTerminal(`Max Drones: ${stats.maxDrones}`, 'info');
logToTerminal(`Damage: ${damage}`, 'info');
const xpFill = document.getElementById('xpFill');
xpFill.classList.add('level-up-glow');
setTimeout(() => {
xpFill.classList.remove('level-up-glow');
}, 1500);
nextXp = newXpForNextLevel;
saveGame();
}
updateHUD();
}
// Lose XP - Player cannot lose levels, only XP from current bar
function loseXP(amount) {
if (amount <= 0) return;
// Calculate XP that can be lost (only from current level's XP)
const xpForCurrentLevel = getXPForLevel(level);
const currentLevelXP = xp; // XP in current level
// Player can only lose XP from current level, not total XP that would cause level loss
const xpLoss = Math.min(currentLevelXP, amount);
if (xpLoss > 0) {
xp -= xpLoss;
totalXP -= xpLoss;
// Ensure XP doesn't go below 0 for current level
if (xp < 0) xp = 0;
if (totalXP < xpForCurrentLevel) totalXP = xpForCurrentLevel;
logToTerminal(`-${xpLoss} XP (damage taken)`, 'error');
updateHUD();
}
}
// Show hit marker
function showHitMarker() {
const marker = document.getElementById('hitMarker');
if (!marker) return;
marker.style.opacity = '1';
marker.style.transform = 'translate(-50%, -50%) scale(1.5)';
setTimeout(() => {
marker.style.opacity = '0';
marker.style.transform = 'translate(-50%, -50%) scale(1)';
}, 70);
}
// Show damage text
function showDamageText(text, position, color) {
const damageContainer = document.getElementById('damageContainer');
if (!damageContainer) return;
const damageText = document.createElement('div');
damageText.className = 'damage-text';
damageText.textContent = text;
damageText.style.color = `rgb(${color >> 16}, ${(color >> 8) & 255}, ${color & 255})`;
const vector = new THREE.Vector3();
vector.copy(position);
vector.project(camera);
const x = (vector.x * 0.5 + 0.5) * window.innerWidth;
const y = (-(vector.y * 0.5) + 0.5) * window.innerHeight;
damageText.style.left = `${x}px`;
damageText.style.top = `${y}px`;
damageText.style.opacity = '1';
damageContainer.appendChild(damageText);
let posY = y;
let opacity = 1;
const anim = setInterval(() => {
posY -= 1.5;
opacity -= 0.02;
damageText.style.top = `${posY}px`;
damageText.style.opacity = opacity;
if (opacity <= 0) {
clearInterval(anim);
damageText.remove();
}
}, 16);
}
// Update accuracy
function updateAccuracy() {
if (stats.shotsFired > 0) {
stats.accuracy = Math.round((stats.shotsHit / stats.shotsFired) * 100);
document.getElementById('accuracy').textContent = `${stats.accuracy}%`;
}
}
// Update HUD
function updateHUD() {
document.getElementById('level').textContent = level;
document.getElementById('drones').textContent = drones.length;
document.getElementById('maxDrones').textContent = stats.maxDrones;
document.getElementById('wave').textContent = wave;
document.getElementById('damage').textContent = damage;
document.getElementById('dronesDestroyed').textContent = dronesDestroyedTotal;
document.getElementById('shotsFired').textContent = stats.shotsFired;
document.getElementById('shotsHit').textContent = stats.shotsHit;
// Update experience bar (yellow)
const xpFill = document.getElementById('xpFill');
const xpText = document.getElementById('xpText');
const currentLevel = document.getElementById('currentLevel');
const xpForNextLevel = getXPForNextLevel(level);
const xpPercentage = (xp / xpForNextLevel) * 100;
if (xpFill) xpFill.style.width = `${Math.min(100, xpPercentage)}%`;
if (xpText) xpText.textContent = `XP: ${xp}/${xpForNextLevel}`;
if (currentLevel) currentLevel.textContent = level;
if (zoomed) {
document.getElementById('scopeReadout').textContent = `ZOOM: 4x`;
document.getElementById('fireMode').textContent = "ZOOMED (LMB)";
} else {
document.getElementById('scopeReadout').textContent = `ZOOM: 1x`;
document.getElementById('fireMode').textContent = "NORMAL (LMB)";
}
updateAccuracy();
}
// Export training data
function exportTrainingData() {
try {
// Complete current session
trainingData.currentSession.endTime = Date.now();
trainingData.sessions.push({...trainingData.currentSession});
// Prepare data for export
const exportData = {
metadata: {
game: "XFORC3D: SNIPER CELL",
version: "1.0",
export_date: new Date().toISOString(),
player_stats: {
level: level,
total_xp: totalXP,
waves_completed: wave,
drones_destroyed: dronesDestroyedTotal,
accuracy: stats.accuracy
}
},
training_data: trainingData,
game_state: {
level: level,
xp: xp,
totalXP: totalXP,
wave: wave,
droneKills: droneKills,
dronesDestroyedTotal: dronesDestroyedTotal,
damage: damage,
stats: stats
},
settings: {
XP_LOSS_RATE: XP_LOSS_RATE,
max_drones_by_tier: {
"1-10": "4-5 drones max",
"11-20": "6 drones max",
"21-30": "7 drones max",
"31-40": "8 drones max",
"41-50": "9 drones max",
"51-99": "10 drones max"
}
}
};
// Create ZIP file
const zip = new JSZip();
// Add main JSON data
zip.file("xforc3d_training_data.json", JSON.stringify(exportData, null, 2));
// Add CSV versions for easier analysis
const shotsCSV = convertToCSV(trainingData.shots, "shots");
const hitsCSV = convertToCSV(trainingData.hits, "hits");
const levelUpsCSV = convertToCSV(trainingData.levelUps, "level_ups");
const wavesCSV = convertToCSV(trainingData.waves, "waves");
zip.file("shots_data.csv", shotsCSV);
zip.file("hits_data.csv", hitsCSV);
zip.file("level_ups_data.csv", levelUpsCSV);
zip.file("waves_data.csv", wavesCSV);
// Add README file
const readme = `XFORC3D: SNIPER CELL - TRAINING DATA EXPORT
=============================================
Exported: ${new Date().toISOString()}
Player Level: ${level}
Total XP: ${totalXP}
Waves Completed: ${wave}
Drones Destroyed: ${dronesDestroyedTotal}
Accuracy: ${stats.accuracy}%
FILES INCLUDED:
---------------
1. xforc3d_training_data.json - Complete dataset in JSON format
2. shots_data.csv - All shots fired by player and drones
3. hits_data.csv - All hits and drone destructions
4. level_ups_data.csv - Level progression data
5. waves_data.csv - Wave completion data
DATA STRUCTURE:
---------------
- Each action is timestamped for time-series analysis
- XP rewards and penalties are recorded
- Position data for spatial analysis
- Level-based difficulty scaling included
TIERED DRONE SYSTEM:
--------------------
Level 1-10: 4-5 drones max
Level 11-20: 6 drones max
Level 21-30: 7 drones max
Level 31-40: 8 drones max
Level 41-50: 9 drones max
Level 51-99: 10 drones max
USE FOR TRAINING:
-----------------
This data can be used to train reinforcement learning models
for drone combat AI, player behavior prediction, or
difficulty balancing algorithms.
COMPRESSION:
------------
This ZIP file supports GZIP, ZSTD, BZ2, LZ4, and LZMA decompression.`;
zip.file("README.txt", readme);
// Generate and download ZIP
zip.generateAsync({type: "blob"}).then(function(content) {
saveAs(content, `xforc3d_training_data_${Date.now()}.zip`);
logToTerminal('Training data exported successfully!', 'success');
});
} catch (error) {
console.error("Export error:", error);
logToTerminal(`Export failed: ${error.message}`, 'error');
}
}
// Convert data to CSV
function convertToCSV(data, type) {
if (!data || data.length === 0) return "";
const headers = Object.keys(data[0]);
const rows = data.map(obj =>
headers.map(header => {
const value = obj[header];
if (typeof value === 'object') {
return JSON.stringify(value);
}
return value;
}).join(',')
);
return [headers.join(','), ...rows].join('\n');
}
// Save game
function saveGame() {
const gameData = {
level,
xp,
totalXP,
wave,
droneKills,
dronesDestroyedTotal,
dronesToNextWave,
damage,
stats,
trainingData: trainingData // Include training data in save
};
localStorage.setItem('xforc3d_save', JSON.stringify(gameData));
const saveIndicator = document.getElementById('saveIndicator');
if (saveIndicator) {
saveIndicator.style.opacity = '1';
lastSaveTime = Date.now();
setTimeout(() => {
if (Date.now() - lastSaveTime >= 1500) {
saveIndicator.style.opacity = '0';
}
}, 1500);
}
}
// Load game
function loadGame() {
try {
const saved = localStorage.getItem('xforc3d_save');
if (saved) {
const gameData = JSON.parse(saved);
level = gameData.level || 1;
xp = gameData.xp || 0;
totalXP = gameData.totalXP || 0;
wave = gameData.wave || 1;
droneKills = gameData.droneKills || 0;
dronesDestroyedTotal = gameData.dronesDestroyedTotal || 0;
dronesToNextWave = gameData.dronesToNextWave || 6;
damage = gameData.damage || 100;
stats = gameData.stats || {
shotsFired: 0,
shotsHit: 0,
dronesDestroyed: 0,
totalDrones: 0,
accuracy: 0,
maxDrones: getMaxDronesForLevel(level)
};
// Load training data if exists
if (gameData.trainingData) {
trainingData = gameData.trainingData;
}
nextXp = getXPForNextLevel(level);
stats.maxDrones = getMaxDronesForLevel(level);
logToTerminal('Game loaded', 'success');
return true;
}
} catch (error) {
console.error("Failed to load saved game:", error);
logToTerminal('Starting fresh game', 'info');
}
return false;
}
// Setup event listeners
function setupEventListeners() {
// Menu buttons
document.getElementById('startBtn').addEventListener('click', startGame);
document.getElementById('continueBtn').addEventListener('click', startGame);
document.getElementById('controlsBtn').addEventListener('click', () => {
alert(`CONTROLS:\n\nW = Forward\nA = Left Strafe\nS = Backward\nD = Right Strafe\nLMB = Shoot (2-hit drones)\nRMB = Zoom Scope\nSPACE = Sprint\nSHIFT = Jetpack\nESC = Menu\n\nTIERED DRONE SYSTEM:\n- Level 1-10: 4-5 drones max\n- Level increases add 1-2 drones every 10 levels\n- Max level 99: 10 drones max\n- XP bar shows yellow progress\n- Damage gives XP, taking damage reduces XP (25%)\n- Cannot lose levels, only XP from current bar\n\nClick game screen to activate controls!`);
});
// Export button
document.getElementById('exportBtn').addEventListener('click', exportTrainingData);
// Keyboard controls
document.addEventListener('keydown', (e) => {
keyState[e.code] = true;
if (e.code === 'Escape') {
if (currentState === GameState.PLAYING) {
currentState = GameState.MENU;
document.getElementById('mainMenu').style.display = 'flex';
saveGame();
if (document.exitPointerLock) {
document.exitPointerLock();
}
logToTerminal('Game paused', 'warning');
}
return;
}
if (e.code === 'Space') {
e.preventDefault();
}
});
document.addEventListener('keyup', (e) => {
keyState[e.code] = false;
});
// Mouse controls
document.addEventListener('mousedown', (e) => {
if (currentState === GameState.PLAYING) {
if (e.button === 0) {
mouseButtons.left = true;
} else if (e.button === 2) {
e.preventDefault();
mouseButtons.right = true;
zoomed = !zoomed;
if (zoomed) {
document.getElementById('scopeOverlay').style.display = 'block';
document.getElementById('crosshair').style.display = 'none';
targetFOV = ZOOM_FOV;
} else {
document.getElementById('scopeOverlay').style.display = 'none';
document.getElementById('crosshair').style.display = 'block';
targetFOV = NORMAL_FOV;
}
updateHUD();
}
}
});
document.addEventListener('mouseup', (e) => {
if (e.button === 0) {
mouseButtons.left = false;
}
if (e.button === 2) {
mouseButtons.right = false;
}
});
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
return false;
});
const canvas = document.getElementById('gameCanvas');
canvas.addEventListener('click', () => {
if (currentState === GameState.PLAYING) {
if (canvas.requestPointerLock) {
canvas.requestPointerLock();
}
canvas.focus();
movementEnabled = true;
logToTerminal('Controls active', 'info');
}
});
document.addEventListener('pointerlockchange', () => {
pointerLocked = document.pointerLockElement === canvas;
movementEnabled = pointerLocked;
});
document.addEventListener('mousemove', (e) => {
if (pointerLocked && currentState === GameState.PLAYING && player) {
const movementX = e.movementX || 0;
const movementY = e.movementY || 0;
player.rotation.y -= movementX * mouseSensitivity;
camera.rotation.x -= movementY * mouseSensitivity;
camera.rotation.x = Math.max(-Math.PI/2, Math.min(Math.PI/2, camera.rotation.x));
}
});
window.addEventListener('resize', () => {
if (camera) {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
if (renderer) {
renderer.setSize(window.innerWidth, window.innerHeight);
}
if (thickLineMaterial) {
thickLineMaterial.resolution.set(window.innerWidth, window.innerHeight);
}
});
window.addEventListener('blur', () => {
keyState = {};
mouseButtons.left = false;
mouseButtons.right = false;
});
window.addEventListener('focus', () => {
keyState = {};
});
if (canvas) {
canvas.tabIndex = 1;
canvas.style.outline = 'none';
}
}
// Animation loop
let lastTime = 0;
function animate(currentTime = 0) {
requestAnimationFrame(animate);
const delta = Math.min((currentTime - lastTime) / 1000, 0.1);
lastTime = currentTime;
if (currentState === GameState.PLAYING) {
updatePlayer(delta);
updateDrones(delta);
updateProjectiles(delta);
updateParticles(delta);
if (renderer && scene && camera) {
renderer.render(scene, camera);
}
}
}
// Initialize game when page loads
window.addEventListener('load', init);
</script>
</body>
</html>