-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
393 lines (323 loc) · 15.1 KB
/
game.js
File metadata and controls
393 lines (323 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { Car } from './js/car.js';
import { Map } from './js/world/map.js';
import { Controls } from './js/controls.js';
import { MissionManager } from './js/game/mission.js';
import { HUD } from './js/ui/hud.js';
import { ScoreManager } from './js/game/scoring.js';
import { GameTimer } from './js/game/timer.js';
import { ParticleSystem } from './js/effects/particles.js';
// Game class
export class Game {
constructor(containerId) {
console.log('Game constructor called with container:', containerId);
this.container = document.getElementById(containerId);
console.log('Found container:', this.container);
if (!this.container) {
console.error(`Container element with id '${containerId}' not found!`);
return; // Exit constructor if container not found
}
this.width = window.innerWidth;
this.height = window.innerHeight;
// Game state
this.isRunning = false;
this.debugMode = false;
this.score = 0;
this.lastTime = 0;
// Set up renderer with maximum performance optimizations
this.renderer = new THREE.WebGLRenderer({
antialias: false,
powerPreference: "high-performance",
precision: "lowp" // Use low precision for better performance
});
this.renderer.setSize(this.width, this.height);
// Disabled shadow maps completely
this.renderer.shadowMap.enabled = false;
// Set lowest possible pixel ratio
this.renderer.setPixelRatio(1);
// Make sure we're appending to the container
console.log('Appending renderer to container');
this.container.innerHTML = ''; // Clear any existing content
this.container.appendChild(this.renderer.domElement);
console.log('Renderer appended successfully');
// Set up scene
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x87CEEB);
// Less aggressive fog for better visibility
this.scene.fog = new THREE.Fog(0x87CEEB, 300, 800);
// Set up camera with reduced far plane
this.camera = new THREE.PerspectiveCamera(75, this.width / this.height, 0.1, 800);
this.camera.position.set(0, 50, 50);
// Debug orbit controls
this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement);
this.orbitControls.enabled = this.debugMode;
// Camera settings - higher position for better road visibility
this.cameraOffset = new THREE.Vector3(0, 20, -25); // Higher and further back
this.cameraLookOffset = new THREE.Vector3(0, 0, 30); // Look further ahead
this.cameraLerpFactor = 1.0;
// Add lights - simplified for performance
this.setupLights();
// Create effects systems
this.particleSystem = new ParticleSystem(this.scene);
// Create game elements
this.map = new Map(this.scene);
this.car = new Car(this.scene, this.particleSystem);
this.controls = new Controls(this.car);
// Add gameplay systems
this.missionManager = new MissionManager(this.scene, this.map);
this.scoreManager = new ScoreManager();
this.gameTimer = new GameTimer(90); // 90 seconds starting time
this.hud = new HUD();
// Set up minimap
this.setupMinimap();
// Performance monitoring
this.fpsCounter = document.createElement('div');
this.fpsCounter.style.position = 'absolute';
this.fpsCounter.style.top = '10px';
this.fpsCounter.style.right = '10px';
this.fpsCounter.style.color = 'white';
this.fpsCounter.style.backgroundColor = 'rgba(0,0,0,0.5)';
this.fpsCounter.style.padding = '5px';
document.body.appendChild(this.fpsCounter);
this.frameCount = 0;
this.lastFpsUpdate = 0;
// Handle window resize
window.addEventListener('resize', this.onWindowResize.bind(this));
// Add debug toggle
window.addEventListener('keydown', (e) => {
if (e.key === 'd') {
this.debugMode = !this.debugMode;
this.orbitControls.enabled = this.debugMode;
}
// Toggle minimap when 'm' is pressed
if (e.key === 'm') {
this.toggleMinimap();
}
});
// Display starting message - detect touch device for appropriate message
const isTouchDevice = ('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
window.matchMedia("(pointer: coarse)").matches;
if (isTouchDevice) {
this.showMessage("Welcome to Crazy Uber! Use on-screen buttons to drive. Hold 'DRIFT' to drift.");
} else {
this.showMessage("Welcome to Crazy Uber! Use arrow keys to drive. Press 'D' for debug camera view. Press 'M' to toggle minimap.");
}
setTimeout(() => this.hideMessage(), 5000);
// Bind the animate method to preserve 'this' context
this.animate = this.animate.bind(this);
console.log("Game initialized");
}
setupLights() {
// Simple lighting - no shadows
// Strong ambient light since we don't have shadows
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
this.scene.add(ambientLight);
// Simple directional light without shadows
const sunLight = new THREE.DirectionalLight(0xffffff, 0.5);
sunLight.position.set(50, 100, 50);
sunLight.castShadow = false; // No shadows
this.scene.add(sunLight);
}
setupMinimap() {
// Create minimap container
this.minimapContainer = document.createElement('div');
this.minimapContainer.style.position = 'absolute';
this.minimapContainer.style.bottom = '20px';
this.minimapContainer.style.right = '20px';
this.minimapContainer.style.width = '200px';
this.minimapContainer.style.height = '200px';
this.minimapContainer.style.backgroundColor = 'rgba(0,0,0,0.5)';
this.minimapContainer.style.border = '2px solid white';
this.minimapContainer.style.borderRadius = '5px';
// Hide minimap by default
this.minimapContainer.style.display = 'none';
document.body.appendChild(this.minimapContainer);
// Create minimap renderer
this.minimapRenderer = new THREE.WebGLRenderer({ alpha: true });
this.minimapRenderer.setSize(200, 200);
this.minimapContainer.appendChild(this.minimapRenderer.domElement);
// Create minimap camera (top-down view)
this.minimapCamera = new THREE.OrthographicCamera(
-300, 300, 300, -300, 1, 1000
);
this.minimapCamera.position.set(0, 100, 0);
this.minimapCamera.lookAt(0, 0, 0);
this.minimapCamera.rotation.z = Math.PI; // Adjust orientation
// Create player indicator for minimap - but don't add it to the scene yet
const indicatorGeometry = new THREE.CircleGeometry(5, 8);
const indicatorMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
this.playerIndicator = new THREE.Mesh(indicatorGeometry, indicatorMaterial);
this.playerIndicator.rotation.x = -Math.PI / 2; // Make it horizontal
}
addRoadsToMinimap() {
// Add simplified representation of roads to minimap
const roadMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
// Get road segments from the map
if (this.map && this.map.roadSegments) {
for (const segment of this.map.roadSegments) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(segment.start.x, 1, segment.start.z),
new THREE.Vector3(segment.end.x, 1, segment.end.z)
]);
const line = new THREE.Line(geometry, roadMaterial);
this.minimapScene.add(line);
}
}
}
start() {
console.log('Game.start() called');
this.isRunning = true;
this.lastTime = performance.now();
console.log('Starting animation loop');
this.animate();
console.log("Game started");
}
animate() {
if (!this.isRunning) {
console.warn('Animation loop stopped: isRunning is false');
return;
}
requestAnimationFrame(this.animate);
// Get actual time delta for smoother movement
const currentTime = performance.now();
const delta = Math.min((currentTime - this.lastTime) / 1000, 0.1); // Clamp to avoid jumps
this.lastTime = currentTime;
// FPS counter update
this.frameCount++;
if (currentTime - this.lastFpsUpdate > 1000) {
const fps = Math.round(this.frameCount * 1000 / (currentTime - this.lastFpsUpdate));
this.fpsCounter.textContent = `FPS: ${fps}`;
this.frameCount = 0;
this.lastFpsUpdate = currentTime;
}
// Update game logic
this.update(delta);
// Render the scene
this.renderer.render(this.scene, this.camera);
// Render minimap
this.updateMinimap();
}
update(delta) {
// Update controls
this.controls.update();
// Update car physics with map for collision detection
this.car.update(delta, this.map);
// Update effects
this.particleSystem.update(delta);
// Get previous passenger state to detect dropoffs
const hadPassenger = this.missionManager.currentPassenger !== null;
const previousScore = this.missionManager.score;
// Update gameplay systems
this.missionManager.update(delta, this.car.position);
this.scoreManager.update(delta);
this.gameTimer.update(delta);
// Check if passenger was dropped off (detect score change in mission manager)
const currentScore = this.missionManager.score;
if (currentScore > previousScore) {
const fareAmount = currentScore - previousScore;
this.scoreManager.addFare(fareAmount);
}
// Check if car is drifting for score bonuses
if (this.car.driftFactor > 0.3 && this.car.speed > 20) {
this.scoreManager.addDriftBonus(delta, this.car.driftFactor);
}
// Check if the player has picked up or dropped off a passenger
const gameStats = this.missionManager.getGameStats();
// Update the HUD
this.hud.update({
score: this.scoreManager.getScoreStats().totalScore,
timeRemaining: this.gameTimer.getTimeStats().timeRemaining,
isGameOver: this.gameTimer.getTimeStats().isGameOver
}, Math.round(1 / delta), this.missionManager.currentPassenger !== null);
// Check for game over
if (this.gameTimer.getTimeStats().isGameOver && !this.isGameOver) {
this.isGameOver = true;
this.gameOver();
}
// Update camera to follow car
this.updateCamera();
}
updateMinimap() {
// Only update minimap if it's visible
if (this.minimapContainer && this.minimapContainer.style.display !== 'none') {
// Update player indicator position on minimap
this.playerIndicator.position.x = this.car.position.x;
this.playerIndicator.position.z = this.car.position.z;
this.playerIndicator.position.y = 0.5; // Slightly above ground
this.playerIndicator.rotation.y = this.car.rotation;
// Add indicator right before rendering minimap, remove after rendering
this.scene.add(this.playerIndicator);
this.minimapRenderer.render(this.scene, this.minimapCamera);
this.scene.remove(this.playerIndicator); // Remove it immediately after rendering
}
}
updateCamera() {
if (this.debugMode) return; // Don't move camera in debug mode
const carPosition = this.car.position;
const carRotation = this.car.rotation;
// Position camera at a moderate distance from the car - not too close, not too far
this.camera.position.x = carPosition.x - Math.sin(carRotation) * 12;
this.camera.position.y = carPosition.y + 6; // Moderately above car
this.camera.position.z = carPosition.z - Math.cos(carRotation) * 12;
// Look ahead of the car at a comfortable distance
const lookPosition = new THREE.Vector3(
carPosition.x + Math.sin(carRotation) * 20, // Look ahead
carPosition.y - 1, // Slightly below car height to see road better
carPosition.z + Math.cos(carRotation) * 20 // Look ahead
);
this.camera.lookAt(lookPosition);
}
onWindowResize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.camera.aspect = this.width / this.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.width, this.height);
}
showMessage(text) {
// Create or update message element
let message = document.getElementById('game-message');
if (!message) {
message = document.createElement('div');
message.id = 'game-message';
message.style.position = 'absolute';
message.style.top = '50%';
message.style.left = '50%';
message.style.transform = 'translate(-50%, -50%)';
message.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
message.style.color = 'white';
message.style.padding = '20px';
message.style.borderRadius = '10px';
message.style.fontSize = '24px';
message.style.textAlign = 'center';
message.style.maxWidth = '80%';
message.style.zIndex = '1000';
document.body.appendChild(message);
}
message.textContent = text;
message.style.display = 'block';
}
hideMessage() {
const message = document.getElementById('game-message');
if (message) {
message.style.display = 'none';
}
}
gameOver() {
// Show game over screen
this.hud.showGameOver(this.scoreManager.getScoreStats().totalScore);
// Stop the game loop
this.isRunning = false;
}
toggleMinimap() {
if (this.minimapContainer) {
if (this.minimapContainer.style.display === 'none') {
this.minimapContainer.style.display = 'block';
} else {
this.minimapContainer.style.display = 'none';
}
}
}
}