-
Notifications
You must be signed in to change notification settings - Fork 0
/
robo_script.go
507 lines (445 loc) · 13.3 KB
/
robo_script.go
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package main
import (
"fmt"
"strconv"
"strings"
"unicode"
)
type ResultType uint8
const (
ResultAction ResultType = iota
ResultError
ResultInt
)
// Let's just use crappy pseudo-unions for now. Not memory-efficient, but simple.
type Result struct {
Type ResultType
Action Action
Err error
Int int
}
var ResultTrue = Result{Type: ResultInt, Int: 1}
var ResultFalse = Result{Type: ResultInt, Int: 0}
type NodeType uint8
const (
Expr NodeType = iota
FuncName
Int
)
type ScriptNode struct {
Children []*ScriptNode
Type NodeType
Func Function
N int
}
type Script struct {
Code *ScriptNode
State *GameState
}
// If the script returns a number instead of performing an action, just wait.
func (s *Script) Run() Result {
result := s.Eval(s.Code)
if result.Type != ResultAction {
result.Type = ResultAction
result.Action = Action{Type: ActionWait}
}
return result
}
func ParseScript(code string) *ScriptNode {
node, _, err := readToken(code)
if err != nil {
logger.Fatalf("Parse error! %v", err)
}
return node
}
// Counts the number of expressions in a ScriptNode tree.
func (node *ScriptNode) Size() int {
if node.Type == Expr {
i := 0
for _, child := range node.Children {
i += child.Size()
}
return i
} else {
return 1
}
}
// It's quick! It's dirty! It's a Lisp parser in ~60 lines!
func readToken(code string) (*ScriptNode, string, error) {
var err error
code = strings.TrimSpace(code)
node := ScriptNode{ Children: make([]*ScriptNode, 0) }
if code[0] == '(' {
code = code[1:]
node.Type = Expr
for {
var child *ScriptNode
child, code, err = readToken(code)
if err != nil {
return nil, code, err
} else if child == nil {
break
} else if len(code) == 0 {
return nil, code, fmt.Errorf("Unterminated expression!")
}
node.Children = append(node.Children, child)
}
if len(node.Children) == 0 {
return nil, code, fmt.Errorf("Found an empty list!")
}
if node.Children[0].Type != FuncName {
return nil, code, fmt.Errorf("Non-symbol in function position! Type %v", node.Children[0].Type)
}
for _, child := range node.Children[1:] {
if child.Type == FuncName {
return nil, code, fmt.Errorf("Symbol '%s' passed as function argument!", child.Func.Name)
}
}
if len(node.Children) != 1 + node.Children[0].Func.Arity {
return nil, code, fmt.Errorf("Wrong number of arguments to '%s': got %d, expected %d",
node.Children[0].Func.Name, len(node.Children) - 1, node.Children[0].Func.Arity)
}
} else if code[0] == ')' {
return nil, code[1:], nil
} else if unicode.IsDigit(rune(code[0])) {
s := string(code[0])
for i := 1; i < len(code) - 1 && code[i] != ')' && unicode.IsDigit(rune(code[i])); i++ {
s += string(code[i])
}
var err error
node.Type = Int
node.N, err = strconv.Atoi(s)
if err != nil {
return nil, code, fmt.Errorf("Couldn't convert int string to int: '%s', %v", s, err)
}
return &node, code[len(s):], nil
} else if !unicode.IsSpace(rune(code[0])) {
s := string(code[0])
for i := 1; i < len(code) - 1 && code[i] != ')' && !unicode.IsSpace(rune(code[i])); i++ {
s += string(code[i])
}
node.Type = FuncName
node.Func, err = ResolveFunction(s)
if err != nil {
return nil, code, err
}
return &node, code[len(s):], nil
}
return &node, code, nil
}
func (s *Script) Eval(node *ScriptNode) Result {
switch node.Type {
case Int:
return Result{Type: ResultInt, Int: node.N}
case Expr:
function := node.Children[0].Func
return function.Code(s, node.Children[1:])
case FuncName:
logger.Fatalf("Tried to evaluate a symbol! '%s'", node.Func.Name)
}
return Result{}
}
// Functions
type Function struct {
Name string
Arity int
Code func(s *Script, args []*ScriptNode) Result
}
// Can't use map literal syntax here or we get into recursive initialization.
var FunctionLookupTable = make(map[string]Function)
var AllFunctions []Function
func InitScript() {
// Base functionality
FunctionLookupTable["+"] = Function{"+", 2, RS_Add}
FunctionLookupTable["-"] = Function{"-", 2, RS_Subtract}
FunctionLookupTable["*"] = Function{"*", 2, RS_Multiply}
FunctionLookupTable["/"] = Function{"/", 2, RS_Divide}
FunctionLookupTable["mod"] = Function{"mod", 2, RS_Modulus}
FunctionLookupTable["<"] = Function{"<", 2, RS_LessThan}
FunctionLookupTable[">"] = Function{">", 2, RS_GreaterThan}
FunctionLookupTable["="] = Function{"=", 2, RS_Equal}
FunctionLookupTable["if"] = Function{"if", 3, RS_If}
FunctionLookupTable["and"] = Function{"and", 2, RS_And}
FunctionLookupTable["or"] = Function{"or", 2, RS_Or}
FunctionLookupTable["not"] = Function{"not", 1, RS_Not}
// Actions
FunctionLookupTable["move"] = Function{"move", 1, RS_Move}
// Commenting this out for a bit to see if it improves fitness.
// FunctionLookupTable["wait"] = Function{"wait", 0, RS_Wait}
FunctionLookupTable["shoot"] = Function{"shoot", 1, RS_Shoot}
FunctionLookupTable["shoot-nearest"] = Function{"shoot-nearest", 0, RS_ShootNearest}
// Predicates
FunctionLookupTable["can-move?"] = Function{"can-move?", 1, RS_CanMove}
FunctionLookupTable["enemy-visible?"] = Function{"enemy-visible?", 0, RS_EnemyVisible}
FunctionLookupTable["ally-visible?"] = Function{"ally-visible?", 0, RS_AllyVisible}
FunctionLookupTable["enemy-goal-visible?"] = Function{"enemy-goal-visible?", 0, RS_EnemyGoalVisible}
FunctionLookupTable["own-goal-visible?"] = Function{"own-goal-visible?", 0, RS_OwnGoalVisible}
// Miscellaneous
FunctionLookupTable["tick"] = Function{"tick", 0, RS_Tick}
FunctionLookupTable["visible-enemies-count"] = Function{"visible-enemies-count", 0, RS_VisibleEnemiesCount}
FunctionLookupTable["visible-allies-count"] = Function{"visible-allies-count", 0, RS_VisibleAlliesCount}
FunctionLookupTable["my-x-pos"] = Function{"my-x-pos", 0, RS_MyXPos}
FunctionLookupTable["my-y-pos"] = Function{"my-y-pos", 0, RS_MyYPos}
for _, v := range FunctionLookupTable {
AllFunctions = append(AllFunctions, v)
}
}
func ResolveFunction(name string) (Function, error) {
function, found := FunctionLookupTable[name]
if !found {
return Function{}, fmt.Errorf("No such function: '%s'", name)
}
return function, nil
}
// "Functions" is a poor choice of name, since the functions are responsible for evaluating their own arguments.
// It's more like a language that has only special forms.
func RS_Add(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
result1.Int += result2.Int
return result1
}
func RS_Subtract(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
result1.Int -= result2.Int
return result1
}
func RS_Multiply(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
result1.Int *= result2.Int
return result1
}
// If we try to divide by zero, we just return zero instead of causing an error.
func RS_Divide(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt || result2.Int == 0 {
return result2
}
result1.Int /= result2.Int
return result1
}
func RS_Modulus(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt || result2.Int == 0 {
return result2
}
result1.Int %= result2.Int
return result1
}
func RS_LessThan(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
if result1.Int < result2.Int {
return ResultTrue
} else {
return ResultFalse
}
}
func RS_GreaterThan(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
if result1.Int > result2.Int {
return ResultTrue
} else {
return ResultFalse
}
}
func RS_Equal(s *Script, args []*ScriptNode) Result {
result1 := s.Eval(args[0])
if result1.Type != ResultInt {
return result1
}
result2 := s.Eval(args[1])
if result2.Type != ResultInt {
return result2
}
if result1.Int == result2.Int {
return ResultTrue
} else {
return ResultFalse
}
}
func RS_If(s *Script, args []*ScriptNode) Result {
condition := s.Eval(args[0])
if condition.Type != ResultInt {
return condition
}
if condition.Int > 0 {
return s.Eval(args[1])
} else {
return s.Eval(args[2])
}
}
func RS_And(s *Script, args []*ScriptNode) Result {
var condition Result = ResultFalse
for _, arg := range args {
condition = s.Eval(arg)
if condition.Type != ResultInt {
return condition
}
if condition.Int == 0 {
return ResultFalse
}
}
return condition
}
func RS_Or(s *Script, args []*ScriptNode) Result {
for _, arg := range args {
condition := s.Eval(arg)
if condition.Type != ResultInt || condition.Int > 0 {
return condition
}
}
return ResultFalse
}
func RS_Not(s *Script, args []*ScriptNode) Result {
condition := s.Eval(args[0])
if condition.Int > 0 {
return ResultFalse
} else {
return ResultTrue
}
}
func RS_Move(s *Script, args []*ScriptNode) Result {
direction := s.Eval(args[0])
if direction.Type != ResultInt {
return direction
}
dir := relativeToAbsoluteDirection(Direction(direction.Int % int(NumberOfDirections)), s.State.CurrentTeam())
destination := s.State.Arena.DestinationCellAfterMove(s.State.CurrentBot.Position, dir)
return Result{Type: ResultAction, Action: Action{Type: ActionMove, Target: destination}}
}
func RS_CanMove(s *Script, args []*ScriptNode) Result {
direction := s.Eval(args[0])
if direction.Type != ResultInt {
return direction
}
dir := relativeToAbsoluteDirection(Direction(direction.Int % int(NumberOfDirections)), s.State.CurrentTeam())
destination := s.State.Arena.DestinationCellAfterMove(s.State.CurrentBot.Position, dir)
if s.State.CellIsEmpty(destination) {
return ResultTrue
} else {
return ResultFalse
}
}
func RS_Wait(s *Script, args []*ScriptNode) Result {
return Result{Type: ResultAction, Action: Action{Type: ActionWait}}
}
func RS_Shoot(s *Script, args []*ScriptNode) Result {
direction := s.Eval(args[0])
if direction.Type != ResultInt {
return direction
}
dir := relativeToAbsoluteDirection(Direction(direction.Int % int(NumberOfDirections)), s.State.CurrentTeam())
pos := s.State.CurrentBot.Position
var target *Cell
switch dir {
case North: target = &s.State.Arena.Cells[pos.X * s.State.Arena.Height]
case South: target = &s.State.Arena.Cells[pos.X * s.State.Arena.Height + s.State.Arena.Height - 1]
case East: target = &s.State.Arena.Cells[(s.State.Arena.Width - 1) * s.State.Arena.Height + pos.Y]
case West: target = &s.State.Arena.Cells[pos.Y]
}
return Result{Type: ResultAction, Action: Action{Type: ActionShoot, Target: target}}
}
func RS_ShootNearest(s *Script, args []*ScriptNode) Result {
nearestTarget := s.State.NearestVisibleEnemyOrGoal()
if nearestTarget == nil {
return Result{Type: ResultAction, Action: Action{Type: ActionWait}}
}
action := Action{Type: ActionShoot, Target: nearestTarget}
return Result{Type: ResultAction, Action: action}
}
func RS_Tick(s *Script, args []*ScriptNode) Result {
return Result{Type: ResultInt, Int: s.State.Tick}
}
func RS_EnemyVisible(s *Script, args []*ScriptNode) Result {
if s.State.CountVisibleEnemiesAndGoals() > 0 { // This could be optimized to short-circuit if necessary.
return ResultTrue
} else {
return ResultFalse
}
}
func RS_AllyVisible(s *Script, args []*ScriptNode) Result {
if s.State.CountVisibleAlliesAndGoals() > 0 { // This could be optimized to short-circuit if necessary.
return ResultTrue
} else {
return ResultFalse
}
}
func RS_VisibleEnemiesCount(s *Script, args []*ScriptNode) Result {
return Result{Type: ResultInt, Int: s.State.CountVisibleEnemiesAndGoals()}
}
func RS_VisibleAlliesCount(s *Script, args []*ScriptNode) Result {
return Result{Type: ResultInt, Int: s.State.CountVisibleAlliesAndGoals()}
}
func RS_EnemyGoalVisible(s *Script, args []*ScriptNode) Result {
if s.State.GoalVisible(s.State.OpposingTeam()) {
return ResultTrue
} else {
return ResultFalse
}
}
func RS_OwnGoalVisible(s *Script, args []*ScriptNode) Result {
if s.State.GoalVisible(s.State.CurrentTeam()) {
return ResultTrue
} else {
return ResultFalse
}
}
// We have to rotate it 90 degrees so that X increasing is consistently east and Y increasing is consistently south, no matter which team you're on. (Yes, it's confusing. Imagine it from the perspective of the bot, looking towards the enemy goal.)
func RS_MyXPos(s *Script, args []*ScriptNode) Result {
pos := s.State.CurrentBot.Position.Y
if s.State.CurrentTeam() == TeamA {
return Result{Type: ResultInt, Int: pos}
} else {
return Result{Type: ResultInt, Int: s.State.Arena.Height - pos}
}
}
func RS_MyYPos(s *Script, args []*ScriptNode) Result {
pos := s.State.CurrentBot.Position.X
if s.State.CurrentTeam() == TeamA {
return Result{Type: ResultInt, Int: pos}
} else {
return Result{Type: ResultInt, Int: s.State.Arena.Width - pos}
}
}