/
room.coffee
54 lines (46 loc) · 1.31 KB
/
room.coffee
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
GameRunner = require('./game_runner')
class Room
constructor: (@maxPlayers, @p1, @p2) ->
@game = null
@spectators = []
@players = []
@players.push(@p1) if @p1
@players.push(@p2) if @p2
@open = this.startGame() # will fail if not enough players
@id = 0 # roomID
addPlayer: (p) ->
console.log '-- ADDING PLAYER TO ROOM --'
return false if this.isFull()
if @p1 then @p2 = p else @p1 = p
@players.push(p)
p.room = this
p.socket.on 'disconnect', => # notify room of leaving
this.stopGame()
# Destroy the room
console.log '-- DELETING ROOM ' + @id
delete Room.AllRooms[@id]
console.log '-- NUM PLAYERS IN ROOM = '+@players.length+' --'
this.startGame()
true
addSpectator: (p) ->
@spectators.push p
removeSpectator: (p) ->
idx = @spectators.indexOf(p)
@spectators.splice(idx, 1) if idx >= 0
# startGame: returns true if successful
startGame: ->
return false if !this.isFull() # both players must be present
@game = new GameRunner(this)
console.log '-- STARTING GAME ---'
@game.start()
true
stopGame: ->
@game.stop() if @game
@game = null
this.emit('gameDestroy')
gameRunning: -> @game && @game.running
isFull: -> @players.length >= @maxPlayers
emit: (msg, data) ->
p.socket.emit(msg, data) for p in @players
Room.AllRooms = {} # static property
module.exports = Room