Advertisement
RowanHarley

Untitled

Jun 14th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var config = require("./config/config.js");
  2. //var spawn = require("./src/spawn.js");
  3. var pkg = require("./package.json");
  4. var WebSocket = require("ws").Server;
  5. var snake = require("./src/entities/snake");
  6. var food = require("./src/entities/food");
  7. var sector = require("./src/entities/sector");
  8. var messages = require("./src/messages");
  9. var message = require("./src/utils/message");
  10. var math = require("./src/utils/math");
  11.  
  12. var counter = 0;
  13. var clients = [];
  14. var foods = [];
  15. var sectors = []; // Development Code
  16.  
  17.  
  18. console.log("[DEBUG] You are currently running on " + pkg.version);
  19. console.log("[SERVER] Starting Server...");
  20. var server;
  21. server = new WebSocket({port: config["port"], path: "/slither"}, function(){
  22.     console.log("[SERVER] Server Started at 127.0.0.1:" + config["port"] + "! Waiting for Connections...");
  23.     generateFood(config["food"]);
  24.     generateSectors();
  25. });
  26. /* server.on('error', function() {
  27.     console.log('[DEBUG] Error while connecting!');
  28. });
  29. console.log("[SERVER] Server Started at 127.0.0.1:" + config["port"] + "! Waiting for Connections...");
  30.  */
  31. server.on("connection", handleConnection.bind(server));
  32. function handleConnection(conn) {
  33.     if(config['isDebug']){
  34.         console.log("[DEBUG] handleConnection() has begun");
  35.     }
  36.     if (clients.length >= config['max-connections']) {
  37.         console.log("[SERVER] Too many connections. Closing newest connections!");
  38.         conn.close();
  39.         return;
  40.     }
  41.     try {
  42.         conn.id = ++counter;
  43.         clients[conn.id] = conn;
  44.     }catch(e){
  45.         console.log("[ERROR] " + e);
  46.     }
  47.    
  48.     function close(id) {
  49.         console.log("[ERROR] Error!");
  50.         console.log("[DEBUG] Connection closed.");
  51.         //clearInterval(conn.snake.update);
  52.         delete clients[id];
  53.     }
  54.     conn.on('message', handleMessage.bind(this, conn));
  55.     //conn.on('error', close.bind(conn.id));
  56.     conn.on('error', function(e){
  57.         console.log(e);
  58.         //delete clients[conn.id];
  59.     });
  60.    
  61.     conn.on('close', close.bind(conn.id));
  62.     send(conn.id, messages.initial);
  63. };
  64. function handleMessage(conn, data) {
  65.     var firstByte, name, radians, secondByte, skin, speed, value, x, y;
  66.     if (data.length === 0) {
  67.         console.log("[SERVER] No Data to handle!");
  68.         return;
  69.     }
  70.     if (data.length >= 227) {
  71.         console.log("[SERVER] Data length less than 227!");
  72.         conn.close();
  73.     } else if (data.length === 1) {
  74.         value = message.readInt8(0, data);
  75.         if (value <= 250) {
  76.             console.log('Snake going to', value);
  77.             if (value === conn.snake.direction.angle) {
  78.                 return;
  79.             }
  80.             radians = value * (Math.PI / 125);
  81.             speed = 1;
  82.             x = Math.cos(radians) + 1;
  83.             y = Math.sin(radians) + 1;
  84.             conn.snake.direction.x = x * 127 * speed;
  85.             conn.snake.direction.y = y * 127 * speed;
  86.             conn.snake.direction.angle = value;
  87.         } else if (value === 253) {
  88.             console.log("Snake in speed mode");
  89.         } else if (value === 254) {
  90.             console.log("Snake in speed mode");
  91.         } else if (value === 251) {
  92.             send(conn.id, messages.pong);
  93.         }
  94.     } else {
  95.        
  96.         firstByte = message.readInt8(0, data);
  97.         secondByte = message.readInt8(1, data);
  98.         if (firstByte === 115) {
  99.             skin = message.readInt8(2, data);
  100.             name = message.readString(3, data, data.byteLength);
  101.             conn.snake = new snake(conn.id, name, {
  102.                 x: 28907.6 * 5,
  103.                 y: 21137.4 * 5
  104.             }, skin);
  105.             broadcast(messages.snake.build(conn.snake));
  106.             var move = messages.movement.build(conn.id, conn.snake.direction.x, conn.snake.direction.y)
  107.             var dir = messages.direction.build(conn.id, conn.snake.direction);
  108.             console.log("[DEBUG] A new snake called " + conn.snake.name + " was connected!");
  109.             spawnSnakes(conn.id);
  110.             conn.snake.update = setInterval((function() {
  111.                 conn.snake.body.x += Math.round(Math.cos(conn.snake.direction.angle * 1.44 * Math.PI / 180) * 170);
  112.                 conn.snake.body.y += Math.round(Math.sin(conn.snake.direction.angle * 1.44 * Math.PI / 180) * 170);
  113.                 broadcast(dir);
  114.                 broadcast(move);
  115.             }), 230);
  116.             } else {
  117.                 console.log("[ERROR] Unhandled message " + (String.fromCharCode(firstByte)));
  118.             }
  119.             send(conn.id, messages.leaderboard.build([conn], 1, [conn]));
  120.             send(conn.id, messages.highscore.build("Rowan", "Test Message"));
  121.             send(conn.id, messages.minimap.build(foods));
  122.     }
  123. }
  124. function generateFood(amount) {
  125.     var color, i, id, results, size, x, y;
  126.     i = 0;
  127.     results = [];
  128.     while (i < amount) {
  129.         x = math.randomInt(0, 65535);
  130.         y = math.randomInt(0, 65535);
  131.         id = x * config['game-radius'] * 3 + y;
  132.         color = math.randomInt(0, config['foodColors']);
  133.         size = math.randomInt(config['foodSize'][0], config['foodSize'][1]);
  134.         foods.push(new food(id, {
  135.             x: x,
  136.             y: y
  137.         }, size, color));
  138.         results.push(i++);
  139.     }
  140.     return results;
  141. }
  142. function generateSectors() {
  143.     var i, results, sectorsAmount;
  144.     sectorsAmount = config['gameRadius'] / config['sectorSize'];
  145.     i = 0;
  146.     results = [];
  147.     while (i < sectorsAmount) {
  148.         results.push(i++);
  149.     }
  150.     return results;
  151. }
  152. function spawnSnakes(id){
  153.     clients.forEach(function(client){
  154.         if(client.id !== id){
  155.             send(id, messages.snake.build(client.snake));
  156.         }
  157.     });
  158. }
  159.  
  160. function send(id,data){
  161.     if(clients[id]){
  162.         clients[id].send(data, {binary:true});
  163.     }
  164. }
  165.  
  166. function broadcast(data){
  167.     /* "use strict";
  168.     for(let client in clients){
  169.         if(client != null){
  170.             client.send(data, {binary: true});
  171.         }
  172.     } */
  173.     for(var i = 0; i < clients.length; i++){
  174.         if(clients[i]){
  175.             clients[i].send(data);
  176.         }
  177.     }
  178. }
  179. /* function broadcast(data) {
  180.     var client, j, len, ref, results;
  181.     ref = this.clients;
  182.     results = [];
  183.     for (j = 0, len = ref.length; j < len; j++) {
  184.         client = ref[j];
  185.         results.push(client != null ? client.send(data, {
  186.             binary: true
  187.         }) : void 0);
  188.     }
  189.     return results;
  190. }; */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement