2022-08-04 10:31:09 +00:00
|
|
|
const express = require('express')
|
|
|
|
const app = express()
|
|
|
|
app.use(express.static('public'))
|
|
|
|
const host = process.env.HOST || '0.0.0.0'
|
2022-08-04 14:21:29 +00:00
|
|
|
const port = process.env.PORT || 3000
|
2022-08-04 17:11:19 +00:00
|
|
|
const server = app.listen(port, host, () => console.log(`陆战棋游戏服务运行在 http://${host}:${port}/`))
|
2022-08-04 10:31:09 +00:00
|
|
|
const io = require('socket.io')(server)
|
|
|
|
|
|
|
|
const clients = []
|
|
|
|
let currentPlayer = null
|
|
|
|
|
|
|
|
io.on('connection', (client) => {
|
|
|
|
// 来人了
|
|
|
|
clients.push(client)
|
|
|
|
|
|
|
|
const i = clients.indexOf(client)
|
|
|
|
if (i == 0) client.emit('role', '玩家1')
|
|
|
|
else if (i == 1) client.emit('role', '玩家2')
|
|
|
|
else client.emit('role', '旁观者')
|
|
|
|
|
|
|
|
if (clients.length == 2) {
|
|
|
|
currentPlayer = clients[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
io.emit('player', clients.length < 2 || currentPlayer != clients[1] ? 'player1' : 'player2')
|
|
|
|
|
|
|
|
// 人走了
|
|
|
|
client.on('disconnect', () => {
|
|
|
|
const idx = clients.indexOf(client)
|
|
|
|
clients.splice(idx, 1)
|
|
|
|
|
|
|
|
clients.forEach((c) => {
|
|
|
|
const i = clients.indexOf(c)
|
|
|
|
if (i == 0) c.emit('role', '玩家1')
|
|
|
|
else if (i == 1) c.emit('role', '玩家2')
|
|
|
|
else c.emit('role', '旁观者')
|
|
|
|
})
|
|
|
|
|
|
|
|
if (clients.length >= 2) {
|
|
|
|
currentPlayer = clients[0]
|
|
|
|
} else {
|
|
|
|
currentPlayer = null
|
|
|
|
}
|
|
|
|
io.emit('player', clients.length < 2 || currentPlayer != clients[1] ? 'player1' : 'player2')
|
|
|
|
})
|
|
|
|
|
|
|
|
client.on('click', () => {
|
|
|
|
if (clients.length >= 2 && client == currentPlayer) {
|
|
|
|
// 切换玩家
|
|
|
|
if (currentPlayer === clients[0]) {
|
|
|
|
currentPlayer = clients[1]
|
|
|
|
io.emit('player', 'player2')
|
|
|
|
} else {
|
|
|
|
currentPlayer = clients[0]
|
|
|
|
io.emit('player', 'player1')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|