Created
June 9, 2014 14:32
-
-
Save toddself/ee23c74eb68a224c84ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var http = require('http'); | |
var url = require('url'); | |
function rollDie(max){ | |
return Math.floor(Math.random() * (max - 1 + 1)) + 1; | |
} | |
function startRollServer(port, ip){ | |
var server = http.createServer(function(req, res){ | |
var parsed = url.parse(req.url, true); | |
if(parsed.pathname === '/roll'){ | |
var diceData = parsed.query.text.split('d'); | |
var numDice = parseInt(diceData[0], 10); | |
var diceType = parseInt(diceData[1], 10); | |
var results = 0; | |
var roll = 0; | |
console.log('request', req.url); | |
if(!isNaN(numDice) && !isNaN(diceType)){ | |
console.log('valid request, rolling dice'); | |
numDice = numDice > 10 ? 10 : numDice; | |
diceType = diceType > 20 ? 20 : diceType; | |
for(var i = 0; i < numDice; i++){ | |
roll = rollDie(diceType); | |
results += roll; | |
} | |
} | |
var output = diceData.join('d')+': '+results; | |
res.end(output); | |
} else { | |
res.end('nope'); | |
} | |
}); | |
server.listen(port, ip); | |
console.log('listening on', ip+':'+port) | |
} | |
if(!module.parent){ | |
startRollServer(process.argv[3] || 3000, process.argv[2] || '127.0.0.1'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment