-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinit.js
105 lines (86 loc) · 2.42 KB
/
init.js
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
var model = require('./model')
var api = require('./logic')
var vm = require('vm')
var inspect = require('util').inspect
var idle = require('idle')
var net = require('net')
setInterval(function () {
//don't remove this, this is how the server knows that
//this process is still alive (not inifinte looping)
process.stdout.write(' ') //heartbeat
}, 500)
var stream = net.connect(66666)
stream.pipe(model.createStream()).pipe(stream)
model.on('create', function (row) {
//on the first update, set api stuff...
row.api = api(row)
row.once('update', function () {
// console.log('create', row.toJSON())
// console.log(row)
var timer
var _fn
row.on('change', function (ch) {
var res
if((ch.source || ch.cast) && row.state.run !== false) {
clearTimeout(timer)
console.log(ch, row.id)
timer = setTimeout(function () {
if(row.state.run === false) return
console.log('\n'+JSON.stringify([ 'start', row.id ]))
try {
res = vm.runInNewContext(ch.source || ch.cast, {
self : row.api
})
} catch (err) {
row.set('error', String(err))
console.log('\n'+JSON.stringify([ 'error', row.id, String(err) ]))
return
}
console.log('\n'+JSON.stringify([ 'end', row.id ]))
try {
row.set('result', inspect(res))
}
catch (e) { row.set('error', String(e)) }
}, 100)
}
})
if(row.get('type') === 'monster') {
row.set("source", string(init))
} else if (row.get("type") === "tree") {
row.set("source", string(tree))
} else if (row.get("type") === "rock") {
row.set("source", string(rock))
}
})
})
function tree() {
// I am a tree
}
function rock() {
// I am a rock
}
//this function is eval'd (the user will enter it as text...)
/*global self*/
//remove indentation, so that it displays property in the text editor
function init () {
self.say('hello')
self.think(function () {
function r () {
return (Math.random()*2 - 1)
}
var x = r(), y = r()
var l = Math.sqrt(x*x + y*y)
x = x / l; y = y / l
self.move(x*10, y*10)
if(Math.random() < 0.1)
self.say('woof')
})
//if another monster speaks nearby...
self.hear(function (words, id) {
//...
})
}
function string(code) {
code = code.toString()
return code.substring(code.indexOf('{') + 1, code.length - 2)
}