~jameinel/+junk/ants-2011-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
package main

import (
	//	"io"
	"fmt"
	"os"
	"rand"
	"sort"
)

type MyBot struct {
	log *os.File
}

//NewBot creates a new instance of your bot
func NewBot(s *State) Bot {
	f, _ := os.Create(",,log.txt")
	mb := &MyBot{
		//do any necessary initialization here
		log: f,
	}
	if f != nil {
		fmt.Fprintf(f, "Initialize:\n%#v", s)
	}
	return mb
}

//DoTurn is where you should do your bot's actual work.
func (mb *MyBot) DoTurn(s *State) os.Error {
	if mb.log != nil {
		fmt.Fprintf(mb.log, "\n\nTurn %d\n", s.Turn)
	}
	dirs := []Direction{North, East, South, West}
	// First thing, move ants closer to visible food
	ants2food := FindAntsCloseToFood(s.Map, s.ViewRadius2, nil)
	if len(ants2food) == 0 {
		fmt.Fprintf(mb.log, "No ant food paths found for %d visible food\n%s",
			len(s.Map.Food), s.Map)
	}
	sort.Sort(ants2food)
	for _, a2f := range ants2food {
		if _, present := s.Map.Ants[a2f.Ant]; !present {
			// Ant already assigned something else
			ar, ac := s.Map.FromLocation(a2f.Ant)
			fr, fc := s.Map.FromLocation(a2f.Food)
			fmt.Fprintf(mb.log, "ant @ (%d, %d) ignoring food at (%d, %d) dist %d\n",
				ar, ac, fr, fc, a2f.Distance)
			continue
		}
		d := s.Map.DirectionFromLocations(a2f.Ant, a2f.Step)
		if mb.log != nil {
			ar, ac := s.Map.FromLocation(a2f.Ant)
			fr, fc := s.Map.FromLocation(a2f.Food)
			fmt.Fprintf(mb.log, "ant @ (%d, %d) moving %s for food at (%d, %d) dist %d\n",
				ar, ac, d, fr, fc, a2f.Distance)
		}
		if d != IllegalMovement && s.Map.SafeDestination(a2f.Step) {
			s.IssueOrderLoc(a2f.Ant, d)
			s.Map.Ants[a2f.Ant] = 0, false
		} else if mb.log != nil {
			fmt.Fprintf(mb.log, "%s not a safe move", d)
		}
	}
	for loc, ant := range s.Map.Ants {
		if ant != MY_ANT {
			continue
		}

		//try each direction in a random order
		p := rand.Perm(4)
		for _, i := range p {
			d := dirs[i]

			loc2 := s.Map.Move(loc, d)
			if s.Map.SafeDestination(loc2) {
				s.IssueOrderLoc(loc, d)
				//there's also an s.IssueOrderRowCol if you don't have a Location handy
				break
			}
		}
	}
	//returning an error will halt the whole program!
	return nil
}