xiaomaodiaoyu/server.js
2022-08-18 09:14:04 +08:00

72 lines
1.9 KiB
JavaScript

const express = require('express')
const game = express()
game.use(express.static('public'))
const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 3000
const server = game.listen(port, host, () => console.log(`小猫钓鱼游戏服务运行在 http://${host}:${port}/`))
const io = require('socket.io')(server)
const clients = []
const players = []
const cards = []
let current = 0
let started = false
function isGameStarted() {
if (players.length < 2) return false
for (let player of players) {
if (!player.ready) return false
}
return true
}
io.on('connection', (client) => {
client.ready = false
client.cards = []
clients.push(client)
io.emit('onlineNumber', clients.length)
io.emit('playersNumber', players.length)
client.on('ready', () => {
if (!isGameStarted()) {
client.ready = !client.ready
if (client.ready) {
players.push(client)
} else {
const index = players.indexOf(client)
players.splice(index, 1)
}
io.emit('playersNumber', players.length)
client.emit('ready', client.ready)
if (isGameStarted()) gameStart()
}
})
client.on('disconnect', () => {
const index = clients.indexOf(client)
clients.splice(index, 1)
io.emit('onlineNumber', clients.length)
})
})
function gameStart() {
console.log('游戏开始')
// cards = []
cards.length = 0
current = 0
// 洗牌 -> players.cards 每家18张
// players[0].cards = [1, 2, 3]
// players[1].cards = [1, 2, 3, 4]
// players[2].cards = [1, 2, 3, 4, 5]
// ...
emitStatus()
}
function emitStatus() {
const cardsNumbers = []
for (let p of players) {
cardsNumbers.push(p.cards.length)
}
io.emit('status', { players: cardsNumbers, cards, current })
}