63 lines
1.8 KiB
JavaScript
63 lines
1.8 KiB
JavaScript
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 || 3000
|
|
const server = app.listen(port, host, () => console.log(`陆战棋游戏服务运行在 http://${host}:${port}/`))
|
|
const io = require('socket.io')(server)
|
|
|
|
const clients = []
|
|
let player1 = null
|
|
let player2 = null
|
|
let startTime = null
|
|
let isStarted = false
|
|
let player1Ready = false
|
|
let player2Ready = false
|
|
let currentPlayer = null
|
|
|
|
io.on('connection', (client) => {
|
|
handleConnection(client)
|
|
client.on('disconnect', () => handleDisconnection(client))
|
|
client.on('join', () => handleJoin(client))
|
|
})
|
|
|
|
// 处理客户端连接
|
|
function handleConnection(client) {
|
|
clients.push(client)
|
|
client.emit('joined', { player: 'player1', ip: player1 != null ? player1.handshake.address : '' })
|
|
client.emit('joined', { player: 'player2', ip: player2 != null ? player2.handshake.address : '' })
|
|
}
|
|
|
|
// 处理客户端断线
|
|
function handleDisconnection(client) {
|
|
const index = clients.indexOf(client)
|
|
clients.splice(index, 1)
|
|
}
|
|
|
|
// 处理参战请求
|
|
function handleJoin(client) {
|
|
if (player1 != null && player2 != null) {
|
|
client.emit('alert', '玩家已满,无法加入游戏。')
|
|
return
|
|
}
|
|
|
|
if (client == player1 || client == player2) {
|
|
client.emit('alert', '你已加入,无法重新加入。')
|
|
return
|
|
}
|
|
|
|
if (player1 == null) {
|
|
player1 = client
|
|
client.emit('alert', '加入游戏成功,你是黑方。')
|
|
io.emit('joined', { player: 'player1', ip: client.handshake.address })
|
|
return
|
|
}
|
|
|
|
if (player2 == null) {
|
|
player2 = client
|
|
client.emit('alert', '加入游戏成功,你是红方。')
|
|
io.emit('joined', { player: 'player2', ip: client.handshake.address })
|
|
return
|
|
}
|
|
}
|