-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
92 lines (83 loc) · 2.78 KB
/
server.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
const express = require('express')
const app = express()
app.use(express.static('public'))
const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 8000
const server = app.listen(port, host, () => console.log(`server started at http://${host}:${port}/`))
const io = require('socket.io')(server)
const gridSize = 20
const apple = { x: 10, y: 10 }
const player1 = {
id: '',
key: '',
pos: { x: 3, y: 1 },
vel: { x: 1, y: 0 },
snake: [
{ x: 3, y: 1 },
{ x: 2, y: 1 },
{ x: 1, y: 1 },
],
}
const player2 = {
id: '',
key: '',
pos: { x: 16, y: 18 },
vel: { x: -1, y: 0 },
snake: [
{ x: 16, y: 18 },
{ x: 17, y: 18 },
{ x: 18, y: 18 },
],
}
io.on('connection', (client) => {
// first two clients are players
if (!player1.id) {
client.emit('playerNumber', 1)
player1.id = client.id
} else if (!player2.id) {
client.emit('playerNumber', 2)
player2.id = client.id
} else {
client.emit('playerNumber', 0)
return
}
// restart game when new player joins
player1.snake = player1.snake.slice(0, 3)
player2.snake = player2.snake.slice(0, 3)
client.on('keydown', (key) => {
if (client.id == player1.id) player1.key = key
else player2.key = key
})
client.on('disconnect', () => {
if (client.id == player1.id) player1.id = ''
else player2.id = ''
})
})
setInterval(() => {
for (let player of [player1, player2]) {
// snake turn
if (player.key == 'ArrowDown' && player.vel.y == 0) player.vel = { x: 0, y: 1 }
else if (player.key == 'ArrowUp' && player.vel.y == 0) player.vel = { x: 0, y: -1 }
else if (player.key == 'ArrowLeft' && player.vel.x == 0) player.vel = { x: -1, y: 0 }
else if (player.key == 'ArrowRight' && player.vel.x == 0) player.vel = { x: 1, y: 0 }
player.key = ''
// snake move
player.pos.x = (player.pos.x + player.vel.x + gridSize) % gridSize
player.pos.y = (player.pos.y + player.vel.y + gridSize) % gridSize
player.snake.unshift({ x: player.pos.x, y: player.pos.y })
// snake eat
if (player.pos.x == apple.x && player.pos.y == apple.y) {
// reset apple
apple.x = Math.floor(Math.random() * gridSize)
apple.y = Math.floor(Math.random() * gridSize)
} else player.snake.pop()
// snake collide
if (
player1.snake.slice(1).some((c) => player.pos.x == c.x && player.pos.y == c.y) ||
player2.snake.slice(1).some((c) => player.pos.x == c.x && player.pos.y == c.y)
)
player.snake.length > 3 && player.snake.pop()
}
// brocast game state
io.emit('game', { apple, player1, player2 })
}, 200)