Spaces:
Running
Running
File size: 2,887 Bytes
c679a93 |
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 115 |
import geckos from '@geckos.io/server'
import { iceServers } from '@geckos.io/server'
import pkg from 'phaser'
const { Scene } = pkg
import { Player } from './components/player.js'
export class GameScene extends Scene {
constructor() {
super({ key: 'GameScene' })
this.playerId = 0
}
init() {
this.io = geckos({
iceServers: process.env.NODE_ENV === 'production' ? iceServers : []
})
this.io.addServer(this.game.server)
}
getId() {
return this.playerId++
}
prepareToSync(player) {
return `${player.playerId},${Math.round(player.x).toString(36)},${Math.round(player.y).toString(36)},${
player.dead === true ? 1 : 0
},`
}
getState() {
let state = ''
this.playersGroup.children.iterate(player => {
state += this.prepareToSync(player)
})
return state
}
create() {
this.playersGroup = this.add.group()
const addDummy = () => {
let x = Phaser.Math.RND.integerInRange(50, 800)
let y = Phaser.Math.RND.integerInRange(100, 400)
let id = Math.random()
let dead = this.playersGroup.getFirstDead()
if (dead) {
dead.revive(id, true)
dead.setPosition(x, y)
} else {
this.playersGroup.add(new Player(this, id, x, y, true))
}
}
this.io.onConnection(channel => {
channel.onDisconnect(() => {
console.log('Disconnect user ' + channel.id)
this.playersGroup.children.each(player => {
if (player.playerId === channel.playerId) {
player.kill()
}
})
channel.room.emit('removePlayer', channel.playerId)
})
channel.on('addDummy', addDummy)
channel.on('getId', () => {
channel.playerId = this.getId()
channel.emit('getId', channel.playerId.toString(36))
})
channel.on('playerMove', data => {
this.playersGroup.children.iterate(player => {
if (player.playerId === channel.playerId) {
player.setMove(data)
}
})
})
channel.on('addPlayer', data => {
let dead = this.playersGroup.getFirstDead()
if (dead) {
dead.revive(channel.playerId, false)
} else {
this.playersGroup.add(new Player(this, channel.playerId, Phaser.Math.RND.integerInRange(100, 700)))
}
})
channel.emit('ready')
})
}
update() {
let updates = ''
this.playersGroup.children.iterate(player => {
let x = Math.abs(player.x - player.prevX) > 0.5
let y = Math.abs(player.y - player.prevY) > 0.5
let dead = player.dead != player.prevDead
if (x || y || dead) {
if (dead || !player.dead) {
updates += this.prepareToSync(player)
}
}
player.postUpdate()
})
if (updates.length > 0) {
this.io.room().emit('updateObjects', [updates])
}
}
}
|