repl.it
@dcbriccetti/

online game

Nodejs

No description

fork
loading
Files
  • index.js
  • public
  • Packager files
  • package-lock.json
  • package.json
index.js
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
const express = require('express');
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);

app.use(express.static("public"));

/* Server */
// Movement keys
const W = 87;
const A = 65;
const S = 83;
const D = 68;

// The data
let data = {players:{}};

let width = 600;
let height = 600;

io.on("connection", socket => {
  // New player connected
  console.log("player connected");

  // Create new player
  data.players[socket.id] = {
    pos:{x:Math.random()*100, y:Math.random()*100},
    speed:2,
    size:16,
    color:{r:Math.random()*255, g:Math.random()*255, b:Math.random()*255}
  };

  // Movement event
  socket.on("move", key => {
    // Get the current player
    let player = data.players[socket.id];

    // Check which movement key was pressed, and move accordingly
    if(key == W) player.pos.y -= player.speed;
    if(key == A) player.pos.x -= player.speed;
    if(key == S) player.pos.y += player.speed;
    if(key == D) player.pos.x += player.speed;

    // Check if player is touching the boundry, if so stop them from moving past it
    if(player.pos.x > width - player.size) player.pos.x = width - player.size;
    if(player.pos.x < 0) player.pos.x = 0;
    if(player.pos.y > height - player.size) player.pos.y = height - player.size;
    if(player.pos.y < 0) player.pos.y = 0;
  });

  socket.on("disconnect", () => {
    // Player  disconnected
    console.log("player disconnected");
    // Delete player
    delete data.players[socket.id];
  });
});

// Update players
setInterval(() => {
  // Send the update to each client
  io.emit("update", data);
}, 1000/60);

http.listen(3000, () => {
  console.log('server started');
});
Fetching token
?