-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
114 lines (96 loc) · 2.77 KB
/
app.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
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
const { brownLogic, translateLogic, judgmentLogic, playerEnter, playerExit, playerCommand } = require('./core.js')
const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const port = process.env.PORT | 3000
app.use(express.static('client'))
const socketWrappers = {
// socketId: { socket, where }
}
const lobby = {
socketToEntity: {
},
entityToSocket: {
},
entityIdCount: 0,
entities: {
},
oldTime: undefined,
updateTerm: 10,
emit(type, data) {
for (const socketId in this.socketToEntity) {
socketWrappers[socketId].socket.emit(type, data)
}
},
idleToUpdate() {
const newTime = Date.now()
while (newTime - this.oldTime >= this.updateTerm) {
this.oldTime += this.updateTerm
this.emit('updateWorld')
brownLogic.update(this.entities)
translateLogic.update(this.entities)
judgmentLogic.update(this.entities)
}
setTimeout(() => this.idleToUpdate())
},
start() {
this.oldTime = Date.now()
setTimeout(() => this.idleToUpdate())
}
}
io.on('connection', (socket) => {
console.log('플레이어 로비 접속')
const socketId = socket.id
socketWrappers[socketId] = {
socket,
where: 'lobby'
}
const entity = {
type: 'brown',
position: {
x: Math.random() * 300 + 100,
z: Math.random() * 300 + 100
},
velocity: {
x: 0,
z: 0
},
direction: {
x: 1,
z: 1
},
movePoint: 3,
state: 'idle',
stateTick: 0,
maxMoveCount: 2,
moveCount: 0,
angle: 0,
hitFlag: false
}
const entityId = lobby.entityIdCount++
const data = { entityId, entity }
lobby.emit('playerEnter', data)
playerEnter(lobby.entities, data)
lobby.socketToEntity[socketId] = entityId
lobby.entityToSocket[entityId] = socketId
socket.emit('initLobby', { entities: lobby.entities, entityId: entityId })
socket.on('playerCommand', (data) => {
data.entityId = lobby.socketToEntity[socketId]
lobby.emit('playerCommand', data)
playerCommand(lobby.entities, data)
})
socket.on('disconnect', () => {
console.log('플레이어 로비 나감')
delete socketWrappers[socketId]
delete lobby.socketToEntity[socketId]
delete lobby.entityToSocket[entityId]
const data = { entityId }
lobby.emit('playerExit', data)
playerExit(lobby.entities, data)
})
})
http.listen(port, () => {
console.log(`서버가 ${port}번 포트에 열렸습니다`)
})
lobby.start()