-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.coffee
executable file
·685 lines (625 loc) · 20.2 KB
/
app.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
#!/usr/bin/env coffee
require 'coffee-script/register' # for node-inspector
ROT = require 'rot.js'
browserify = require 'browserify-middleware'
commander = require 'commander'
express = require 'express'
http = require 'http'
random = require 'random-ext'
stylus = require 'stylus'
websocket = require 'websocket'
{vec2} = require 'gl-matrix'
{SparseMap, SparseMapList, DenseMap} = require './lib/map.coffee'
{TILES, WALKABLE_TILES, DIR_TO_VEC, ZERO} = require './lib/terrain.coffee'
# TODO: Inject
argv = commander
.option('-p, --numPlayers <n>', "Number of players per party", parseInt, 2)
.option('-h, --host <host>', "Bind port to this", String, '0.0.0.0')
.option('--publicHost <host>', "Servers will be told to connect here", String, 'localhost')
.option('--webPort <port>', "Main web UI port", parseInt, 9000)
.option('--cncPort <port>', "Command and control port", parseInt, 9001)
.option('--gamePort <port>', "Game port", parseInt, 9002)
.parse(process.argv)
app = express()
app.use stylus.middleware src: __dirname + '/static/style'
app.use express.static __dirname + '/static'
app.set 'view engine', 'pug'
app.get '/main.js', browserify('./lib/main.coffee', transform: ['coffeeify'])
app.get '/', (req, res) -> res.render 'index', argv: argv
app.listen argv.webPort, argv.host, ->
console.log "Web server listening on http://#{ argv.host }:#{ argv.webPort }/"
cncServer = http.createServer()
cncServer.listen argv.cncPort, argv.host, -> console.log "CNC server on #{ argv.cncPort }"
cncLobby = {}
cncWSServer = new websocket.server(httpServer: cncServer)
cncWSServer.on 'request', (req) ->
conn = req.accept 'cnc', req.origin
send = (obj) -> conn.sendUTF JSON.stringify obj
console.log 'Accepted CNC connection'
conn.on 'message', (event) ->
msg = JSON.parse if event.type is 'utf8' then event.utf8Data else event.binaryData
console.log 'CNC message', msg
if msg.type is 'hello'
{playerId} = msg
if playerId of cncLobby
console.error "Error: #{ playerId } already in lobby"
return
cncLobby[playerId] = conn
if Object.keys(cncLobby).length >= argv.numPlayers
gameId = "game-#{ random.restrictedString [random.CHAR_TYPE.LOWERCASE], 4, 4 }"
for playerId, playerConn of cncLobby
console.log "Telling player #{ playerId } to start game #{ gameId }"
playerConn.sendUTF JSON.stringify
type: 'connect', url: "ws://#{ argv.publicHost }:#{ argv.gamePort }/", gameId: gameId
delete cncLobby[playerId]
else
cncLobby[playerId] = conn
console.log "Player #{ playerId } is waiting for a game"
conn.on 'close', ->
console.log 'CNC closed'
conn.on 'error', (err) ->
console.log 'CNC error', err
send type: 'hello'
gameServer = http.createServer()
gameServer.listen argv.gamePort, argv.host, -> console.log "Game server on #{ argv.gamePort }"
gameSchedulers = {}
gameWSServer = new websocket.server(httpServer: gameServer)
gameWSServer.on 'request', (req) ->
conn = req.accept 'game', req.origin
console.log 'Accepted Game connection'
conn.on 'error', (err) ->
console.log 'Game error', err
conn.on 'message', (event) ->
msg = JSON.parse if event.type is 'utf8' then event.utf8Data else event.binaryData
if msg.type is 'hello'
{playerId, gameId} = msg
scheduler = gameSchedulers[gameId]
if not scheduler
scheduler = new Scheduler(new World())
gameSchedulers[gameId] = scheduler
scheduler.addPlayer playerId, conn
if Object.keys(scheduler.players).length >= argv.numPlayers
scheduler.start()
conn.on 'close', ->
scheduler.world.gameOver = "A player has lost their connection."
class Scheduler
constructor: (@world) ->
@tickSpeed = 100
@tick = 0
@players = {}
addPlayer: (playerId, conn) ->
@players[playerId] = conn
@world.addPlayer playerId, conn
conn.on 'message', (event) =>
msg = JSON.parse if event.type is 'utf8' then event.utf8Data else event.binaryData
switch msg.type
when 'input'
@world.handlePlayerInput playerId, msg
when 'pause'
if @timer
@send type: 'status', subtype: 'pause', playerId: playerId
@stop()
else
@send type: 'status', subtype: 'resume', playerId: playerId
@start()
when 'set-speed'
@tickSpeed = Math.min 3000, Math.max 100, Number(msg.speed or 100)
@send type: 'status', subtype: 'speed', value: @tickSpeed, playerId: playerId
send: (obj) ->
for playerId, conn of @players
conn.sendUTF JSON.stringify obj
start: ->
oldLevelIndex = null
doTick = =>
start = Date.now()
@tick++
if oldLevelIndex != @world.levelIndex
@send
type: 'level-init'
index: @world.levelIndex
name: @world.level.name
width: @world.level.width
height: @world.level.height
oldLevelIndex = @world.levelIndex
diff = @world.simulate(@tickSpeed, @tick)
if @world.gameOver
console.log "Game over"
@send type: 'gameover', reason: @world.gameOver, messages: @world.messages
return
monsters = []
items = []
if @world.level?
for _, monster of @world.level.monsters
monsters.push monster.toViewJSON() if diff.get monster.pos
for _, item of @world.level.items
if diff.get item.pos
items.push item.toViewJSON()
players = {}
for playerId, actor of @world.playerActors
players[playerId] = actor.toViewJSON()
@send
type: 'tick'
tick: @tick
players: players
monsters: monsters
items: items
diff: diff.toJSON()
messages: @world.messages
next = (start + @tickSpeed) - Date.now()
@timer = setTimeout doTick, if next < 0 then 0 else next
doTick()
stop: ->
clearTimeout @timer
@timer = null
class World
constructor: ->
@_nextGUID = 1
@levels = [new Level(this, 1, 'level-1')]
@levelIndex = 0
@level = @levels[@levelIndex]
@gameOver = null
@messages = null
@playerConns = {}
@playerActors = {}
addPlayer: (id, conn) ->
actor = new Player(id)
@playerConns[id] = conn
@playerActors[id] = actor
actor.pos = @level.pickPositionOfType TILES.STAIRCASE_UP
throw new Error("Couldn't find staircase up") unless actor.pos
@level.actors.add actor.pos, actor
handlePlayerInput: (id, msg) ->
actor = @playerActors[id]
actor.lastInput = msg unless actor.isDead
getGUID: ->
return @_nextGUID++
kill: (actor) ->
actor.isDead = true
@level.actors.remove actor.pos, actor
delete @level.monsters[actor.id]
simulate: (tickSpeed, tick) ->
@messages = if tick is 1 then ['Welcome to Kragnoth'] else []
max = [@level.width - 1, @level.height - 1]
updatePos = (actor, command, dir) =>
delta = DIR_TO_VEC[dir] or ZERO
next = [0, 0]
vec2.add next, actor.pos, delta
vec2.min next, next, max
vec2.max next, next, ZERO
tile = @level.terrain.get next
pile = @level.piles.get next
occupants = @level.actors.get next
isMove = command in ['move', 'attack-move']
isAttack = command in ['attack-move', 'attack']
# 1. Players cannot attack themselves or other players.
# 2. Players can overlap players.
# 3. Monsters cannot overlap players.
# 4. If a player kills the defender, don't move onto the space afterwards.
if isAttack
candidates = (o for o in occupants when o.isPlayer != actor.isPlayer) if occupants
defender = candidates?[0]
solveAttack actor, defender if defender?
if isMove and not defender
if tile of WALKABLE_TILES
if actor.isPlayer
blockers = (o for o in occupants when not o.isPlayer) if occupants
else
blockers = occupants
if not blockers?.length
vec2.copy actor.pos, next
vec2.copy item.pos, next for item in actor.items
return
solveAttack = (attacker, defender) =>
ap = attacker.ap
ap += attacker.weapon.ap if attacker.weapon?
defender.hp -= ap
if attacker.isPlayer
@messages.push "Player #{ attacker.name } hit the #{ defender.name }"
if attacker.ap is 0
msg += " It seems unaffected."
@messages.push msg
if defender.isPlayer
msg = "The #{ attacker.name } hits #{ defender.name }!"
if attacker.ap is 0
msg += " They seem unaffected."
@messages.push msg
if defender.hp <= 0
@kill defender
if attacker.isPlayer
@messages.push "#{ attacker.name } kills the #{ defender.name }!"
handlePickup = (actor) =>
pile = @level.piles.get actor.pos
if pile
@level.piles.delete actor.pos
loop
item = pile.shift()
delete @level.items[item.id]
switch item.class
when 'gold'
actor.gold += item.value
msg = "#{ item.value } gold"
when 'weapon'
actor.items.push item
article = if (/^[aeiouy]/i).test(item.name) then 'an' else 'a'
msg = "#{ article } #{ item.name }"
when 'potion'
actor.items.push item
msg = 'a potion!'
if actor.isPlayer
@messages.push "#{ actor.name } picks up #{ msg }"
else
@messages.push "The #{ actor.name } picks up #{ msg }"
break unless pile.length
else
if actor.isPlayer
@messages.push "There nothing for #{ actor.name } to pickup"
goLevelUp = =>
if @level.depth is 1
@gameOver = "All party members have left the dungeon. Goodbye!"
@levelIndex = -1
@level = null
else
@levelIndex--
@level = @levels[@levelIndex]
pos = @level.pickPositionOfType TILES.STAIRCASE_DOWN
for _, player of @playerActors
vec2.copy player.pos, pos
goLevelDown = =>
@levelIndex++
@level = @levels[@levelIndex]
if not @level?
depth = @levelIndex + 1
@level = new Level(this, depth, "level-#{ depth }")
if depth > 2
pos = @level.pickPositionOfType TILES.STAIRCASE_DOWN
@level.terrain.set pos, TILES.FLOOR
@levels[@levelIndex] = @level
pos = @level.pickPositionOfType TILES.STAIRCASE_UP
for _, player of @playerActors
vec2.copy player.pos, pos
for _, player of @playerActors
command = player.simulate()
switch command?.command
when 'move', 'attack-move', 'attack'
dir = command.direction
if dir in ['up', 'down']
tile = @level.terrain.get player.pos
actors = @level.actors.get player.pos
if actors
actors = (a for a in actors when a.isPlayer)
if actors?.length is argv.numPlayers
if dir is 'up' and tile is TILES.STAIRCASE_UP
goLevelUp()
else if dir is 'down' and tile is TILES.STAIRCASE_DOWN
goLevelDown()
else
@messages.push "There is no #{ dir } staircase here."
else
@messages.push "All #{ argv.numPlayers } players must be on the staircase."
else
oldPos = vec2.copy [0,0], player.pos
updatePos player, command.command, command.direction
@level.actors.remove oldPos, player
@level.actors.add player.pos, player
when 'pickup'
handlePickup player
when 'choose-item'
for i in player.items
item = i if i.id is command.id
if item?
if item.class is 'weapon'
player.weapon = item
else if item.class is 'potion'
player.hp = Math.min (player.hp + item.hp), player.maxHp
player.items = (i for i in player.items when i.id != item.id)
delete @level.items[item.id]
else
@messages.push "Can't use #{ item.name } as a weapon"
if (a for _, a of @playerActors when not a.isDead).length is 0
@gameOver = "All of the party members are dead!"
return if @gameOver
for _, monster of @level.monsters
continue unless (tick - monster.lastTick) >= monster.speed
command = monster.simulate(this)
switch command?.command
when 'move', 'attack-move', 'attack'
oldPos = vec2.copy [0,0], monster.pos
updatePos monster, command.command, command.direction
@level.actors.remove oldPos, monster
@level.actors.add monster.pos, monster
when 'pickup'
handlePickup monster
monster.lastTick = tick
# computer what areas the player can see
pos = [0, 0]
diff = new SparseMap(@level.width, @level.height)
isWalkable = (x, y) =>
vec2.set pos, x, y
@level.terrain.get(pos) of WALKABLE_TILES
fov = new ROT.FOV.PreciseShadowcasting(isWalkable)
for _, player of @playerActors
[x, y] = player.pos
fov.compute x, y, 10, (x, y, _, visible) =>
# for now, just send terrain data
vec2.set pos, x, y
diff.set pos, terrain: @level.terrain.get pos
return diff
toJSON: ->
return {
players: (p.toJSON() for _, p of @playerActors)
level: @level.toJSON()
}
class Level
constructor: (@world, @depth, @name) ->
@width = 60
@height = 24
@actors = new SparseMapList(@width, @height)
@piles = new SparseMapList(@width, @height)
@terrain = new DenseMap(@width, @height)
pos = [0, 0]
map = new ROT.Map.Digger(@width, @height)
map.create (x, y, v) =>
vec2.set pos, x, y
@terrain.set pos, switch v
when 0 then TILES.FLOOR
when 1 then TILES.VOID
for corridor in map.getCorridors()
for x in [corridor._startX..corridor._endX]
for y in [corridor._startY..corridor._endY]
vec2.set pos, x, y
@terrain.set pos, TILES.CORRIDOR if @terrain.get(pos) is TILES.FLOOR
maybeDoor = (x, y) =>
vec2.set pos, x, y
tile = @terrain.get pos
if tile is TILES.FLOOR then @terrain.set pos, TILES.DOOR
if tile is TILES.VOID then @terrain.set pos, TILES.WALL
for room in map.getRooms()
x1 = room._x1 - 1
x2 = room._x2 + 1
y1 = room._y1 - 1
y2 = room._y2 + 1
for x in [x1..x2]
maybeDoor x, y1
maybeDoor x, y2
for y in [y1+1..y2-1]
maybeDoor x1, y
maybeDoor x2, y
pos = @pickPositionOfType(TILES.FLOOR)
@terrain.set pos, TILES.STAIRCASE_UP
pos = @pickPositionOfType(TILES.FLOOR)
@terrain.set pos, TILES.STAIRCASE_DOWN
@monsters = {}
monsterSpec = [
{ cls: Mosquito, min: 1, max: 3 }
{ cls: Slug, min: 3, max: 6 }
{ cls: Seeker, min: 5, max: 8 }
]
for {cls, min, max} in monsterSpec
for i in [0..random.integer(max, min)]
monster = new cls()
monster.id = @world.getGUID()
monster.lastTick = random.integer 10
monster.pos = @pickRandomSpawnablePosition()
@actors.add monster.pos, monster
@monsters[monster.id] = monster
@items = {}
itemSpec = [
{ cls: 'gold', min: 0, max: 3 },
{ cls: 'weapon', min: 0, max: 3},
{ cls: 'potion', min: 0, max: 1},
]
for {cls, min, max} in itemSpec
for i in [0..random.integer(max, min)]
item = Item.createFromClass cls
item.id = @world.getGUID()
vec2.copy item.pos, @pickRandomSpawnablePosition()
@piles.add item.pos, item
@items[item.id] = item
pickPositionOfType: (type) ->
tries = 0
pos = [0, 0]
loop
vec2.set pos, random.integer(@width-1), random.integer(@height-1)
return pos if @terrain.get(pos) is type
break if tries++ > 1000
for x in [0...@width]
for y in [0...@height]
vec2.set pos, x, y
return pos if @terrain.get(pos) is type
return null
pickRandomSpawnablePosition: ->
pos = [0, 0]
loop
vec2.set pos, random.integer(@width-1), random.integer(@height-1)
return pos if @terrain.get(pos) is TILES.FLOOR and @actors.isEmpty(pos)
toJSON: ->
return {
name: @name
width: @width
height: @height
terrain: @terrain.toJSON()
}
class Actor
constructor: ->
@id = -1
@pos = [0, 0]
@items = []
@weapon = null
@gold = 0
@isDead = false
class Player extends Actor
constructor: (@name) ->
super()
@lastInput = null
@isPlayer = true
@ap = 5
@hp = 50
@maxHp = 50
simulate: ->
obj = @lastInput
@lastInput = null
return obj
toViewJSON: ->
return {
id: @id
name: @name
pos: @pos
items: (i.toViewJSON() for i in @items)
gold: @gold
ap: @ap
hp: @hp
maxHp: @maxHp
weapon: @weapon?.toViewJSON()
isDead: @isDead
}
class Monster extends Actor
constructor: ->
super()
@pos = [0, 0]
@isPlayer = false
simulate: (world) ->
dir = random.pick 'n w s e nw sw se ne'.split ' '
return { command: 'attack-move', direction: dir }
toJSON: ->
return {
id: @id
name: @name
pos: @pos
speed: @speed
}
toViewJSON: ->
return {
id: @id
name: @name
pos: @pos
}
class Mosquito extends Monster
constructor: ->
super()
@name = 'mosquito'
@speed = 2
@hp = 1
@ap = 1
class Slug extends Monster
constructor: ->
super()
@name = 'slug'
@speed = 15
@hp = 10
@ap = 0
class Seeker extends Monster
constructor: ->
super()
@name = 'seeker'
@speed = 7
@sightRadius = 5
@hp = 10
@ap = 2
simulate: (world) ->
{level, actors} = world
vision = new SparseMap(level.width, level.height)
pos = [0, 0]
isWalkable = (x, y) ->
vec2.set pos, x, y
return level.terrain.get(pos) of WALKABLE_TILES
fov = new ROT.FOV.PreciseShadowcasting(isWalkable)
fov.compute @pos[0], @pos[1], 4, (x, y, _, visible) ->
vec2.set pos, x, y
vision.set pos, true
for y of vision.map
for x of vision.map[y]
vec2.set pos, x, y
actors = level.actors.get pos
if actors?
for actor in actors
if actor.isPlayer
target = actor.pos
break
if not target
return super(world)
steps = []
path = new ROT.Path.AStar(target[0], target[1], isWalkable)
path.compute @pos[0], @pos[1], (x, y) ->
steps.push [x, y]
if steps.length is 0
return super(world)
if steps.length is 1
throw new Error("Weird single step from #{ @pos } to #{ target }")
if steps.length > 1
vec2.sub pos, steps[1], steps[0]
for dir, offset of DIR_TO_VEC
if pos[0] is offset[0] and pos[1] is offset[1]
return { command: 'attack-move', direction: dir }
class Item
constructor: ->
@id = -1
@pos = [0, 0]
@createFromKey: (key) ->
return @createFromSpec ITEMS[key]
@createFromClass: (cls) ->
spec = random.pick(v for k, v of ITEMS when v.class is cls)
throw new Error("Unknown item class: #{ cls }") unless spec?
return @createFromSpec spec
@createFromSpec: (spec) ->
item = new this()
item.name = spec.name
item.class = spec.class
switch spec.class
when 'weapon'
item.ap = random.integer spec.apMax, spec.apMin
when 'gold'
item.value = random.integer 15, 1
when 'potion'
item.hp = random.integer spec.hpMax, spec.hpMin
return item
toViewJSON: ->
return {
id: @id
name: @name
class: @class
pos: @pos
}
ITEMS =
gold:
name: 'pieces of gold'
class: 'gold'
majorHealthPotion:
name: 'major health potion'
class: 'potion'
hpMin: 10
hpMax: 20
minorHealthPotion:
name: 'minor health potion'
class: 'potion'
hpMin: 4
hpMax: 8
shortSword:
name: 'short sword'
class: 'weapon'
apMin: 3
apMax: 6
longSword:
name: 'long sword'
class: 'weapon'
apMin: 4
apMax: 8
dagger:
name: 'dagger'
class: 'weapon'
apMin: 2
apMax: 4
sabre:
name: 'sabre'
class: 'weapon'
apMin: 6
apMax: 8
knife:
name: 'knife'
class: 'weapon'
apMin: 1
apMax: 3
screwdriver:
name: 'screwdriver'
class: 'weapon'
apMin: 1
apMax: 2