-
Notifications
You must be signed in to change notification settings - Fork 30
/
base-robot.ls
137 lines (111 loc) · 2.84 KB
/
base-robot.ls
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
importScripts('../log.js')
class BaseRobot
me: {id: 0, x: 0, y: 0, hp: 0}
#enemy-robots: []
enemy-spot: []
(@name = "base-robot") ->
@event_counter = 0
@callbacks = {}
self.onmessage = (e) ~>
@receive(e.data)
#@_run()
move_forwards: (distance, callback = null) !->
@send({
"action": "move_forwards",
"amount": distance
}, callback)
move_backwards: (distance, callback = null) !->
@send({
"action": "move_backwards",
"amount": distance
}, callback)
move_opposide: (distance, callback = null) !->
@send({
"action": "move_opposide",
"amount": distance
}, callback)
turn_left: (angle, callback = null) !->
@send({
"action": "turn_left",
"amount": angle
}, callback)
turn_right: (angle, callback = null) !->
@send({
"action": "turn_right",
"amount": angle
}, callback)
turn_turret_left: (angle, callback = null) !->
@send({
"action": "turn_turret_left"
"amount": angle
})
turn_turret_right: (angle, callback = null) !->
@send({
"action": "turn_turret_right"
"amount": angle
})
shoot: !->
@send({
"action": "shoot"
})
yell: (msg) !->
@send({
"action": "yell",
"msg": msg
})
receive: (msg) !->
msg_obj = JSON.parse(msg)
if msg_obj.me
@me = msg_obj.me
switch msg_obj["action"]
#the first run
when "run"
@_run!
#When finished an action
when "callback"
logger.log \callback
logger.log @event_counter
# XXX deprecated
if typeof @callbacks[msg_obj["event_id"]] is "function"
@callbacks[msg_obj["event_id"]]()
@event_counter--
if @event_counter == 0
@_run!
when "interruption"
logger.log \interruption
logger.log @event_counter
# TODO the bot need to know its current position
# clean all the event
@event_counter = 0
if msg_obj["status"].wall-collide
@onWallCollide!
if msg_obj["status"].is-hit
@onHit!
console.log \onhit-and-run
@_run!
when "enemy-spot"
logger.log \enemy-spot
@enemy-spot = msg_obj["enemy-spot"]
# clean events
#@event_counter = 0
@onEnemySpot!
#@_run!
_run: !->
logger.log @event_counter
console.log \run
setTimeout(~>
@onIdle!
, 0)
onIdle: !->
throw "You need to implement the onIdle() method"
onWallCollide: !->
throw "You need to implement the onWallCollide() method"
onHit: !->
onEnemySpot: !->
send: (msg_obj, callback) !->
logger.log \send + " " + msg_obj.action
event_id = @event_counter++
@callbacks[event_id] = callback
msg_obj["event_id"] = event_id
postMessage(JSON.stringify(msg_obj))
@BaseRobot = BaseRobot