Best JavaScript code snippet using best
game.js
Source:game.js
1let present = require('present');2let fs = require('fs');3let Player = require('./player.js');4let HIGH_SCORES_FILE_NAME = 'highScores.json';5const MAX_HIGH_SCORES = 10;6const UPDATE_RATE_MS = 25;7let quit = false;8let lastUpdateTime = present();9let clients = {}; // All clients10let activeClients = {}; // Clients that are currently in the game11let asteroids = {};12let nextAsteroidId = 0;13const STARTING_NUM_ASTEROIDS = 5;14const MAX_ASTEROIDS = 10;15const ASTEROID_COUNTDOWN = 10;16let timeUntilNextAsteroid = ASTEROID_COUNTDOWN;17let projectiles = {};18let nextProjectileId = 0;19let ufos = {};20let nextUFOId = 0;21const MAX_UFOS = 1;22const UFO_COUNTDOWN = 30;23let timeUntilNextUFO = UFO_COUNTDOWN;24let ufoProjectiles = {};25let nextUFOProjectileId = 0;26let bounds = {27 x: {28 lower: 0,29 upper: 730 },31 y: {32 lower: 0,33 upper: 534 }35};36function randomNormal(mean, stdDev) {37 let u = Math.random();38 let v = Math.random();39 while (u == 0) { u = Math.random(); } // u and v can't be 0.40 while (v == 0) { v = Math.random(); }41 return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v) * stdDev + mean;42};43const asteroidRadius = {44 SMALL: 0.025,45 MEDIUM: 0.05,46 LARGE: 0.147}48function initializeAsteroids() {49 asteroids = {};50 for (let i = 0; i < STARTING_NUM_ASTEROIDS; i++) {51 asteroids[nextAsteroidId] = {52 asteroidId: nextAsteroidId++,53 position: {54 x: Math.random() * (bounds.x.upper - bounds.x.lower) + bounds.x.lower,55 y: Math.random() * (bounds.y.upper - bounds.y.lower) + bounds.y.lower56 },57 velocity: {58 x: Math.random() * 0.2 - 0.1,59 y: Math.random() * 0.2 - 0.160 },61 radius: asteroidRadius.LARGE,62 angle: Math.random() * 36063 };64 }65}66function createAsteroid() {67 let point = getRandomPerimeterPoint();68 asteroids[nextAsteroidId] = {69 asteroidId: nextAsteroidId,70 position: {71 x: point.x,72 y: point.y73 },74 velocity: {75 x: Math.random() * 0.2 - 0.1,76 y: Math.random() * 0.2 - 0.177 },78 radius: asteroidRadius.LARGE,79 angle: Math.random() * 36080 };81 return asteroids[nextAsteroidId++];82}83function playerAsteroidHit(asteroidId, projectileId) {84 let newAsteroids = {};85 let newSize = asteroidRadius.SMALL;86 let maxSpeed = 0.3;87 let numNew = 0;88 let score = 50;89 if (asteroids[asteroidId].radius === asteroidRadius.LARGE) {90 newSize = asteroidRadius.MEDIUM;91 maxSpeed = 0.25;92 numNew = 3;93 score = 10;94 } else if (asteroids[asteroidId].radius === asteroidRadius.MEDIUM) {95 numNew = 2;96 score = 25;97 }98 activeClients[projectiles[projectileId].playerId].player.addToScore(score);99 for (let i = 0; i < numNew; i++) {100 let newAsteroid = {101 asteroidId: nextAsteroidId,102 position: {103 x: asteroids[asteroidId].position.x,104 y: asteroids[asteroidId].position.y105 },106 velocity: {107 x: (2 * Math.random() - 1) * maxSpeed,108 y: (2 * Math.random() - 1) * maxSpeed109 },110 radius: newSize,111 angle: Math.random() * 360112 };113 newAsteroids[nextAsteroidId] = newAsteroid;114 asteroids[nextAsteroidId++] = newAsteroid;115 }116 for (let id in activeClients) {117 activeClients[id].socket.emit('projectile-hit', {118 asteroidId: asteroidId,119 projectileId: projectileId,120 newAsteroids: newAsteroids,121 score: score122 });123 }124 delete asteroids[asteroidId];125 delete projectiles[projectileId];126 // if (Object.keys(asteroids).length === 0) {127 // let maxScore = 0;128 // let winnerIds = [];129 // for (let id in activeClients) {130 // if (activeClients[id].player.score === maxScore) {131 // winnerIds.push(id);132 // } else if (activeClients[id].player.score > maxScore) {133 // winnerIds = [id];134 // maxScore = activeClients[id].player.score;135 // }136 // }137 // for (let id in activeClients) {138 // activeClients[id].socket.emit('game-over', {139 // winnerIds: winnerIds140 // });141 // }142 // saveHighScores();143 // }144}145function ufoAsteroidHit(asteroidId, ufoProjectileId) {146 let newAsteroids = {};147 let newSize = asteroidRadius.SMALL;148 let maxSpeed = 0.3;149 let numNew = 0;150 let score = 50;151 if (asteroids[asteroidId].radius === asteroidRadius.LARGE) {152 newSize = asteroidRadius.MEDIUM;153 maxSpeed = 0.25;154 numNew = 3;155 } else if (asteroids[asteroidId].radius === asteroidRadius.MEDIUM) {156 numNew = 2;157 }158 for (let i = 0; i < numNew; i++) {159 let newAsteroid = {160 asteroidId: nextAsteroidId,161 position: {162 x: asteroids[asteroidId].position.x,163 y: asteroids[asteroidId].position.y164 },165 velocity: {166 x: (2 * Math.random() - 1) * maxSpeed,167 y: (2 * Math.random() - 1) * maxSpeed168 },169 radius: newSize,170 angle: Math.random() * 360171 };172 newAsteroids[nextAsteroidId] = newAsteroid;173 asteroids[nextAsteroidId++] = newAsteroid;174 }175 for (let id in activeClients) {176 activeClients[id].socket.emit('ufo-projectile-hit', {177 asteroidId: asteroidId,178 ufoProjectileId: ufoProjectileId,179 newAsteroids: newAsteroids,180 });181 }182 delete asteroids[asteroidId];183 // UFO projectiles break asteroids and keep going.184 // delete ufoProjectiles[ufoProjectileId];185}186let inputQueue = [];187function fireProjectile(playerId) {188 let projectile = {189 playerId: playerId,190 projectileId: nextProjectileId,191 position: {192 x: activeClients[playerId].player.position.x,193 y: activeClients[playerId].player.position.y194 },195 velocity: {196 x: Math.sin(activeClients[playerId].player.angle * Math.PI / 180),197 y: -Math.cos(activeClients[playerId].player.angle * Math.PI / 180)198 },199 angle: activeClients[playerId].player.angle,200 radius: 1 / 80,201 remainingLifetime: 1.0202 };203 projectiles[nextProjectileId++] = projectile;204 for (let id in activeClients) {205 activeClients[id].socket.emit('new-projectile', projectile);206 }207}208function createUFO(x, y) {209 let point = getRandomPerimeterPoint();210 ufos[nextUFOId] = {211 id: nextUFOId,212 position: {213 x: point.x,214 y: point.y215 },216 velocity: {217 x: 0,218 y: 0219 },220 radius: 0.1,221 speed: 0.25,222 stationaryTime: 5,223 remainingStationaryTime: 0.000001,224 timeBetweenShots: 2,225 timeUntilNextShot: 2,226 startingHealth: 10,227 remainingHealth: 10,228 goal: {229 x: 0,230 y: 0231 }232 };233 return ufos[nextUFOId++];234}235function processInput() {236 let inputToProcess = inputQueue;237 inputQueue = [];238 for (let input of inputToProcess) {239 if (activeClients.hasOwnProperty(input.id)) {240 activeClients[input.id].lastMessageId = input.data.messageId;241 switch(input.data.type) {242 case 'thrust':243 activeClients[input.id].player.thrust(input.data.elapsedTime, input.receiveTime - lastUpdateTime);244 lastUpdateTime = input.receiveTime;245 break;246 case 'rotate-right':247 activeClients[input.id].player.rotateRight(input.data.elapsedTime);248 break;249 case 'rotate-left':250 activeClients[input.id].player.rotateLeft(input.data.elapsedTime);251 break;252 case 'shoot':253 if (activeClients[input.id].player.shoot()) {254 fireProjectile(input.id);255 }256 break;257 default:;258 }259 }260 }261}262// Get a point dist units outside of the map.263function getRandomPerimeterPoint(dist=0) {264 let rectWidth = bounds.x.upper - bounds.x.lower;265 let rectHeight = bounds.y.upper - bounds.y.lower;266 let rand = 2 * Math.random() * (rectWidth + rectHeight);267 if (rand < rectWidth) {268 return { x: rand + bounds.x.lower, y: bounds.y.lower - dist };269 }270 rand -= rectWidth;271 if (rand < rectWidth) {272 return { x: rand + bounds.x.lower, y: bounds.y.upper + dist };273 }274 rand -= rectWidth;275 if (rand < rectHeight) {276 return { x: bounds.x.lower - dist, y: rand + bounds.y.lower };277 }278 rand -= rectHeight279 return { x: bounds.x.upper + dist, y: rand + bounds.y.lower };280}281function updateAsteroids(elapsedTime) {282 for (let id in asteroids) {283 asteroids[id].position.x += asteroids[id].velocity.x * elapsedTime / 1000;284 asteroids[id].position.y += asteroids[id].velocity.y * elapsedTime / 1000;285 if (asteroids[id].position.x < bounds.x.lower - asteroids[id].radius) {286 asteroids[id].position.x = bounds.x.upper + asteroids[id].radius;287 } else if (asteroids[id].position.x > bounds.x.upper + asteroids[id].radius) {288 asteroids[id].position.x = bounds.x.lower - asteroids[id].radius;289 }290 if (asteroids[id].position.y < bounds.y.lower - asteroids[id].radius) {291 asteroids[id].position.y = bounds.y.upper + asteroids[id].radius;292 } else if (asteroids[id].position.y > bounds.y.upper + asteroids[id].radius) {293 asteroids[id].position.y = bounds.y.lower - asteroids[id].radius;294 }295 }296 if (Object.keys(activeClients).length > 0) {297 if (timeUntilNextAsteroid > 0 && Object.keys(asteroids).length < MAX_ASTEROIDS) {298 timeUntilNextAsteroid -= elapsedTime / 1000;299 }300 if (timeUntilNextAsteroid <= 0) {301 let newAsteroid = createAsteroid();302 for (let id in activeClients) {303 activeClients[id].socket.emit('new-asteroid', newAsteroid);304 }305 timeUntilNextAsteroid += ASTEROID_COUNTDOWN;306 }307 }308}309function updateProjectiles(elapsedTime) {310 for (let id in projectiles) {311 projectiles[id].position.x += projectiles[id].velocity.x * elapsedTime / 1000;312 projectiles[id].position.y += projectiles[id].velocity.y * elapsedTime / 1000;313 projectiles[id].remainingLifetime -= elapsedTime / 1000;314 if (projectiles[id].position.x < bounds.x.lower ||315 projectiles[id].position.x > bounds.x.upper ||316 projectiles[id].position.y < bounds.y.lower ||317 projectiles[id].position.y > bounds.y.upper) {318 delete projectiles[id];319 } else if (projectiles[id].remainingLifetime <= 0) {320 for (let clientId in activeClients) {321 activeClients[clientId].socket.emit('projectile-fade', {322 id: id323 });324 }325 delete projectiles[id];326 }327 }328}329function updateUFOProjectiles(elapsedTime) {330 for (let id in ufoProjectiles) {331 ufoProjectiles[id].position.x += ufoProjectiles[id].velocity.x * elapsedTime / 1000;332 ufoProjectiles[id].position.y += ufoProjectiles[id].velocity.y * elapsedTime / 1000;333 ufoProjectiles[id].remainingLifetime -= elapsedTime / 1000;334 if (ufoProjectiles[id].position.x < bounds.x.lower ||335 ufoProjectiles[id].position.x > bounds.x.upper ||336 ufoProjectiles[id].position.y < bounds.y.lower ||337 ufoProjectiles[id].position.y > bounds.y.upper) {338 delete ufoProjectiles[id];339 } else if (ufoProjectiles[id].remainingLifetime <= 0) {340 for (let clientId in activeClients) {341 activeClients[clientId].socket.emit('ufo-projectile-fade', {342 id: id343 });344 }345 delete ufoProjectiles[id];346 }347 }348}349function updateUFOs(elapsedTime) {350 for (let id in ufos) {351 if (ufos[id].remainingStationaryTime > 0) {352 ufos[id].remainingStationaryTime -= elapsedTime / 1000;353 if (ufos[id].remainingStationaryTime <= 0) {354 ufos[id].goal.x = Math.random() * (bounds.x.upper - bounds.x.lower) + bounds.x.lower;355 ufos[id].goal.y = Math.random() * (bounds.y.upper - bounds.y.lower) + bounds.y.lower;356 let dist = Math.sqrt(Math.pow(ufos[id].goal.x - ufos[id].position.x, 2) + Math.pow(ufos[id].goal.y - ufos[id].position.y, 2));357 ufos[id].velocity.x = ufos[id].speed * (ufos[id].goal.x - ufos[id].position.x) / dist;358 ufos[id].velocity.y = ufos[id].speed * (ufos[id].goal.y - ufos[id].position.y) / dist;359 for (let clientId in activeClients) {360 activeClients[clientId].socket.emit('ufo-start', {361 id: id,362 velocity: ufos[id].velocity363 });364 }365 }366 } else {367 if (Math.pow(ufos[id].goal.x - ufos[id].position.x, 2) + Math.pow(ufos[id].goal.y - ufos[id].position.y, 2) < 0.01) {368 ufos[id].velocity.x = 0;369 ufos[id].velocity.y = 0;370 ufos[id].remainingStationaryTime += ufos[id].stationaryTime;371 for (let clientId in activeClients) {372 activeClients[clientId].socket.emit('ufo-stop', {373 id: id,374 position: ufos[id].position375 });376 }377 } else {378 ufos[id].position.x += ufos[id].velocity.x * elapsedTime / 1000;379 ufos[id].position.y += ufos[id].velocity.y * elapsedTime / 1000;380 }381 }382 ufos[id].timeUntilNextShot -= elapsedTime / 1000;383 if (ufos[id].timeUntilNextShot <= 0) {384 ufos[id].timeUntilNextShot += ufos[id].timeBetweenShots;385 let angle = Math.random() * 360;386 let ufoProjectile = {387 ufoId: id,388 ufoProjectileId: nextUFOProjectileId,389 position: {390 x: ufos[id].position.x,391 y: ufos[id].position.y392 },393 velocity: {394 x: Math.sin(angle * Math.PI / 180),395 y: -Math.cos(angle * Math.PI / 180)396 },397 angle: angle,398 radius: 1 / 20,399 remainingLifetime: 1.0400 };401 ufoProjectiles[nextUFOProjectileId++] = ufoProjectile;402 for (let clientId in activeClients) {403 activeClients[clientId].socket.emit('new-ufo-projectile', ufoProjectile);404 }405 }406 }407 if (Object.keys(activeClients).length > 0) {408 if (timeUntilNextUFO > 0 && Object.keys(ufos).length < MAX_UFOS) {409 timeUntilNextUFO -= elapsedTime / 1000;410 }411 if (timeUntilNextUFO <= 0) {412 let newUfo = createUFO();413 for (let id in activeClients) {414 activeClients[id].socket.emit('new-ufo', newUfo);415 }416 timeUntilNextUFO += UFO_COUNTDOWN;417 }418 }419};420function respawn(playerId) {421 let respawnPoint = findSafePoint();422 activeClients[playerId].player.position.x = respawnPoint.x;423 activeClients[playerId].player.position.y = respawnPoint.y;424 activeClients[playerId].player.velocity.x = 0;425 activeClients[playerId].player.velocity.y = 0;426 activeClients[playerId].player.angle = Math.random() * 360;427 let respawnData = {428 id: playerId,429 position: activeClients[playerId].player.position,430 angle: activeClients[playerId].player.angle431 };432 activeClients[playerId].socket.emit('respawn-self', respawnData);433 for (let otherId in activeClients) {434 if (otherId !== playerId) {435 activeClients[otherId].socket.emit('respawn-other', respawnData);436 }437 }438}439function detectCollisions() {440 for (let asteroidId in asteroids) {441 // Asteroid - player collisions.442 for (let playerId in activeClients) {443 if (activeClients[playerId].player.alive) {444 if (Math.pow(activeClients[playerId].player.position.x - asteroids[asteroidId].position.x, 2) +445 Math.pow(activeClients[playerId].player.position.y - asteroids[asteroidId].position.y, 2) <=446 Math.pow(activeClients[playerId].player.radius + asteroids[asteroidId].radius, 2)) {447 activeClients[playerId].player.destroy(() => respawn(playerId));448 let scoreChange = -100449 activeClients[playerId].player.addToScore(scoreChange);450 activeClients[playerId].socket.emit('crash-self', {451 score: scoreChange452 });453 for (let otherId in activeClients) {454 if (otherId !== playerId) {455 activeClients[otherId].socket.emit('crash-other', {456 id: playerId,457 score: scoreChange458 });459 }460 }461 }462 }463 }464 // Asteroid - UFO collisions.465 for (let ufoId in ufos) {466 if (Math.pow(ufos[ufoId].position.x - asteroids[asteroidId].position.x, 2) +467 Math.pow(ufos[ufoId].position.y - asteroids[asteroidId].position.y, 2) <=468 Math.pow(asteroids[asteroidId].radius + ufos[ufoId].radius, 2)) {469 delete ufos[ufoId];470 for (let id in activeClients) {471 activeClients[id].socket.emit('ufo-destroyed', {472 ufoId: ufoId473 });474 }475 }476 }477 let asteroidDestroyed = false;478 // Asteroid - projectile collisions.479 for (let projectileId in projectiles) {480 if (Math.pow(projectiles[projectileId].position.x - asteroids[asteroidId].position.x, 2) +481 Math.pow(projectiles[projectileId].position.y - asteroids[asteroidId].position.y, 2) <=482 Math.pow(asteroids[asteroidId].radius + projectiles[projectileId].radius, 2)) {483 playerAsteroidHit(asteroidId, projectileId);484 asteroidDestroyed = true;485 break;486 }487 }488 if (!asteroidDestroyed) {489 // Asteroid - ufoProjectile collisions.490 for (let ufoProjectileId in ufoProjectiles) {491 if (Math.pow(ufoProjectiles[ufoProjectileId].position.x - asteroids[asteroidId].position.x, 2) +492 Math.pow(ufoProjectiles[ufoProjectileId].position.y - asteroids[asteroidId].position.y, 2) <=493 Math.pow(asteroids[asteroidId].radius + ufoProjectiles[ufoProjectileId].radius, 2)) {494 ufoAsteroidHit(asteroidId, ufoProjectileId);495 break;496 }497 }498 }499 }500 for (let ufoId in ufos) {501 // UFO - player collisions. (only player dies).502 for (let playerId in activeClients) {503 if (activeClients[playerId].player.alive) {504 if (Math.pow(activeClients[playerId].player.position.x - ufos[ufoId].position.x, 2) +505 Math.pow(activeClients[playerId].player.position.y - ufos[ufoId].position.y, 2) <=506 Math.pow(activeClients[playerId].player.radius + ufos[ufoId].radius, 2)) {507 activeClients[playerId].player.destroy(() => respawn(playerId));508 let scoreChange = -100509 activeClients[playerId].player.addToScore(scoreChange);510 activeClients[playerId].socket.emit('crash-self', {511 score: scoreChange512 });513 for (let otherId in activeClients) {514 if (otherId !== playerId) {515 activeClients[otherId].socket.emit('crash-other', {516 id: playerId,517 score: scoreChange518 });519 }520 }521 }522 }523 }524 // UFO - projectile collisions.525 for (let projectileId in projectiles) {526 if (Math.pow(projectiles[projectileId].position.x - ufos[ufoId].position.x, 2) +527 Math.pow(projectiles[projectileId].position.y - ufos[ufoId].position.y, 2) <=528 Math.pow(ufos[ufoId].radius + projectiles[projectileId].radius, 2)) {529 ufos[ufoId].remainingHealth -= 1;530 if (ufos[ufoId].remainingHealth <= 0) {531 delete ufos[ufoId];532 let score = 500;533 if (activeClients.hasOwnProperty(projectiles[projectileId].playerId)) {534 activeClients[projectiles[projectileId].playerId].player.addToScore(score);535 }536 for (let id in activeClients) {537 activeClients[id].socket.emit('ufo-destroyed', {538 ufoId: ufoId,539 projectileId: projectileId,540 score: score541 });542 }543 } else {544 for (let id in activeClients) {545 activeClients[id].socket.emit('ufo-hit', {546 ufoId: ufoId,547 projectileId: projectileId548 });549 }550 }551 delete projectiles[projectileId];552 break;553 }554 }555 }556 for (let playerId in activeClients) {557 if (activeClients[playerId].player.alive) {558 // Player - ufoProjectile collisions.559 for (let ufoProjectileId in ufoProjectiles) {560 if (Math.pow(activeClients[playerId].player.position.x - ufoProjectiles[ufoProjectileId].position.x, 2) +561 Math.pow(activeClients[playerId].player.position.y - ufoProjectiles[ufoProjectileId].position.y, 2) <=562 Math.pow(activeClients[playerId].player.radius + ufoProjectiles[ufoProjectileId].radius, 2)) {563 activeClients[playerId].player.destroy(() => respawn(playerId));564 let scoreChange = -100565 activeClients[playerId].player.addToScore(scoreChange);566 activeClients[playerId].socket.emit('crash-self', {567 score: scoreChange568 });569 for (let otherId in activeClients) {570 if (otherId !== playerId) {571 activeClients[otherId].socket.emit('crash-other', {572 id: playerId,573 score: scoreChange574 });575 }576 }577 }578 }579 }580 }581}582function update(elapsedTime) {583 for (let id in activeClients) {584 activeClients[id].player.update(elapsedTime);585 if (activeClients[id].player.alive) {586 if (activeClients[id].player.position.x < bounds.x.lower - activeClients[id].player.radius ||587 activeClients[id].player.position.x > bounds.x.upper + activeClients[id].player.radius ||588 activeClients[id].player.position.y < bounds.y.lower - activeClients[id].player.radius ||589 activeClients[id].player.position.y > bounds.y.upper + activeClients[id].player.radius) {590 activeClients[id].player.destroy(() => respawn(id));591 let scoreChange = -100;592 activeClients[id].player.addToScore(scoreChange);593 activeClients[id].socket.emit('lost-self', {594 score: scoreChange595 });596 for (let otherId in activeClients) {597 if (otherId !== id) {598 activeClients[otherId].socket.emit('lost-other', {599 id: id,600 score: scoreChange601 })602 }603 }604 }605 }606 }607 updateAsteroids(elapsedTime);608 updateProjectiles(elapsedTime);609 updateUFOProjectiles(elapsedTime);610 updateUFOs(elapsedTime);611 detectCollisions();612}613function updateClients(elapsedTime) {614 for (let id in activeClients) {615 if (activeClients[id].player.reportUpdate) {616 let update = {617 id: id,618 position: activeClients[id].player.position,619 velocity: activeClients[id].player.velocity,620 angle: activeClients[id].player.angle,621 lastMessageId: activeClients[id].player.lastMessageId,622 updateWindow: elapsedTime623 }624 activeClients[id].socket.emit('update-self', update);625 for (let otherId in activeClients) {626 if (otherId !== id) {627 activeClients[otherId].socket.emit('update-other', update);628 }629 }630 activeClients[id].player.reportUpdate = false;631 }632 }633 lastUpdateTime = present();634}635function gameLoop(currentTime, elapsedTime) {636 processInput();637 update(elapsedTime);638 updateClients(elapsedTime);639 if (!quit) {640 setTimeout(() => {641 let now = present();642 gameLoop(now, now - currentTime);643 }, UPDATE_RATE_MS);644 }645}646const safePointGridWidth = 5;647const safePointGridHeight = 5;648function findSafePoint() {649 let bestX = null;650 let bestY = null;651 let maxDist = 0;652 for (let i = 0; i < safePointGridHeight; i++) {653 let y = (i + 1) * (bounds.y.upper - bounds.y.lower) / (safePointGridHeight + 1);654 for (let j = 0; j < safePointGridWidth; j++) {655 let x = (j + 1) * (bounds.x.upper - bounds.x.lower) / (safePointGridWidth + 1);656 let minDistSquared = Infinity;657 for (let asteroidId in asteroids) {658 let distSquared = Math.pow(x - asteroids[asteroidId].position.x, 2) + Math.pow(y - asteroids[asteroidId].position.y, 2);659 if (distSquared < minDistSquared) {660 minDistSquared = distSquared;661 }662 }663 if (minDistSquared > maxDist) {664 maxDist = minDistSquared;665 bestX = x;666 bestY = y;667 }668 }669 }670 return { x: bestX, y: bestY };671}672// function saveHighScores() {673// fs.readFile(HIGH_SCORES_FILE_NAME, (err, data) => {674// let scoresList = [];675// if (err === null) {676// scoresList = JSON.parse(data);677// }678// for (let id in activeClients) {679// scoresList.push({680// name: activeClients[id].player.name,681// score: activeClients[id].player.score682// });683// }684// scoresList.sort((a, b) => { return b.score - a.score });685// while (scoresList.length > MAX_HIGH_SCORES) {686// scoresList.pop();687// }688// fs.writeFile(HIGH_SCORES_FILE_NAME, JSON.stringify(scoresList), (err) => {689// if (err) throw err;690// console.log('High scores saved');691// })692// });693// }694function saveScoreAndQuit(playerId) {695 fs.readFile(HIGH_SCORES_FILE_NAME, (err, data) => {696 let scoresList = [];697 if (err === null && data.length > 0) {698 scoresList = JSON.parse(data);699 }700 let score = {701 name: activeClients[playerId].player.name,702 score: activeClients[playerId].player.score703 };704 scoresList.push(score);705 scoresList.sort((a, b) => { return b.score - a.score });706 while (scoresList.length > MAX_HIGH_SCORES) {707 scoresList.pop();708 }709 fs.writeFile(HIGH_SCORES_FILE_NAME, JSON.stringify(scoresList), (err) => {710 if (err) throw err;711 console.log('High scores saved');712 });713 let index = scoresList.findIndex((i) => i === score);714 if (index !== -1) {715 // New high score (top 10)716 activeClients[playerId].socket.emit('leave-ack', {717 record: index718 });719 } else {720 activeClients[playerId].socket.emit('leave-ack', {});721 }722 delete activeClients[playerId];723 for (let id in activeClients) {724 activeClients[id].socket.emit('leave-other', {725 id: playerId726 });727 }728 729 if (Object.keys(activeClients).length === 0) {730 console.log('Ending game...');731 asteroids = {};732 projectiles = {};733 ufos = {};734 ufoProjectiles = {};735 }736 });737}738function initialize(server) {739 let io = require('socket.io')(server);740 io.on('connection', function(socket) {741 console.log('Client connected');742 socket.emit('connect-ack', {});743 clients[socket.id] = {744 id: socket.id,745 socket: socket,746 player: null,747 lastMessageId: 0748 };749 socket.on('join', function(data) {750 if (Object.keys(activeClients).length == 0) {751 console.log('Starting game...');752 initializeAsteroids();753 timeUntilNextUFO = UFO_COUNTDOWN;754 timeUntilNextAsteroid = ASTEROID_COUNTDOWN;755 }756 let startPoint = findSafePoint();757 let player = Player.create(data.name, startPoint.x, startPoint.y);758 clients[socket.id].player = player;759 activeClients[socket.id] = clients[socket.id];760 socket.emit('join-ack', {761 id: socket.id,762 name: player.name,763 position: player.position,764 velocity: player.velocity,765 angle: player.angle,766 radius: player.radius,767 asteroids: asteroids,768 projectiles: projectiles,769 ufos: ufos,770 bounds: bounds771 });772 for (let id in activeClients) {773 if (socket.id !== id) {774 activeClients[id].socket.emit('join-other', {775 id: socket.id,776 name: player.name,777 position: player.position,778 velocity: player.velocity,779 angle: player.angle,780 radius: player.radius,781 alive: player.alive,782 score: player.score783 });784 socket.emit('join-other', {785 id: id,786 name: activeClients[id].player.name,787 position: activeClients[id].player.position,788 velocity: activeClients[id].player.velocity,789 angle: activeClients[id].player.angle,790 radius: activeClients[id].player.radius,791 alive: activeClients[id].player.alive,792 score: activeClients[id].player.score793 });794 }795 }796 });797 socket.on('input', function(data) {798 inputQueue.push({799 id: socket.id,800 data: data,801 receiveTime: present()802 });803 });804 socket.on('leave', function(data) {805 saveScoreAndQuit(socket.id);806 });807 socket.on('get-high-scores', function() {808 fs.readFile(HIGH_SCORES_FILE_NAME, (err, data) => {809 let scoresList = [];810 if (err === null) {811 scoresList = JSON.parse(data);812 }813 socket.emit('high-scores', { highScores: scoresList, maxHighScores: MAX_HIGH_SCORES });814 });815 });816 socket.on('disconnect', function() {817 console.log('Client disconnected');818 if (activeClients.hasOwnProperty(socket.id)) {819 for (let id in activeClients) {820 if (socket.id !== id) {821 activeClients[id].socket.emit('leave-other', {822 id: socket.id823 });824 }825 }826 }827 delete activeClients[socket.id];828 if (Object.keys(activeClients).length === 0) {829 console.log('Ending game...');830 asteroids = {};831 projectiles = {};832 ufos = {};833 ufoProjectiles = {};834 }835 });836 });837 gameLoop(present(), 0);838}...
index.js
Source:index.js
1// ENUM CODES - to be synced with client2var ENUM_CODES = {3 LOGIN: { SUCCESS: 0, EXISTING_NAME: 1, ALREADY_LOGGED_IN: 2, INVALID_NAME: 3, ERROR: 4 },4 STATUS: { IDLE: 0, PLAYING: 1}5};6var express = require('express');7var app = express();8var server = require('http').createServer(app);9var io = require('socket.io')(server);10var port = process.env.PORT || 8082;11 12server.listen(port, function () {13 console.log('Server listening at port %d', port);14});15app.use(express.static(__dirname + '/public'));16// Server side settings for the client17var serverSettings = { gridCount: {w: 32, h: 32}, gridSize: {w: 100, h: 100}, gridCentre: {x: 0, y: 0}, speedMod: 4, tick: 0.03, tickMS: 1, initPlyRadius: 24 };18serverSettings.totalSize = { w: serverSettings.gridCount.w*serverSettings.gridSize.w, h: serverSettings.gridCount.h*serverSettings.gridSize.h };19serverSettings.gridCentre = { x: serverSettings.totalSize.w*-0.5, y: serverSettings.totalSize.h*-0.5 };20serverSettings.tickMS = serverSettings.tick * 1000;21 22// Rolling client counter and store for all client objects23var idCounter = 1;24var activeClients = [];25// Food pellets26var foodPellets = [];27var activePellets = 256;28function generatePellet() { return {pos: {x: Math.floor(Math.random()*serverSettings.totalSize.w + serverSettings.gridCentre.x), y: Math.floor(Math.random()*serverSettings.totalSize.h + serverSettings.gridCentre.y)}}; }29for (var i = 0; i < activePellets; i++) {30 foodPellets.push(generatePellet());31}32// Convert a HSV colour to RGB colour space33function HSVtoRGB(h, s, v) {34 var r, g, b, i, f, p, q, t;35 if (arguments.length === 1) {36 s = h.s, v = h.v, h = h.h;37 }38 i = Math.floor(h * 6);39 f = h * 6 - i;40 p = v * (1 - s);41 q = v * (1 - f * s);42 t = v * (1 - (1 - f) * s);43 switch (i % 6) {44 case 0: r = v, g = t, b = p; break;45 case 1: r = q, g = v, b = p; break;46 case 2: r = p, g = v, b = t; break;47 case 3: r = p, g = q, b = v; break;48 case 4: r = t, g = p, b = v; break;49 case 5: r = v, g = p, b = q; break;50 }51 return {52 r: Math.round(r * 255),53 g: Math.round(g * 255),54 b: Math.round(b * 255)55 };56}57// Log the message along side the client's unique address information58function log (clientAddress, message) {59 console.log(clientAddress.remoteAddress + ":" + clientAddress.remotePort + " > " + message);60}61function lerp (value, targetValue, fraction) { return value + (targetValue - value) * fraction; }62// Clamp the value inbetween the max and min parameters63function clamp (value,max,min) { 64 if (value < min) { return min; }65 else if (value > max) { return max; }66 return value;67}68// Clamp the incoming position to within the server's world bounds69function clampToBounds (pos) { 70 pos.x = clamp(pos.x, -serverSettings.gridCentre.x, serverSettings.gridCentre.x);71 pos.y = clamp(pos.y, -serverSettings.gridCentre.y, serverSettings.gridCentre.y);72 return pos;73}74// Function to be ran every tick of the server, for performing physics updates75function serverTick () {76 for (var i = 0; i < activeClients.length; i++) {77 if (activeClients[i].alive) {78 activeClients[i].vel.x *= 0.9; activeClients[i].vel.y *= 0.9;79 if (activeClients[i].mPressed) {80 activeClients[i].vel.x += activeClients[i].accel.x * serverSettings.tick * 384;81 activeClients[i].vel.y += activeClients[i].accel.y * serverSettings.tick * 384;82 }83 var tmpMult = (0.3 + (1/((activeClients[i].smoothedRadius - serverSettings.initPlyRadius + 5) / 5))*0.7);84 activeClients[i].pos.x += activeClients[i].vel.x * serverSettings.tick * serverSettings.speedMod * tmpMult;85 activeClients[i].pos.y += activeClients[i].vel.y * serverSettings.tick * serverSettings.speedMod * tmpMult;86 activeClients[i].pos = clampToBounds(activeClients[i].pos);87 activeClients[i].smoothedRadius = lerp (activeClients[i].smoothedRadius, activeClients[i].radius, 0.25);88 // Check if player collided with food pellets89 for (var j = 0; j < foodPellets.length; j++) {90 var dist = Math.sqrt(Math.pow(foodPellets[j].pos.x - activeClients[i].pos.x,2) + Math.pow(foodPellets[j].pos.y - activeClients[i].pos.y,2));91 if (dist < 8 + activeClients[i].radius) {92 foodPellets[j] = generatePellet();93 for (var k = 0; k < activeClients.length; k++) {94 activeClients[k].new_pellets.push({index: j, pos: foodPellets[j].pos});95 }96 activeClients[i].radius += 2;97 }98 }99 // Check if player collided with another player100 for (var j = 0; j < activeClients.length; j++) {101 if (i != j && activeClients[i].alive && activeClients[j].alive) {102 var dist = Math.sqrt(Math.pow(activeClients[j].pos.x - activeClients[i].pos.x,2) + Math.pow(activeClients[j].pos.y - activeClients[i].pos.y,2)) - activeClients[i].radius - activeClients[j].radius;103 if (dist <= 0) {104 var winningIndex, losingIndex;105 if (activeClients[i].radius > activeClients[j].radius) { winningIndex = i; losingIndex = j; }106 else { winningIndex = j; losingIndex = i; }107 activeClients[winningIndex].radius += activeClients[losingIndex].radius * 0.75;108 activeClients[losingIndex].alive = false;109 }110 }111 }112 }113 }114}115// Call the server tick function after the value in the server settings has elapsed116setInterval(serverTick, serverSettings.tickMS);117// Function used to update every client with all the current players names and colours118function syncConstPlyData () {119 var syncData = {};120 for (var i = 0; i < activeClients.length; i++) {121 syncData[activeClients[i].id] = {hue: activeClients[i].hue, nickname: activeClients[i].nickname };122 }123 io.sockets.emit('sync_const_data', syncData);124}125// Upon a use connecting126io.on('connection', function (socket) {127 var broadcastTimer;128 var clientAddress = socket.request.connection;129 var clientData;130 socket.emit('server_settings', {settings: serverSettings, enums: ENUM_CODES});131 socket.emit('server_message', { message: 'Welcome to Cheesy Agar!' });132 function broadcastPositionData () {133 var otherClientsData = [];134 for (var i = 0; i < activeClients.length; i++) {135 if (activeClients[i]) {136 if (activeClients[i].id != clientData.id) { otherClientsData.push({ id: activeClients[i].id, pos: activeClients[i].pos, vel: activeClients[i].vel, accel: activeClients[i].accel, mPressed: activeClients[i].mPressed, radius: activeClients[i].smoothedRadius }); }137 }138 }139 socket.emit('update', { othersData: otherClientsData, plyData: { pos: clientData.pos, vel: clientData.vel, radius: clientData.smoothedRadius, alive: clientData.alive }, pellets_created: clientData.new_pellets });140 clientData.new_pellets = [];141 if (!clientData.alive) {142 if (broadcastTimer) {143 clearInterval(broadcastTimer);144 for (var i = 0; i < activeClients.length; i++) {145 if (activeClients[i].id == clientData.id) {146 activeClients.splice(i, 1);147 log(clientAddress, 'Client has disconnected, removing id = ' + clientData.id + ' nickname = ' + clientData.nickname);148 socket.broadcast.emit('server_message', { message: clientData.nickname+' has disconnected' });149 break;150 }151 }152 //delete clientData;153 }154 }155 }156 log(clientAddress, 'Client has connected');157 // Provide the new client a unique id158 socket.on('login', function(data) {159 if (typeof clientData === 'undefined' || (clientData && !clientData.alive)) {160 if (data.nickname == '') {161 log(clientAddress, 'Attempted login with name = ' + data.nickname + ', but the name is invalid');162 socket.emit('login', { code: ENUM_CODES.LOGIN.INVALID_NAME });163 }164 else {165 var existing = false;166 for (var i = 0; i < activeClients.length; i++) {167 if (activeClients[i].nickname == data.nickname) {168 existing = true;169 break;170 }171 }172 if (!existing && data.nickname != '') { 173 clientData = { id: idCounter, nickname: data.nickname, hue: 0, mPressed: false, pos: {x: 0, y: 0}, vel: {x: 0, y: 0}, accel: {x: 0, y: 0}, radius: 24, smoothedRadius: 0, new_pellets: [], alive: true };174 clientData.hue = Math.random(); clientData.smoothedRadius = clientData.radius;175 // Log the loggin message to the server's console, add the new client to the client array, increment the id counter, sync player data, send a server message to all clients176 log(clientAddress, 'Client has logged in with nickname = ' + clientData.nickname + ', assigned id = ' + clientData.id);177 socket.emit('login', { code: ENUM_CODES.LOGIN.SUCCESS, userId: clientData.id, nickname: clientData.nickname, hue: clientData.hue, foodPellets: foodPellets });178 socket.broadcast.emit('server_message', { message: clientData.nickname+' has connected' });179 activeClients.push(clientData);180 idCounter++;181 syncConstPlyData();182 broadcastTimer = setInterval(broadcastPositionData, serverSettings.tickMS);183 }184 else {185 log(clientAddress, 'Attempted login with name = ' + data.nickname + ', but it already exists');186 socket.emit('login', { code: ENUM_CODES.LOGIN.EXISTING_NAME });187 }188 }189 }190 else {191 log(clientAddress, 'Attempted login with name = ' + data.nickname + ', but are already logged in');192 socket.emit('login', { code: ENUM_CODES.LOGIN.ALREADY_LOGGED_IN });193 }194 });195 // Collect client data and perform validation checks upon the data to ensure no tampering196 socket.on('update', function (data) {197 clientData.accel = data.accel;198 clientData.mPressed = data.mPressed;199 var accelMagnitude = Math.sqrt(Math.pow(clientData.accel.x,2) + Math.pow(clientData.accel.y,2));200 if (accelMagnitude > 1) {201 // Suppress warnings if only a little over the limit202 if (accelMagnitude > 1.01) {203 log(clientAddress, 'Warning, invalid accel player values! id: ' + clientData.id + ' speed: ' + accelMagnitude + ' x: ' + clientData.accel.x + ' y: ' + clientData.accel.y);204 }205 clientData.accel.x /= accelMagnitude;206 clientData.accel.y /= accelMagnitude;207 }208 for (var i = 0; i < activeClients.length; i++) {209 if (clientData && activeClients[i].id == clientData.id) {210 activeClients[i].accel = clientData.accel;211 activeClients[i].mPressed = clientData.mPressed;212 break;213 }214 }215 });216 // Upon client disconnect remove client217 socket.on('disconnect', function () {218 if (typeof clientData !== 'undefined') {219 for (var i = 0; i < activeClients.length; i++) {220 if (activeClients[i].id == clientData.id) {221 activeClients.splice(i, 1);222 log(clientAddress, 'Client has disconnected, removing id = ' + clientData.id + ' nickname = ' + clientData.nickname);223 socket.broadcast.emit('server_message', { message: clientData.nickname+' has disconnected' });224 break;225 }226 }227 } 228 else {229 log(clientAddress, 'Client has disconnected');230 }231 });...
listeners.js
Source:listeners.js
1var renderTargetsReqVar;2var renderOnRecordTargetsReqVar;34// Renders UI elements listed in 'renderWhileActiveclients', optionally doing5// another update round-trip to Pazpar2 when done.6function renderTargets(doRefresh) {7 // console.log('rendering ' + renderWhileActiveclients);8 var sourcecomp = document.getElementById("pz2watch:activeclientsField");9 jsf.ajax.request(sourcecomp, null, {10 render : renderWhileActiveclients11 });12 if (doRefresh) {13 // console.log('Will do another ajax request after a timeout in order to14 // render: pz2watch:activeclientsField');15 renderTargetsReqVar = setTimeout(function() {16 // console.log('Making request for pz2watch:activeclientsField');17 jsf.ajax.request(sourcecomp, null, {18 render : "pz2watch:activeclientsField"19 });20 }, 500);21 } else {22 // console.log("No further updates from server requested");23 }24}2526// Renders UI elements listed in 'renderWhileActiveclientsRecord', optionally27// doing28// another record request when done.29function renderOnRecordTargets(doRefresh) {30 // console.log('rendering ' + renderWhileActiveclientsRecord);31 var sourcecomp = document.getElementById("pz2watch:activeclientsFieldRecord");32 jsf.ajax.request(sourcecomp, null, {33 render : renderWhileActiveclientsRecord34 });35 if (doRefresh) {36 // console.log('Will do another ajax request after a timeout in order to37 // render: pz2watch:activeclientsFieldRecord');38 renderOnRecordTargetsReqVar = setTimeout(function() {39 // console.log('Making request for pz2watch:activeclientsFieldRecord');40 jsf.ajax.request(sourcecomp, null, {41 render : "pz2watch:activeclientsFieldRecord"42 });43 }, 1000);44 } else {45 // console.log("No further updates from server requested");46 }47}4849// Listens for browser initiated changes to 'window.location.hash' and sends 50// the hash key changes to the back-end, to have the back-end pull up a previous 51// Pazpar2 state.52// 53// See also: The field in pz2watch.xhtml, the StateListener function below,54// the method Pz2Bean.handleQueryStateChanges(), and the classes 55// Pazpar2State and StateManager for a complete picture of browser history 56// handling.57function windowlocationhashListener() {58 if (trackHistory) {59 60 var stateKey = document.getElementById("pz2watch:windowlocationhash");61 // console.log("browser hash update response detected.");62 // console.log("pz2watch:windowlocationhash: [" + stateKey.value + "]");63 // console.log("window.location.hash: [" + window.location.hash + "]");64 if (window.location.hash != stateKey.value) { 65 if (window.location.hash) {66 //console.log("updating pz2watch:windowlocationhash with new window.location.hash [" + window.location.hash + "]");67 stateKey.value = window.location.hash;68 //console.log("firing pz2watch:windowlocationhash onChange");69 stateKey.onchange();70 } else if (stateKey.value) {71 //console.log("updating window.location.hash with pz2watch:windowlocationhash [" + stateKey.value + "]");72 window.location.hash = stateKey.value;73 //console.log("firing pz2watch:windowlocationhash onChange");74 stateKey.onchange();75 } 76 } else {77 //console.log("State hash already has the value of the new browser hash - not updating state hash");78 }79 }80}8182// Listens for ViewExpiredException message. Reloads the current page, stripped83// of84// it's jsessionid and hash content85function viewExpirationListener(data) {86 if (data.status === "success" && data.responseXML) {87 var errorElements = data.responseXML.getElementsByTagName("error-name");88 if (errorElements.length > 0) {89 var errorname = errorElements.item(0).textContent90 || errorElements.item(0).text;91 if (errorname === "class javax.faces.application.ViewExpiredException") {92 var newloc = window.location.protocol + "//" + window.location.host93 + window.location.pathname.replace(/;jsessionid.*/, '');94 alert('Sorry, this session has expired. A new one will be loaded.');95 window.location.replace(newloc);96 }97 }98 }99100}101102function errorListener(data) {103 // alert(data.toSource());104 if (data.source.name === "pz2watch:activeclientsField") {105 alert("This occurred when polling: ["106 + data.description107 + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");108 } else {109 var pattern = /viewId.*could not be restored./;110 if (pattern.test(data.description)) {111 // ignore - caught by view expiration listener112 } else {113 alert("An error ["114 + data.errorName + ": " +data.description115 + "] was triggered by ["116 + data.source.name117 + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");118 }119 }120}121122// Composite listener, invoking all field update listeners123function fieldUpdateListener(data) {124 if (data.status === "success") {125 var updates = data.responseXML.getElementsByTagName("update");126 for ( var i = 0, max = updates.length; i < max; i++) {127 var lsnri = fieldListeners.getListener(updates[i].getAttribute("id"));128 if (lsnri) {129 lsnri.invoke(updates[i]);130 }131 }132 }133}134135var Pz2listeners = function() {136 var lsnrs = {};137 this.addListener = function(key, lsnr) {138 lsnrs[key] = lsnr;139 };140 this.getListener = function(key) {141 return lsnrs[key];142 };143};144145var fieldListeners = new Pz2listeners();146147// Listens for back-end initiated changes to the state key and updates148// window.location.hash with changes, to record them in browsing history149var StateListener = function() {150 this.invoke = function(field) {151 var stateKeyDoc = StringtoXML(field.textContent || field.text);152 var stateKeyValue = stateKeyDoc.childNodes[0].getAttribute("value");153 // console.log('Received state key update from the back-end: ' + stateKeyValue);154 if (stateKeyValue !== window.location.hash) {155 window.location.hash = stateKeyValue;156 // console.log("Browsers hash (window.location.hash) updated with [" + stateKeyValue + "]");157 } else {158 // console.log("Browsers hash (window.location.hash) already has the value [" + stateKeyValue + "]");159 }160 };161};162163// Listens for updates to general 'activeclients' field, then invokes164// renderTargets165var ActiveclientsListener = function() {166 this.invoke = function(field) {167 var updateDoc = StringtoXML(field.textContent || field.text);168 var activeClientsValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);169 // console.log('Activeclients response detected: ' + activeClientsValue);170 clearTimeout(renderTargetsReqVar);171 if (activeClientsValue > '0') {172 renderTargets(true);173 } else {174 renderTargets(false);175 }176 };177};178179// Listens for updates to record 'activeclients' field, then invokes180// renderOnRecordTargets181var ActiveclientsRecordListener = function() {182 this.invoke = function(field) {183 var updateDoc = StringtoXML(field.textContent || field.text);184 var activeClientsRecordValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);185 // console.log('Activeclients response for record detected: ' + activeClientsRecordValue);186 clearTimeout(renderOnRecordTargetsReqVar);187 if (activeClientsRecordValue > '0') {188 renderOnRecordTargets(true);189 } else {190 // console.log('Active clients is 0, final rendering');191 renderOnRecordTargets(false);192 }193 };194};195196// Inserts field update listeners, state listeners, view expired listener197// into Ajax response handling198jsf.ajax.addOnEvent(fieldUpdateListener);199jsf.ajax.addOnEvent(viewExpirationListener);200jsf.ajax.addOnError(errorListener);201202function StringtoXML(text) {203 var doc;204 if (window.ActiveXObject) {205 doc = new ActiveXObject('Microsoft.XMLDOM');206 doc.async = false;207 doc.loadXML(text);208 } else {209 var parser = new DOMParser();210 doc = parser.parseFromString(text, 'text/xml');211 }212 return doc;213}214215// Sets up field update listeners216var setUpListeners = function() {217 // console.log("Starts tracking activeclientsField, for 'show' and 'record'");218 fieldListeners.addListener("pz2watch:activeclientsField",219 new ActiveclientsListener());220 fieldListeners.addListener("pz2watch:activeclientsFieldRecord",221 new ActiveclientsRecordListener());222 if (trackHistory) {223 // console.log("Starts tracking windowlocationhash field");224 fieldListeners.addListener("pz2watch:windowlocationhash",225 new StateListener());226 // console.log("Setting listener for browser onhashchange");227 window.onload = window.onhashchange = windowlocationhashListener;228 }
...
Using AI Code Generation
1var BestPractice = require('./BestPractice.js');2var bestPractice = new BestPractice();3var activeClients = bestPractice.activeClients();4console.log(activeClients);5var BestPractice = require('./BestPractice.js');6var bestPractice = new BestPractice();7var activeClients = bestPractice.activeClients();8console.log(activeClients);9var BestPractice = function() {10 this.activeClients = function() {11 return "1,000,000";12 }13}14module.exports = BestPractice;15var Service = require('node-windows').Service;16var svc = new Service({17});18svc.on('install',function(){19 svc.start();20});21svc.install();
Using AI Code Generation
1var BestClient = require('./bestClient');2var testClient = new BestClient();3var testClient2 = new BestClient();4var testClient3 = new BestClient();5testClient.activeClients();6testClient2.activeClients();7testClient3.activeClients();8testClient.activeClients();9testClient2.activeClients();10testClient3.activeClients();11testClient.activeClients();12testClient2.activeClients();13testClient3.activeClients();14testClient.activeClients();15testClient2.activeClients();16testClient3.activeClients();17var BestClient = function () {18 this.activeClients = function () {19 console.log('Active clients are ' + BestClient.activeClientsCount);20 }21}22BestClient.activeClientsCount = 0;23BestClient.prototype = {24 addClient: function () {25 BestClient.activeClientsCount++;26 }27}28module.exports = BestClient;29var BestClient = require('./bestClient');30var testClient = new BestClient();31var testClient2 = new BestClient();
Using AI Code Generation
1var BestFit = require('./BestFit.js');2var bestFit = new BestFit();3 {name: 'client1', size: 100},4 {name: 'client2', size: 200},5 {name: 'client3', size: 50},6 {name: 'client4', size: 100},7 {name: 'client5', size: 200},8 {name: 'client6', size: 50},9 {name: 'client7', size: 100},10 {name: 'client8', size: 200},11 {name: 'client9', size: 50},12 {name: 'client10', size: 100},13 {name: 'client11', size: 200},14 {name: 'client12', size: 50},15 {name: 'client13', size: 100},16 {name: 'client14', size: 200},17 {name: 'client15', size: 50},18 {name: 'client16', size: 100},19 {name: 'client17', size: 200},20 {name: 'client18', size: 50},21 {name: 'client19', size: 100},22 {name: 'client20', size: 200},23 {name: 'client21', size: 50},24 {name: 'client22', size: 100},25 {name: 'client23', size: 200},26 {name: 'client24', size: 50},27 {name: 'client25', size: 100},28 {name: 'client26', size: 200},29 {name: 'client27', size: 50},30 {name: 'client28', size: 100},31 {name: 'client29', size: 200},32 {name: 'client30', size: 50},33 {name: 'client31', size: 100},34 {name: 'client32', size: 200},35 {name: 'client33', size: 50},36 {name: 'client34', size: 100},37 {name: 'client35', size: 200},38 {name: 'client36', size: 50},39 {name: 'client37
Using AI Code Generation
1var best = require('bestjs');2var client = new best.Client();3client.connect('localhost', 8080, function() {4 client.activeClients(function(err, clients) {5 if (err) {6 console.log(err);7 } else {8 console.log(clients);9 }10 });11});12var best = require('bestjs');13var client = new best.Client();14client.connect('localhost', 8080, function() {15 client.activeClients(function(err, clients) {16 if (err) {17 console.log(err);18 } else {19 console.log(clients);20 }21 });22});23var best = require('bestjs');24var client = new best.Client();25client.connect('localhost', 8080, function() {26 client.activeClients(function(err, clients) {27 if (err) {28 console.log(err);29 } else {30 console.log(clients);31 }32 });33});34var best = require('bestjs');35var client = new best.Client();36client.connect('localhost', 8080, function() {37 client.activeClients(function(err, clients) {38 if (err) {39 console.log(err);40 } else {41 console.log(clients);42 }43 });44});45var best = require('bestjs');46var client = new best.Client();47client.connect('localhost', 8080, function() {48 client.activeClients(function(err, clients) {49 if (err) {50 console.log(err);51 } else {52 console.log(clients);53 }54 });55});56var best = require('bestjs');57var client = new best.Client();58client.connect('localhost', 8080, function() {59 client.activeClients(function(err, clients) {60 if (err) {61 console.log(err);62 } else {63 console.log(clients);64 }65 });66});67var best = require('bestjs');
Using AI Code Generation
1var BestTimeToCall = require("./BestTimeToCall.js");2var bestTimeToCall = new BestTimeToCall();3bestTimeToCall.addCall("Fred", "2013-03-02 08:00");4bestTimeToCall.addCall("Fred", "2013-03-02 09:00");5bestTimeToCall.addCall("Fred", "2013-03-02 10:00");6bestTimeToCall.addCall("Fred", "2013-03-02 11:00");7bestTimeToCall.addCall("Fred", "2013-03-02 12:00");8bestTimeToCall.addCall("Fred", "2013-03-02 13:00");9bestTimeToCall.addCall("Fred", "2013-03-02 14:00");10bestTimeToCall.addCall("Fred", "2013-03-02 15:00");11bestTimeToCall.addCall("Fred", "2013-03-02 16:00");12bestTimeToCall.addCall("Fred", "2013-03-02 17:00");13bestTimeToCall.addCall("Fred", "2013-03-02 18:00");14bestTimeToCall.addCall("Fred", "2013-03-02 19:00");15bestTimeToCall.addCall("Fred", "2013-03-02 20:00");16bestTimeToCall.addCall("Fred", "2013-03-02 21:00");17bestTimeToCall.addCall("Fred", "2013-03-02 22:00");18bestTimeToCall.addCall("Fred", "2013-03-02 23:00");19bestTimeToCall.addCall("Fred", "2013-03-03 00:00");20bestTimeToCall.addCall("Fred", "2013-03-03 01:00");21bestTimeToCall.addCall("Fred", "2013-03-03 02:00");22bestTimeToCall.addCall("Fred", "2013-03-03 03:00");23bestTimeToCall.addCall("Fred", "2013-03-03 04
Using AI Code Generation
1var config = require('./config.json');2var request = require('request');3var nodemailer = require('nodemailer');4var smtpTransport = require('nodemailer-smtp-transport');5var options = {6 headers: {7 }8};9function callback(error, response, body) {10 if (!error && response.statusCode == 200) {11 var info = JSON.parse(body);12 console.log(info.activeClients);13 if (info.activeClients > 100) {14 sendEmail();15 }16 }17}18function sendEmail() {19 var transporter = nodemailer.createTransport(smtpTransport({20 auth: {21 }22 }));23 var mailOptions = {24 };25 transporter.sendMail(mailOptions, function(error, info) {26 if (error) {27 console.log(error);28 } else {29 console.log('Email sent: ' + info.response);30 }31 });32}33request(options, callback);
Using AI Code Generation
1'use strict';2var bestbuy = require('bestbuy')('API_KEY');3bestbuy.activeClients('2015-01-01', function (err, data) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log('Active clients for 2015-01-01: ' + data);8 }9});10bestbuy.activeClients('2015-01-01', '2015-01-03', function (err, data) {11 if (err) {12 console.log('Error: ' + err);13 } else {14 console.log('Active clients for 2015-01-01 to 2015-01-03: ' + data);15 }16});
Using AI Code Generation
1var BestRoute = require('./BestRoute.js');2var br = new BestRoute();3var client = br.createClient();4var server = br.createServer();5br.createPath(client, server);6var route = br.activeClients(client, server);7console.log(route.path);8console.log(route.bandwidth);9console.log(route.bandwidth);10console.log(route.path);11console.log(route.path);12console.log(route.bandwidth);13console.log(route.bandwidth);14console.log(route.path);15console.log(route.path);16console.log(route.bandwidth);17console.log(route.bandwidth);18console.log(route.path);19console.log(route.path);20console.log(route.bandwidth);21console.log(route.bandwidth);22console.log(route.path);23console.log(route.path);24console.log(route.bandwidth);25console.log(route.bandwidth);26console.log(route.path);27console.log(route.path);28console.log(route.bandwidth);29console.log(route.bandwidth);30console.log(route.path);31console.log(route.path);32console.log(route.bandwidth);33console.log(route.bandwidth);34console.log(route.path);35console.log(route.path);36console.log(route.bandwidth);37console.log(route.bandwidth);38console.log(route.path);39console.log(route.path);40console.log(route.bandwidth);41console.log(route.bandwidth);42console.log(route.path);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!