Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
275 lines (236 loc) · 7.28 KB
/
Copy pathserver.js
File metadata and controls
275 lines (236 loc) · 7.28 KB
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
// Module dependencies.
var express = require('express')
var connect = require('connect')
var stylus = require('stylus')
var nib = require('nib')
var sys = require('sys')
var http = require('http')
var browserify = require('browserify')
var map = require('./map')
var util = require('./js/util')
var fb = require('./fb')
var app = express()
var server = module.exports = http.createServer(app)
var io = require('socket.io').listen(server)
// Configuration
var public = __dirname + '/public'
app.configure(function() {
app.use(
stylus.middleware({
src: public,
dest: public,
compile: function(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', true)
.define('url', stylus.url())
.use(nib())
}
})
)
app.use(browserify({ entry: __dirname + '/js/main.js', mount: '/main.js' }))
app.use('/', express.static(public))
})
app.configure('development', function() {
app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }))
})
app.configure('production', function() {
app.use(connect.errorHandler())
})
io.configure('development', function() {
io.set('log level', 2)
})
io.configure('production', function() {
io.set('log level', 1)
io.set('transports', [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
])
io.enable('browser client minification')
io.enable('browser client etag')
io.enable('browser client gzip')
})
// Routes
app.get('/', function(req, res) {
res.sendfile('public/index.html')
})
var formationPage = '<html>' +
'<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# swarmation: http://ogp.me/ns/fb/swarmation#">' +
'<meta property="fb:app_id" content="536327243050948" />' +
'<meta property="og:type" content="game.achievement" />' +
'<meta property="og:title" content="{name}" />' +
'<meta property="og:description" content="Joined a formation of {points} players on Swarmation." />' +
'<meta property="og:url" content="http://swarmation.com/formation/{name}" />' +
'<meta property="og:image" content="http://swarmation.com/formation/{name}.png" />' +
'<meta property="game:points" content="{points}" />' +
'</head></html>';
var images = require('./images')
app.get('/formation/:name.png', function(req, res) {
var formation = formations[req.params.name]
if (!formation) res.send(404)
images.getImage(formation, function(err, buffer) {
if (err) throw err
res.type('png').send(buffer)
})
})
app.get('/formation/:name', function(req, res) {
var formation = formations[req.params.name]
if (!formation) res.send(404)
res.send(
formationPage
.replace(/\{name\}/g, req.params.name)
.replace(/\{points\}/g, formation.size)
)
})
// Error Handling
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
process.on('uncaughtException', function(e) {
sys.log(e.stack)
})
function shutdown() {
if (io.sockets) io.sockets.emit('restart')
setTimeout(function() {
process.exit()
}, 2000)
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
process.on('SIGHUP', shutdown)
// Model
var map = require('./map')
var players = require('./players')
var PLAYERS = players.PLAYERS
var Player = players.Player
// IO
function onConnect(client) {
client.emit('welcome', { id: client.id, players: Player.getList() })
if (FORMATION && (TIME > 0)) client.emit('nextFormation', {
formation: FORMATION.name, time: TIME, map: FORMATION.map, active: Player.getActive()
})
client.on('info', function(message) {
var player = Player.get(client)
player.setInfo(message)
// mark players that are active
if (!message.name) player.setActive()
message.id = client.id
client.broadcast.emit('info', message)
})
client.on('flash', function(message) {
message.id = client.id
client.broadcast.emit('flash', message)
})
client.on('login', function(message) {
var player = Player.get(client)
if (!player) return
player.login(message.userId, message.token)
fb.get(config.appId + '/scores', message.token, function(err, res) {
if (err) throw err
player.score = res.data[0].score
sys.log('FB: Loaded score for user '+message.userId+': ' + player.score)
io.sockets.emit('info', { id: client.id, score: player.score })
})
})
client.on('disconnect', function() {
Player.get(client).disconnect(io.sockets)
})
}
io.sockets.on('connection', onConnect)
// Formation countdown
var formations = require('./formations').getFormations()
var config = require('./config')
var FORMATIONS = []
var FORMATION
var MIN_SIZE = 3
var MAX_SIZE = 20
for (var i=0; i<=MAX_SIZE; i++) FORMATIONS[i] = []
util.each(formations, function(id, formation) {
for (var i=formation.size; i<=MAX_SIZE; i++) {
FORMATIONS[i].push(formation)
}
// register achievements with FB
fb.post(config.appId + '/achievements', config.token, {
achievement: 'http://swarmation.com/formation/' + formation.name
}, function(err, res) {
if (err) throw err
sys.log('FB: Registered formation ' + formation.name)
})
})
function pickFormation() {
var available = FORMATIONS[Math.max(MIN_SIZE, Math.min(Player.getActive(), MAX_SIZE))]
if (available.length == 0) return
return available[Math.floor(Math.random()*available.length)]
}
function startTurn() {
sys.log('There are '+Player.getActive()+' active players.')
FORMATION = pickFormation()
while (!FORMATION) FORMATION = pickFormation()
TIME = FORMATION.difficulty
sys.log('Next formation is ' + FORMATION.name +', of size '+(FORMATION.size)+'.')
io.sockets.emit('nextFormation', {
formation: FORMATION.name, time: TIME, map: FORMATION.map, active: Player.getActive()
})
}
var MAX_POINTS = 26
function endTurn() {
var players = map.checkFormation(FORMATION, PLAYERS)
var gain = FORMATION.difficulty
var loss = Math.round((MAX_POINTS-FORMATION.difficulty)/4)
var ids = Object.keys(players)
io.sockets.emit('formation', {
formation: FORMATION.name,
difficulty: FORMATION.difficulty,
gain: gain,
loss: loss,
ids: ids
})
util.each(players, function(id, player) {
player.setActive()
if (ids.indexOf(id) >= 0) {
player.score += gain
} else {
player.score = Math.max(0, player.score-loss)
}
if (player.userId) {
// post formation
fb.post(
player.userId+'/achievements',
config.token,
{ achievement: 'http://swarmation.com/formation/' + FORMATION.name },
function(err, res) {
if (err) throw err
sys.log('FB: Published completion of ' + FORMATION.name + ' for ' + player.userId)
}
)
// save score
fb.post(
player.userId+'/scores',
config.token,
{ score: player.score },
function(err, res) {
if (err) throw err
sys.log('FB: Saved score of ' + player.score + ' for ' + player.userId)
}
)
}
})
Player.endTurn()
}
// main loop
var TIME = 0
setInterval(function() {
TIME--
if (TIME == 0) {
if (FORMATION) endTurn()
}
if (TIME == -1) startTurn()
}, 1000)
// Only listen on $ node server.js
var port = parseInt(process.env.PORT, 10) || parseInt(process.argv[2], 10) || 3000
if (!module.parent) server.listen(port)
sys.log('Server now listening on port '+port+'...')