Skip to content
Snippets Groups Projects
Commit e702a99c authored by evilgenius's avatar evilgenius
Browse files

Initial commit to github after much tinkering

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1131 additions and 0 deletions
dist
node_modules
checkpoints
.jshintrc 0 → 100644
{
// --------------------------------------------------------------------
// JSHint Nodeclipse Configuration v0.15.1
// Strict Edition with some relaxations and switch to Node.js, no `use strict`
// by Ory Band, Michael Haschke, Paul Verest
// https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.ui/templates/common-templates/.jshintrc
// JSHint Documentation is at http://www.jshint.com/docs/options/
// JSHint Integration v0.9.9 comes with JSHInt 2.1.10 , see https://github.com/eclipsesource/jshint-eclipse
// Known issues:
// newer JSHint can't be used https://github.com/eclipsesource/jshint-eclipse/issues/75 that depends on JSHint issues.
// --------------------------------------------------------------------
// from https://gist.github.com/haschek/2595796
//
// @author http://michael.haschke.biz/
// @license http://unlicense.org/
//
// This is a options template for [JSHint][1], using [JSHint example][2]
// and [Ory Band's example][3] as basis and setting config values to
// be most strict:
//
// * set all enforcing options to true
// * set all relaxing options to false
// * set all environment options to false, except the node value
// * set all JSLint legacy options to false
//
// [1]: http://www.jshint.com/
// [2]: https://github.com/jshint/node-jshint/blob/master/example/config.json //404
// [3]: https://github.com/oryband/dotfiles/blob/master/jshintrc //404
// [4]: http://www.jshint.com/options/
// == Enforcing Options ===============================================
//
// These options tell JSHint to be more strict towards your code. Use
// them if you want to allow only a safe subset of JavaScript, very
// useful when your codebase is shared with a big number of developers
// with different skill levels. Was all true.
"bitwise" : true, // Prohibit bitwise operators (&, |, ^, etc.).
"curly" : true, // Require {} for every new block or scope.
"eqeqeq" : true, // Require triple equals i.e. `===`.
"forin" : true, // Tolerate `for in` loops without `hasOwnPrototype`.
"immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
"latedef" : true, // Prohibit variable use before definition.
"newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`.
"noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`.
"noempty" : true, // Prohibit use of empty blocks.
"nonew" : true, // Prohibit use of constructors for side-effects.
"plusplus" : false, // Prohibit use of `++` & `--`. //coding style related only
"regexp" : true, // Prohibit `.` and `[^...]` in regular expressions.
"undef" : true, // Require all non-global variables be declared before they are used.
"strict" : false, // Require `use strict` pragma in every file.
"trailing" : true, // Prohibit trailing whitespaces.
// == Relaxing Options ================================================
//
// These options allow you to suppress certain types of warnings. Use
// them only if you are absolutely positive that you know what you are
// doing. Was all false.
"asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons).
"boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
"debug" : false, // Allow debugger statements e.g. browser breakpoints.
"eqnull" : false, // Tolerate use of `== null`.
"es5" : true, // Allow EcmaScript 5 syntax. // es5 is default https://github.com/jshint/jshint/issues/1411
"esnext" : false, // Allow ES.next (ECMAScript 6) specific features such as `const` and `let`.
"evil" : false, // Tolerate use of `eval`.
"expr" : false, // Tolerate `ExpressionStatement` as Programs.
"funcscope" : false, // Tolerate declarations of variables inside of control structures while accessing them later from the outside.
"globalstrict" : false, // Allow global "use strict" (also enables 'strict').
"iterator" : false, // Allow usage of __iterator__ property.
"lastsemic" : false, // Tolerat missing semicolons when the it is omitted for the last statement in a one-line block.
"laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
"laxcomma" : true, // Suppress warnings about comma-first coding style.
"loopfunc" : false, // Allow functions to be defined within loops.
"maxerr" : 100, // This options allows you to set the maximum amount of warnings JSHint will produce before giving up. Default is 50.
"moz" : false, // This options tells JSHint that your code uses Mozilla JavaScript extensions. Unless you develop specifically for the Firefox web browser you don't need this option.
"multistr" : false, // Tolerate multi-line strings.
"onecase" : false, // Tolerate switches with just one case.
"proto" : false, // Tolerate __proto__ property. This property is deprecated.
"regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`.
"scripturl" : false, // Tolerate script-targeted URLs.
"smarttabs" : false, // Tolerate mixed tabs and spaces when the latter are used for alignmnent only.
"shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`.
"sub" : false, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
"supernew" : false, // Tolerate `new function () { ... };` and `new Object;`.
"validthis" : false, // Tolerate strict violations when the code is running in strict mode and you use this in a non-constructor function.
// == Environments ====================================================
//
// These options pre-define global variables that are exposed by
// popular JavaScript libraries and runtime environments—such as
// browser or node.js. TODO JSHint Documentation has more, but it is not clear since what JSHint version they appeared
"browser" : false, // Standard browser globals e.g. `window`, `document`.
"couch" : false, // Enable globals exposed by CouchDB.
"devel" : false, // Allow development statements e.g. `console.log();`.
"dojo" : false, // Enable globals exposed by Dojo Toolkit.
"jquery" : false, // Enable globals exposed by jQuery JavaScript library.
"mootools" : false, // Enable globals exposed by MooTools JavaScript framework.
"node" : true, // Enable globals available when code is running inside of the NodeJS runtime environment.
"nonstandard" : false, // Define non-standard but widely adopted globals such as escape and unescape.
"phantom" : false, //?since version? This option defines globals available when your core is running inside of the PhantomJS runtime environment.
"prototypejs" : false, // Enable globals exposed by Prototype JavaScript framework.
"rhino" : false, // Enable globals available when your code is running inside of the Rhino runtime environment.
"worker" : false, //?since version? This option defines globals available when your code is running inside of a Web Worker.
"wsh" : false, // Enable globals available when your code is running as a script for the Windows Script Host.
"yui" : false, //?since version? This option defines globals exposed by the YUI JavaScript framework.
// == JSLint Legacy ===================================================
//
// These options are legacy from JSLint. Aside from bug fixes they will
// not be improved in any way and might be removed at any point.
"nomen" : false, // Prohibit use of initial or trailing underbars in names.
"onevar" : false, // Allow only one `var` statement per function.
"passfail" : false, // Stop on first error.
"white" : false, // Check against strict whitespace and indentation rules.
// == Undocumented Options ============================================
//
// While Michael have found these options in [example1][2] and [example2][3] (already gone 404)
// they are not described in the [JSHint Options documentation][4].
"predef" : [ // Extra globals.
//"exampleVar",
//"anotherCoolGlobal",
//"iLoveDouglas"
"Java", "JavaFX", "$ARG" //no effect
]
//, "indent" : 2 // Specify indentation spacing
}
.project 0 → 100644
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Malice</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.eclipsesource.jshint.ui.builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.nodeclipse.ui.NodeNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>tern.eclipse.ide.core.ternnature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="node_modules/**/*" kind="src" path=""/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="node_modules"/>
<classpathentry kind="output" path=""/>
</classpath>
eclipse.preferences.version=1
excluded=//*.json\:bower_components//*\:node_lib//*\:node_modules//*
included=//*.jjs\://*.js\://*.jshintrc\://*.mjs\://*.njs\://*.pjs\://*.vjs
projectSpecificOptions=true
eclipse.preferences.version=1
encoding//src/login.coffee=UTF-8
encoding//txt/welcome.txt=UTF-8
eclipse.preferences.version=1
semanticValidation=disabled
org.eclipse.wst.jsdt.launching.JRE_CONTAINER
\ No newline at end of file
Global
\ No newline at end of file
{"libs":["ecma5"],"plugins":{"node":{}},"ide":{}}
\ No newline at end of file
# CrimsonMUD
## Usage
## Developing
### Tools
Created with [Nodeclipse](https://github.com/Nodeclipse/nodeclipse-1)
([Eclipse Marketplace](http://marketplace.eclipse.org/content/nodeclipse), [site](http://www.nodeclipse.org))
Nodeclipse is free open-source project that grows with your contributions.
0 info it worked if it ends with ok
1 verbose cli [ '/home/cabox/.nvm/versions/node/v5.2.0/bin/node',
1 verbose cli '/home/cabox/.nvm/versions/node/v5.2.0/bin/npm',
1 verbose cli 'run-script',
1 verbose cli 'watch-mac' ]
2 info using npm@3.5.1
3 info using node@v5.2.0
4 verbose run-script [ 'prewatch-mac', 'watch-mac', 'postwatch-mac' ]
5 info lifecycle Malice@0.1.0~prewatch-mac: Malice@0.1.0
6 silly lifecycle Malice@0.1.0~prewatch-mac: no script for prewatch-mac, continuing
7 info lifecycle Malice@0.1.0~watch-mac: Malice@0.1.0
8 verbose lifecycle Malice@0.1.0~watch-mac: unsafe-perm in lifecycle true
9 verbose lifecycle Malice@0.1.0~watch-mac: PATH: /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/npm/bin/node-gyp-bin:/home/cabox/workspace/node_modules/.bin:/home/cabox/.nvm/versions/node/v5.2.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
10 verbose lifecycle Malice@0.1.0~watch-mac: CWD: /home/cabox/workspace
11 silly lifecycle Malice@0.1.0~watch-mac: Args: [ '-c', '(coffee --compile --output dist --watch src)' ]
12 silly lifecycle Malice@0.1.0~watch-mac: Returned: code: 143 signal: null
13 info lifecycle Malice@0.1.0~watch-mac: Failed to exec watch-mac script
14 verbose stack Error: Malice@0.1.0 watch-mac: `(coffee --compile --output dist --watch src)`
14 verbose stack Exit status 143
14 verbose stack at EventEmitter.<anonymous> (/home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/npm/lib/utils/lifecycle.js:232:16)
14 verbose stack at emitTwo (events.js:88:13)
14 verbose stack at EventEmitter.emit (events.js:173:7)
14 verbose stack at ChildProcess.<anonymous> (/home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/npm/lib/utils/spawn.js:24:14)
14 verbose stack at emitTwo (events.js:88:13)
14 verbose stack at ChildProcess.emit (events.js:173:7)
14 verbose stack at maybeClose (internal/child_process.js:819:16)
14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:212:5)
15 verbose pkgid Malice@0.1.0
16 verbose cwd /home/cabox/workspace
17 error Linux 2.6.32-042stab112.15
18 error argv "/home/cabox/.nvm/versions/node/v5.2.0/bin/node" "/home/cabox/.nvm/versions/node/v5.2.0/bin/npm" "run-script" "watch-mac"
19 error node v5.2.0
20 error npm v3.5.1
21 error code ELIFECYCLE
22 error Malice@0.1.0 watch-mac: `(coffee --compile --output dist --watch src)`
22 error Exit status 143
23 error Failed at the Malice@0.1.0 watch-mac script '(coffee --compile --output dist --watch src)'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the Malice package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error (coffee --compile --output dist --watch src)
23 error You can get information on how to open an issue for this project with:
23 error npm bugs Malice
23 error Or if that isn't available, you can get their info via:
23 error npm owner ls Malice
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
{
"name": "Malice",
"version": "0.1.0",
"description": "Malice",
"main": "dist/driver.js",
"scripts": {
"test": "echo \"Error: no test specified! Configure in package.json\" && exit 1",
"watch": "(start coffee --compile --output dist --watch src)",
"watch-mac": "(coffee --compile --output dist --watch src)",
"start": "node ./dist/driver.js",
"compile": "coffee --compile --output dist src"
},
"repository": "",
"keywords": [
"node.js",
"eclipse",
"nodeclipse"
],
"author": "",
"license": "MIT",
"readmeFilename": "README.md",
"dependencies": {
"app-module-path": "^2.1.0",
"colors": "^1.1.2",
"cryo": "0.0.6",
"listify": "^1.0.0",
"moment": "^2.10.6",
"nesh": "^1.6.0",
"node-eval": "^1.1.0",
"node-serialize": "0.0.4",
"node-uuid": "^1.4.3",
"nodemailer": "^2.6.4",
"nodemon": "^1.5.0",
"q": "^1.4.1",
"telnet": "0.0.1",
"underscore": "^1.8.3",
"watchr": "^3.0.1",
"wordwrap": "^1.0.0"
},
"devDependencies": {
"coffee-script": "^1.10.0"
}
}
global.$game.common = {} if not global.$game.common
global.$game.common.move = (what, to)->
what.location = global.$game.$index.rooms.$nowhere if not what.location
if what.location?.contents?
what.location.contents = what.location.contents.remove(what)
place.contents = [] if not place.contents
to.contents.push what
what.location = to
global.$game.common.moveTo = (to)->
global.$game.common.move(this, to)
global.$game.common.question = (socket, prompt, criteria, callback)->
deferred = require("./node_modules/q").defer()
readline = require("readline")
askQuestion = ->
rl = readline.createInterface(socket, socket)
rl.question prompt, (answer) ->
rl.close()
if answer == "@abort"
return deferred.reject("Abort")
result = if criteria then criteria(answer) else false
if result
socket.tell(result)
return askQuestion()
deferred.resolve(answer)
askQuestion()
return deferred.promise.nodeify(callback)
global.$game.common.yesorno = (socket, prompt, callback)->
deferred = require("./node_modules/q").defer()
global.$game.common.question socket, prompt, (criteria)->
return "Please answer yes or no." if not criteria or not criteria.toLowerCase().startsWith("y") && not criteria.toLowerCase().startsWith("n")
.then (answer) ->
if answer.toLowerCase().startsWith("y") then deferred.resolve("yes") else deferred.reject("no")
return deferred.promise.nodeify(callback)
global.$game.common.choice = (socket, prompt, choices, callback) ->
deferred = require("./node_modules/q").defer()
what = prompt + "\n"
index = 1
map = {}
for key, value of choices
if not choices.hasOwnProperty(key) then continue
what += " [" + (index).toString().bold + "] " + value + "\n"
map[index] = key
index++
index--
global.$game.common.question socket, what, (answer)->
return "Please enter a number between 1 and #{index} or " + "@abort".underline + " to abort." if isNaN(parseInt(answer)) || parseInt(answer) < 1 || parseInt(answer) > index
, (err, finalAnswer) ->
return deferred.reject("Abort") if err
deferred.resolve(map[parseInt(finalAnswer)])
return deferred.promise.nodeify(callback)
global.$game.common.gameTime = ->
moment = require("./node_modules/moment")
now = moment()
now.year(now.year() + 85)
\ No newline at end of file
if not global.$game.classes.BodyPart
global.$game.classes.BodyPart = class BodyPart
constructor:->
@type="$game.classes.BodyPart"
this.init.apply(this, arguments)
part = global.$game.classes.BodyPart.prototype
part.init = (@name, @bones, @coverable, @removable, @critical, @parts)->
@condition = {}
@wearing = []
part.findPart = (name)->
return this if name == @name || @name.indexOf(name) == 0 || name.test?(@name)
require("underscore").find @parts, (part)->
part.findPart(name)
part.coverageMap = (map = {})->
return map if not @coverable
map[@name] = this
@parts.forEach (part)->
part.coverageMap map
map
global.$game.common.makeBodyPart = (name, bones = [], coverable = false, removable = false, critical = false, parts={})->
new global.$game.classes.BodyPart name, bones, coverable, removable, critical, parts
global.$game.common.makeHead = ->
makeBodyPart = global.$game.common.makeBodyPart
head = makeBodyPart "head", ["skull", "jaw", "teeth"], true, true, true,
scalp:makeBodyPart "scalp", [], true, false, false
throat:makeBodyPart "throat", ["larynx"], true, false, true
neck:makeBodyPart "neck", ["spine"], true, false, true
rightEar:makeBodyPart "right ear", [], true, true, false
leftEar:makeBodyPart "left ear", [], true, true, false
face:makeBodyPart "face", [], true, false, false,
leftEye:makeBodyPart "left eye", [], true, true, false
rightEye:makeBodyPart "right eye", [], true, true, false
mouth:makeBodyPart "mouth", [], true, false, false
nose:makeBodyPart "nose", [], true, true, false
head.canSee = ->
head?.leftEye?.canSee() || head?.rightEye?.canSee()
head.canHear = ->
head?.leftEar?.canHear() || head?.rightEar?.canHear()
head
global.$game.common.makeArm = (leftOrRight)->
makeBodyPart = global.$game.common.makeBodyPart
makeBodyPart leftOrRight + " shoulder", ["clavical", "scapula"], true, false, false,
arm:makeBodyPart leftOrRight + " arm", ["humerus"], true, true, false,
forearm:makeBodyPart leftOrRight + " forearm", ["radius", "ulna"], true, true, false,
hand:makeBodyPart leftOrRight + " hand", ["wrist"], true, true, false,
thumb:makeBodyPart leftOrRight + " thumb", ["metacarpals", "phalanges"], true, true, false
index:makeBodyPart leftOrRight + " index finger", ["metacarpals", "phalanges"], true, true, false
middle:makeBodyPart leftOrRight + " middle finger", ["metacarpals", "phalanges"], true, true, false
ring:makeBodyPart leftOrRight + " ring finger", ["metacarpals", "phalanges"], true, true, false
pinky:makeBodyPart leftOrRight + " pinky finger", ["metacarpals", "phalanges"], true, true, false
global.$game.common.makeLeg = (leftOrRight)->
makeBodyPart = global.$game.common.makeBodyPart
makeBodyPart leftOrRight + " thigh", ["femur"], true, true, false,
knee:makeBodyPart leftOrRight + " knee", ["knee cap"], true, true, false,
leg:makeBodyPart leftOrRight + " leg", ["tibia", "fibula"], true, true, false,
foot:makeBodyPart leftOrRight + " foot", ["metatarsus", "metatarsal"], true, true, false
global.$game.common.makePenis = ->
makeBodyPart = global.$game.common.makeBodyPart
makeBodyPart "groin", ["pelvis"], true, false, false,
penis:makeBodyPart "penis", [], false, true, false
leftTestical:makeBodyPart "left testical", [], false, true, false
rightTestical:makeBodyPart "right testical", [], false, true, false
global.$game.common.makeVagina = ->
makeBodyPart = global.$game.common.makeBodyPart
makeBodyPart "groin", ["pelvis"], true, false, false,
global.$game.common.makeBodyPart "vagina", [], false, false, false
global.$game.common.makeNeuter = ->
makeBodyPart = global.$game.common.makeBodyPart
makeBodyPart "groin", ["pelvis"], true, false, false
if not global.$game.classes.HumanBody
global.$game.classes.HumanBody = class HumanBody
constructor:->
@type = "$game.classes.HumanBody"
this.init.apply(this, arguments)
body = global.$game.classes.HumanBody.prototype
body.init = (@sex = "female", @primaryHand = "right")->
@torso = global.$game.common.makeBodyPart "torso", [], true, false, true,
head:global.$game.common.makeHead()
rightShoulder:global.$game.common.makeArm("right")
leftShoulder:global.$game.common.makeArm("left")
rightThigh:global.$game.common.makeLeg("right")
leftThigh:global.$game.common.makeLeg("left")
groin:if @sex == "male" then global.$game.common.makePenis() else if @sex == "female" then global.$game.common.makeVagina() else global.$game.common.makeNeuter()
leftChest:global.$game.common.makeBodyPart "left half of the chest", ["ribs"], true, false, false
rightChest:global.$game.common.makeBodyPart "right half of the chest", ["ribs"], true, false, false
stomach:global.$game.common.makeBodyPart "stomach", [], true, false, false
back:global.$game.common.makeBodyPart "back", ["spine"], true, false, false
body.getTorso = ->
@torso
body.getPart = (name)->
@getTorso().getPart(name)
body.getHead = ->
@getTorso().parts.head
body.getRightHand = ->
@getTorso().parts.rightShoulder.parts.arm.parts.forearm.parts.hand
body.getLeftHand = ->
@getTorso().parts.leftShoulder?.parts?.arm?.parts?.forearm?.parts?.hand
body.getRightFoot = ->
@getTorso().parts.rightThigh?.parts?.knee?.parts?.leg?.parts?.foot
body.getLeftFoot = ->
@getTorso().parts.leftThigh?.parts?.knee?.parts?.leg?.parts?.foot
body.getPrimaryHand = ->
if primaryHand == "right" then @getRightHand() else @getLeftHand()
body.getSecondaryHand = ->
if primaryHand == "right" then @getLeftHand() else @getRightHand()
body.getHand = ->
@getPrimaryHand() || @getSecondaryHand()
body.getBothHands = ->
[@getPrimaryHand(), @getSecondaryHand()]
body.getFreeHand = ->
if @getPrimaryHand.isEmpty() then @getPrimaryHand else if @getSecondaryHand().isEmpty() then @getSecondaryHand() else undefined
body.isOneHandEmpty = ->
@getPrimaryHand().isEmpty() || @getSecondaryHand().isEmpty()
body.isBothHandsEmpty = ->
@getPrimaryHand().isEmpty() && @getSecondaryHand().isEmpty()
body.holdInHands = (what)->
q = require("./node_modules/q")
return q.reject("Your hands are full.") if not @isOneHandEmpty
return q.reject("That requires both hands to hold.") if what.isTwoHanded?() and not @isBothHandsFree()
firstHand = @getFreeHand()
where = firstHand
if(what.isTwoHanded?())
secondHand = @getFreeHand()
secondHand.holding = what
where = [firstHand, secondHand]
what.moveTo(where)
q(where)
global.$game.common = {} if not global.$game.common
global.$game.common.charGen = {} if not global.$game.common.charGen
charGen = global.$game.common.charGen
charGen.start = (socket)->
socket.tell("Warning: ".red + "You must complete this process without disconnecting, otherwise you will have to start over.")
options = {"name":"Name", "birthday":"Birthday", "sex":"Sex", "ethnicity":"Ethnicity", "stats":"Height and Weight", "appearance":"Appearance", "language":"Native Language", "abort":"Abort".red}
remaining = ["Name", "Birthday", "Sex", "Ethnicity", "Height and Weight", "Appearance", "Native Language"]
results = {}
makePlayerLoop = ->
if results.name then options.name = "Name".green
if results.birthday then options.birthday = "Birthday".green
if results.sex then options.sex = "Sex".green
if results.ethnicity then options.ethnicity = "Ethnicity".green
if results.stats then options.stats = "Height and Weight".green
if results.appearance then options.appearance = "Appearance".green
if results.language then options.language = "Native Language".green
progress = global.$game.common.charGen.formatProgress(results)
prompt = "#{'Character Generation Main Menu'.bold.green}\n"
prompt += progress if progress
prompt += if remaining.length then "Things you still must do before you finish: #{remaining.join(', ').yellow}" else "You're all set. Select ".green + "Finish".green.bold + " to finalize your character.".green
if remaining.length == 0 && not options.finish then options.finish = "Finish".green.bold
socket.choice(prompt, options)
.then (option)->
console.log("option: " + option)
if option == "abort" then throw new Error("Aborting...")
if option == "finish"
socket.tell("This is how you're character is going to start:")
socket.tell global.$game.common.charGen.formatProgress(results)
socket.tell "Now they may not be like that forever, but it may take a little doing to make changes after this."
socket.tell "This is your last chance to say no and make changes.".bold.underline
return global.$game.common.yesorno socket, "Continue with creating your character?\n"
.then ->
global.$game.common.charGen.cloneNewPlayer(socket, results)
.catch ->
setTimeout makePlayerLoop, 0
global.$game.common.charGen[option] socket
.then (stats) ->
console.log("stat: " + stats)
results[option] = stats
remaining.remove options[option]
setTimeout makePlayerLoop, 0
.catch (error) ->
global.catch(error)
socket.tell error.message
setTimeout makePlayerLoop, 0
.catch (error) ->
global.catch(error)
socket.tell error.message
setTimeout ->
socket.user.handleConnection socket
makePlayerLoop()
charGen.cloneNewPlayer = (socket, info)->
player = new global.$game.classes.Player(info.name.alias, socket.user, info)
socket.tell("Designing bio-specification for clone job.".cyan)
socket.tell("Please wait...".italic)
phrases = [
"Checking the geans that code for histocampatibility antigens.".blue,
"Counting and eliminating NK cells.".yellow,
"Activating humoral immunity and stimulating antibody production.".green,
"Checking B cell response for memory properties.".cyan
"Injecting antigens and stimulating natural immune response.".cyan
"Expressing maximum sensitivity though knock-in mutation to combat transgenic mutations.".red
"Modulating tissue plasminogen activator to induce fibrinolsis.".red
"Initiating homologous recombination on all prepared DNA sequences.".blue
"Mapping positional effects of transitive genome inhibitors.".yellow
"Eliminating hereditary conditions and mapping to substitute sequences.".yellow
"Looking for dominant negatives in defected RNA protein molecules.".green
"Permanently hibernating unwanted mutations through insertional mutagenesis.".yellow
"Building scaffolding for cartiovascular structures.".white
"Running Monte Carlo simulation on best drug compatibility matrix.".white
"Slowly devouring your soul.".trap
]
enders = [
"Finished.".green
"Process complete.".green
"Process failed. Removing from process queue and scheduling replacement process to compensate.".yellow
"Partial completion. Scheduling follow up check.".yellow
"Done.".green
"Complete.".green
"Awaiting completion.".green
"Task complete.".green
"Job done.".green
"Scheduled task finished.".green
"Task was interrupted. Scheduling follow up check.".yellow
"Status unknown. Rescheduling job.".red
"System Error! Status unknown. Possible infection.".trap
]
setTimeout ->
socket.tell("Allocating resources on the cluster and scheduling clone job according to your specifications.".cyan)
socket.tell("Please wait... this might take a minute.".italic)
x = 2 + Math.floor(Math.random()*3)
waitMore = ->
if x == 0
socket.tell("Progress: ".cyan + "Vital signs detected! ".blue + "Completing cloning process...".yellow)
return setTimeout ->
socket.tell("Cloning process successful! Returning control to user...".green.bold.italic)
return socket.user.handleConnection socket
, 3000
x--
setTimeout ->
phrase = phrases[Math.floor(Math.random()*(phrases.length))]
phrases.remove(phrase)
socket.tell("Progress: ".cyan + phrase)
setTimeout ->
ender = enders[Math.floor(Math.random()*(enders.length))]
enders.remove(ender)
socket.tell("Progress: ".cyan + ender)
setTimeout waitMore, 1000 + Math.floor(Math.random()*1000)
, 1000 + Math.floor(Math.random()*1000)
, 1000 + Math.floor(Math.random()*1000)
waitMore()
, 1000 + Math.floor(Math.random()*1000)
charGen.formatProgress = (progress)->
results = ""
moment = require("./node_modules/moment")
if progress.name then results += "Alias: " + progress.name.alias + "\n"
if progress.name then results += "First Name: " + progress.name.firstName + "\n"
if progress.name then results += "Last Name: " + progress.name.lastName + "\n"
if progress?.name?.middleName then results += "Middle Name: " + progress.name.middleName + "\n"
if progress.sex then results += "Sex: " + progress.sex + "\n"
if progress.ethnicity then results += "Ethnicity: " + progress.ethnicity + "\n"
if progress.birthday then results += "Birthday: " + moment(progress.birthday).format("dddd, MMMM Do, YYYY") + "\n"
if progress.stats then results += "Height: " + progress.stats.height + " Meters" + " (" + global.$game.constants.player.formatHeight(progress.stats.height) + ")" + "\n"
if progress.stats then results += "Weight: " + progress.stats.weight + " Kilograms (#{global.$game.constants.player.formatWeight(progress.stats.weight, progress.stats.height)} for your height)\n"
if progress.appearance then results += "Eyes: " + progress.appearance.eyeStyle + " " + progress.appearance.eyeColor + " eyes\n"
if progress.appearance then results += "Hair: " + progress.appearance.hairCut + " " + progress.appearance.hairColor + " " + progress.appearance.hairStyle + "\n"
if progress.appearance then results += "Skin: " + progress.appearance.skinStyle + " " + progress.appearance.skinColor + "\n"
if progress.language then results += "Language: " + progress.language + "\n"
return results.bgBlue.white
charGen.birthday = (socket) ->
moment = require("./node_modules/moment")
socket.tell("The City of Malice exists in " + "real-time".bold + ", " + "85 years in the future".underline + ", in the Pacific time zone.")
socket.tell("The current game time is #{global.$game.common.gameTime().format('dddd, MMMM Do, YYYY')}. Please take that into consideration when you give your birthdate. Your character should have an appropriate birth date to reflect the game's timeline.")
socket.question "Please enter your birthday in the format: MM/DD/YYYY. So for April 3rd, 2068, you would enter: 4/3/2068.\n", (criteria)->
date = moment(criteria.trim(), "MM/DD/YYYY")
return "Please enter a valid birthday." if not date.isValid()
return "Please enter a birthday after today's date." if date.isBefore(moment())
before = global.$game.common.gameTime()
before = before.year(before.year()-18)
return "Please enter a birthday making your character at least 18 years of age." if before.isBefore(date)
.then (birthday) ->
moment(birthday.trim(), "MM/DD/YYYY").toDate()
charGen.ethnicity = (socket) ->
socket.choice "What is your ethnicity?", global.$game.constants.player.ethnicity
.then (choice) ->
global.$game.constants.player.ethnicity[choice]
charGen.language = (socket) ->
socket.tell "The game is in English, but your character may be a foreigner, in which case they may not speak the local language. In any case, you can always learn a new language once in the game."
socket.choice "What is your primary language?", global.$game.constants.player.language
.then (result)->
global.$game.constants.player.language[result]
charGen.name = (socket)->
alias = firstName = lastName = middleName = ""
namePrompt = """
What is your character's most common name?
This can be their first name, last name, or a nick name that they're always called. It should be a single word.
You can also log in with this name, and be addressed by others with it by default, so make it easy to type or at least shorten.
"""
socket.question namePrompt, (criteria) ->
return "It must be at least three letters long." if criteria.trim().length < 3
return "It must be a single word." if criteria.trim().indexOf(" ") > -1
return "User names cannot contain any non alphabet characters." if not /^[a-zA-Z]*$/.test(criteria)
_ = require("./node_modules/underscore")
existingUsers = _(global.$game.$index.users).find (user) ->
user.name.toLowerCase() == criteria
existingPlayers = _(global.$game.$index.players).find (player) ->
player.name.toLowerCase() == criteria
if existingPlayers or existingPlayers then return "That name is taken."
.then (aliasAnswer)->
alias = aliasAnswer
socket.question "Ok. What is their real first name from birth?\n", (criteria) ->
return "Please enter their first name from birth." if criteria.trim().length < 2
return "First names cannot contain any non alphabet characters." if not /^[a-zA-Z]*$/.test(criteria)
.then (firstNameAnswer) ->
firstName = firstNameAnswer
socket.question "Now please enter your last name, or the last name of the mother at birth?\n", (criteria) ->
return "Please enter their last name from birth." if criteria.trim().length < 2
return "Middle names cannot contain any non alphabet characters." if not /^[a-zA-Z]*$/.test(criteria)
.then (lastNameAnswer) ->
lastName = lastNameAnswer
socket.question "And if they have a middle name, please enter it now, otherwise leave it blank.\n", (criteria) ->
return "Middle names cannot contain any non alphabet characters." if criteria.trim().length > 0 and not /^[a-zA-Z]*$/.test(criteria)
.then (middleNameAnswer) ->
middleName = middleNameAnswer
return {
alias:alias.trim(),
firstName:firstName.trim(),
lastName:lastName.trim(),
middleName:middleName.trim()
}
charGen.sex = (socket)->
sexPrompt = """
What is your characters #{'sex'.bold}?
(We're going to keep it simple here, although we do understand sometimes the reality can be a little more complex.)
"""
socket.choice sexPrompt, {"male":"Male", "female":"Female"}
charGen.stats = (socket) ->
socket.tell("In The City of Malice, appearances matter.")
socket.tell("The 'average' weight and height for people is about 1.7 meters and 75 kilograms (or about 6 foot tall and 180 pounds). Deviation from that is going to impact your play style.")
askQuestion = ->
ask = global.$game.common.question
heightPrompt = """
What is the #{'height'.bold} of your character? Please answer in meters, between 0.5 and 3.
For example, if your character was 1.8 meters (about 6 feet tall), you would type: '1.8'.\n
"""
height = weight = 0
ask socket, heightPrompt, (criteria) ->
return "Please enter a number between 0.5 and 3, like 1.8." if isNaN(criteria) || criteria < 0.5|| criteria > 3
.then (heightInput) ->
height = Math.floor(heightInput * 100) / 100
ask socket, "That would make you #{global.$game.constants.player.formatHeight(height)}. And your weight in kilograms?\n", (criteria) ->
return "Please enter a number between 15 and 300." if isNaN(parseInt(criteria)) || parseInt(criteria) < 15 || parseInt(criteria) > 300
.then (weightInput)->
weight = parseInt(weightInput)
socket.yesorno "That would make you #{global.$game.constants.player.formatWeight(weight, height)} for your height. Is that ok?\n"
.then ->
return {
height:height
weight:weight
}
.catch ->
askQuestion()
askQuestion()
charGen.appearance = (socket) ->
hairCut = hairStyle = hairColor = eyeColor = eyeStyle = skinColor = skinStyle = undefined;
socket.choice "What would you like your #{'hair cut'.bold} to be?", global.$game.constants.player.hairCut
.then (hairCutChoice)->
hairCut = global.$game.constants.player.hairCut[hairCutChoice]
socket.choice "And the #{'hair style'.bold} to go with your #{hairCut} hair?", global.$game.constants.player.hairStyle
.then (hairStyleChoice)->
hairStyle = global.$game.constants.player.hairStyle[hairStyleChoice]
socket.choice "And is the #{'hair color'.bold} of your #{hairCut} #{hairStyle} hair?", global.$game.constants.player.hairColor
.then (hairColorChoice)->
hairColor = global.$game.constants.player.hairColor[hairColorChoice]
socket.choice "Fine. You have #{hairCut} #{hairColor} #{hairStyle} hair.\nWhat is your #{'eye color'.bold}?", global.$game.constants.player.eyeColor
.then (eyeColorChoice)->
eyeColor = global.$game.constants.player.eyeColor[eyeColorChoice]
socket.choice "Ok, and the #{'eye style'.bold} of these #{eyeColor} eyes?", global.$game.constants.player.eyeStyle
.then (eyeStyleChoice)->
eyeStyle = global.$game.constants.player.eyeStyle[eyeStyleChoice]
socket.choice "Perfect. You've got #{eyeColor} #{eyeStyle} eyes. Let's talk about your #{'skin'.bold}. How would you describe it?", global.$game.constants.player.skinStyle
.then (skinStyleChoice)->
skinStyle = global.$game.constants.player.skinStyle[skinStyleChoice]
socket.choice "Great. And what's the #{'skin color'.bold} of your #{skinStyle}?", global.$game.constants.player.skinColor
.then (skinColorChoice)->
skinColor = global.$game.constants.player.skinColor[skinColorChoice]
console.log({
hairCut:hairCut,
hairColor:hairColor,
hairStyle:hairStyle,
eyeColor:eyeColor,
eyeStyle:eyeStyle,
skinColor:skinColor,
skinStyle:skinStyle
})
return {
hairCut:hairCut,
hairColor:hairColor,
hairStyle:hairStyle,
eyeColor:eyeColor,
eyeStyle:eyeStyle,
skinColor:skinColor,
skinStyle:skinStyle
}
require('app-module-path').addPath(__dirname + '/dist');
serializer = require('./serialize.js')
loader = require("./loader.js")
watchr = require("watchr")
_ = require('underscore')
repl = require('repl')
fs = require('fs')
require('colors')
global.$driver = {}
global.$game = {}
$driver = global.$driver
$game = global.$game
global.$driver.clients = []
global.$driver.authenticatedUsers = {};
global.$driver.inputHandlers = {};
global.$driver.getSocket = (user) ->
global.$driver.authenticatedUsers[user]
global.$driver.getInputHandler = (player) ->
global.$driver.inputHandlers[player]
global.$driver.setInputHandler = (player, handler) ->
global.$driver.inputHandlers[player] = handler
global.$driver.clearInputHandler = (player) ->
delete global.$driver.inputHandlers[player]
global.catch = (error) ->
console.log(error)
console.log(error.stack)
Array.prototype.remove = ->
what = undefined
a = arguments
L = a.length
ax = undefined
while (L && this.length)
what = a[--L]
while ((ax = this.indexOf(what)) != -1)
this.splice(ax, 1)
return this
Array.prototype.proportionate = (num, max)->
return this[0] if num == 0
return this[this.length-1] if num == max
percent = num / max
where = (this.length - 1) * percent
return this[Math.min(this.length-2, Math.max(1,parseInt(where)))]
if (typeof String.prototype.startsWith != 'function')
String.prototype.startsWith = (str)->
return this.slice(0, str.length) == str
if (typeof String.prototype.endsWith != 'function')
String.prototype.endsWith = (str)->
return this.slice(-str.length) == str
global.$driver.save = ->
state = serializer.serialize(global.$game)
now = new Date
year = now.getFullYear().toString()
month = now.getMonth().toString()
if(month.length == 1)
month = "0" + month
day = now.getDate().toString()
if(day.length == 1)
day = "0" + day
hour = now.getHours().toString()
if(hour.length == 1)
hour = "0" + hour
minute = now.getMinutes().toString()
if(minute.length == 1)
minute = "0" + minute
fs.writeFile 'checkpoints/checkpoint-' + year + "" + month + "" + day + "" + hour + "" + minute + '.json', state
return
global.$driver.broadcast = (message) ->
_(global.$driver.clients).each (client) ->
client.write message + '\n'
return
return
global.$driver.load = (filename) ->
if !filename
try
filename = _(fs.readdirSync('checkpoints')).chain().filter((name) ->
name.indexOf('checkpoint') > -1
).sort().reverse().first().value()
catch e
console.log e
return
if !filename
return
try
data = fs.readFileSync("checkpoints/" + filename)
catch e
console.log e
return
console.log 'Loading checkpoint from ' + filename + '...'
try
global.$game = serializer.unserialize(data.toString())
console.log 'Checkpoint loaded.'
catch e
console.log e
return
global.$driver.handleNewConnection = (socket) ->
global.$game.common.login.handleNewConnection(socket)
global.$driver.startDriver = ->
net = require('./telnet.js')
net.createServer((socket) ->
socket.do.window_size()
global.$driver.clients.push socket
socket.alive = true
socket.on 'end', ->
socket.alive = false
global.$driver.clients.splice global.$driver.clients.indexOf(socket), 1
delete(global.$driver.authenticatedUsers[socket.user]) if socket.user
global.$driver.handleNewConnection socket
).listen 5555
console.log 'Server listening at port 5555\n'
global.$driver.load()
global.$driver.startDriver()
global.$game?.common?.startGame() if global.$game?.common?.startGame
setInterval global.$driver.save, 1000 * 60 * 10
repl.start(
prompt: '> ',
input: process.stdin,
output: process.stdout,
useGlobal:true
).on 'exit', ->
socket.end();
stalker = watchr.open "./dist", (changeType,filePath,fileCurrentStat,filePreviousStat) ->
try
if filePath.endsWith("driver.js") or filePath.endsWith("loader.js") then return
console.log("Reloading " + filePath)
loader.loadSync("./" + filePath)
catch e
console.log e
, ->
global.wordwrap = require("wordwrap")
global.process.on 'uncaughtException', (err) ->
console.log(err, err.stack.split("\n"))
\ No newline at end of file
fs=require("fs")
vm = require("vm")
nodeEval = require("node-eval")
module.exports.testLoad = (name) ->
m = require('module')
sandbox = vm.createContext({})
statement = "require(\"" + name + "\")"
try
vm.runInContext(m.wrap(statement), sandbox)(exports, require, module, __filename, __dirname);
return true
catch e
console.log e
return false
module.exports.load = (name, callback) ->
module.exports.loadResource((err, resource)->
callback(nodeEval(resource))
)
module.exports.loadSync = (name) ->
nodeEval(module.exports.loadResourceSync(name))
module.exports.loadResourceSync = (name) ->
fs.readFileSync(name).toString()
module.exports.loadResource = (name, callback) ->
fs.readFile name, (err, data)->
callback err, data.toString()
\ No newline at end of file
require("./dist/user.js")
global.$game.$index.users = {} if not global.$game.$index.users
global.$game.common = {} if not global.$game.common
global.$game.common.login = {} if not global.$game.common.login
global.$game.common.login.handleNewConnection = (socket) ->
wrap = global.wordwrap
readline = require("readline")
width = 80
socket.on 'window size', (e) ->
if e.command == 'sb'
console.log 'telnet window resized to %d x %d', e.width, e.height
width = e.width
rl = readline.createInterface(socket, socket)
rl.question "Can you see the " + "colors? ".rainbow, (useColor) ->
rl.close()
if !useColor.toLowerCase().startsWith("n")
socket.tell = (str)->
str.split("\n").forEach (s)->
socket.write(wrap(width)(s) + "\n")
else
socket.tell = (str)->
str.split("\n").forEach (s)->
socket.write(wrap(width)(s.strip) + "\n")
global.$game.common.login.showWelcomeMessage socket, ->
global.$game.common.login.loginLoop(socket)
global.$game.common.login.loginLoop = (socket) ->
readline = require('readline')
_ = require("./node_modules/underscore")
rl = readline.createInterface(socket, socket)
loginPrompt = "Login> ";
passwordPrompt = "Password> ";
socket.tell("Please login with your user name, character name or email address.")
socket.tell("If you don't have a user, please type " + "register".underline.bold + " to create one.")
socket.tell("One account per person, please.".bold)
socket.tell("If you require any assistance please email " + "shinmojo@gmail.com".underline.bold + ".")
rl.question loginPrompt, (login)->
if(login == "register")
rl.close()
return global.$game.common.login.register socket, ->
global.$game.common.login.loginLoop(socket)
rl.question(passwordPrompt, (password) ->
rl.close()
user = _(global.$game.$index.users).find((user) ->
return user.name.toLowerCase() == login.toLowerCase() || user.email.toLowerCase() == login.toLowerCase()
)
if not user
user = _(global.$game.$index.players).find((player) ->
return player.name.toLowerCase() == login.toLowerCase()
)?.user
return setTimeout(->
socket.tell("No such user, player, email or bad password.")
global.$game.common.login.loginLoop(socket)
, 0) if not user
crypto = require "crypto"
hash = crypto.createHash "sha256"
hash.update password
hash.update user.salt + ""
if(user.password != hash.digest("hex"))
setTimeout(->
socket.tell("Unknown user or bad password.")
global.$game.common.login.loginLoop(socket)
, 0)
return
if not user.verified
global.$game.common.question socket, "Please enter your confirmation code: ", (check) ->
return "Invalid confirmation code." if check.toLowerCase() != user.confirmationCode.toLowerCase()
, (err, answer) ->
user.verified = true
socket.tell("Successfully authenticated as " + login + ". Welcome back!")
global.$driver.authenticatedUsers[user] = socket
socket.user = user
user.handleConnection(socket)
return
socket.tell("Successfully authenticated as " + login + ". Welcome back!")
global.$driver.authenticatedUsers[user] = socket
socket.user = user
user.lastLogin = new Date()
user.handleConnection(socket)
)
global.$game.common.login.showWelcomeMessage = (socket, callback) ->
loader = require("./dist/loader.js")
loader.loadResource "./txt/welcome.txt", (err, text)->
socket.write(text.red + "\r\n")
callback()
global.$game.common.login.register = (socket) ->
global.$game.common.login.getUserName socket, (username) ->
global.$game.common.login.getPassword socket, (password) ->
socket.tell("Great. Just one more thing. We need a valid email in case you ever lose your password. " + "We absolutely promise on a stack of Ono-Sendai Cyberspace 7's that we will only ever use it for VERY infrequent game related communication.".bold)
global.$game.common.question socket, "Please enter your email: ", (email) ->
if not global.$game.common.login.validateEmail(email) then return "Invalid email address."
, (err, validEmail) ->
socket.tell("Perfect! We've created a user for you with the user name " + username.bold + " and sent an email to " + validEmail.bold + " with your confirmation code.\n Now we need you to login with the username you just used, and type in the confirmation code from your email. If you run into any problems, please email shinmojo@gmail.com")
user = new global.$game.classes.User(username, validEmail, password, socket.remoteAddress)
code = global.$game.common.login.createConfirmationCode()
user.confirmationCode = code
user.verified = false
global.$game.common.login.sendEmail(username, validEmail, code)
global.$game.common.login.loginLoop(socket)
global.$game.common.login.createConfirmationCode = ->
x=Math.random().toString(36).substring(7).substr(0,5).toLowerCase()
while (x.length!=5)
x=Math.random().toString(36).substring(7).substr(0,5).toLowerCase()
return x
global.$game.common.login.sendEmail = (username, email, confirmationCode) ->
nodemailer = require('./node_modules/nodemailer');
transporter = nodemailer.createTransport
service: 'Gmail',
auth:
user: 'shinmojo',
pass: 'Zabbas4242!'
mailOptions =
from: 'ShinMojo@gmail.com',
to: email,
subject: 'Confirmation code for ' + username + " from Malice.",
text: 'Hello, ' + username + ". Here is your confirmation code: " + confirmationCode + "\nIf you didn't request this, then we apologize and please ignore this email."
transporter.sendMail mailOptions, (error, info) ->
if(error)
console.log(error)
else
console.log('Message sent: ' + info.response)
global.$game.common.login.getPassword = (socket, callback) ->
global.$game.common.question socket, "Please enter your password (8 characters minimum): ", (answer) ->
return "Password must be 8 or more characters." if answer.trim().length < 8
, (err, password)->
global.$game.common.question socket, "Please enter your password again: ", null, (err, again) ->
if(again != password)
socket.tell("Your passwords did not match. Try again.")
return setTimeout global.$game.common.login.getPassword socket, callback
callback(password)
global.$game.common.login.validateEmail = (email) ->
re = /\S+@\S+\.\S+/;
re.test(email)
global.$game.common.login.getUserName = (socket, callback) ->
global.$game.common.question socket, "What would you like your user name to be? ", (answer) ->
_ = require("./node_modules/underscore")
if(_(global.$game.$index.users).find (user) ->
user.name.toLowerCase() == answer
) then return "That user name is taken."
if(_(global.$game.$index.players).find (player) ->
player.name.toLowerCase() == answer
) then return "That user name is taken."
if answer.length < 3 then return "User names must be 3 or more characters."
if not /^[a-zA-Z0-9]*$/.test(answer) then return "User names cannot contain any non alphanumeric characters."
return false
, (err, answer) ->
callback(answer)
global.$game.common.login.repl = (socket) ->
repl = require("repl")
repl.start(
prompt: '> ',
input: socket,
output: socket,
useGlobal:true
).on 'exit', ->
socket.end()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment