-
Notifications
You must be signed in to change notification settings - Fork 0
/
Turn.rb
146 lines (102 loc) · 2.19 KB
/
Turn.rb
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
class Turn
MAX_HISTORY = 10
CRITICAL_MARGIN = 2
public
def initialize turntime, stdout
@turntime = 1.0*(turntime - AntConfig::TURN_MARGIN)/1000
@stdout = stdout
@open = false
@history = []
@last_go = Timer.now
# First time send
@stdout.puts 'go'
@stdout.flush
end
def maxed_out? max = nil
max = MAX_HISTORY - 3 if max.nil?
history >= max
end
def maxed_urgent?
history >= CRITICAL_MARGIN
end
def check_time_limit
diff = Timer.now - @start
if diff >= @turnlimit
$logger.turn(true) { "Hit time limit" }
throw :maxed_out
end
end
def check_maxed_out
unless @open
$logger.turn "throwing :maxed_out"
throw :maxed_out
else
diff = Timer.now - @start
if diff >= @turnlimit
$logger.turn(true) { "Maxed out!" }
go @turn, 1
throw :maxed_out
end
end
end
def go turn, maxed_out = 0
$logger.turn(true) { "sending for turn #{ turn }" }
unless @open
$logger.turn(true) { "Nothing to send!" }
else
@stdout.puts "go"
@stdout.flush
@last_go = Timer.now
@open = false
add_history maxed_out
end
end
def start turn, diff_gets_d
start = Timer.now
diff = 0.0
diff = ((start - @start)*1000).to_i unless @start.nil?
@start = start
diff_go = start - @last_go
diff_go_d = (diff_go*1000).to_i
diff_gets = 1.0*diff_gets_d/1000
diff_start_d = ( (start - $logger.start)*1000).to_i
@turnlimit = @turntime - diff_go + diff_gets
turnlimit_d = (@turnlimit*1000).to_i
$logger.turn(true) { "start #{ diff_start_d } turn: #{ turn } " +
"limit/go/gets = #{ turnlimit_d }/#{ diff_go_d }/#{ diff_gets_d } " +
" - maxout #{ hist_to_s }; last call #{ diff }" }
@turn = turn
@open = true
end
def send str
ret = true
if @open
$logger.turn(true) { "output open." }
@stdout.puts str
@stdout.flush
else
$logger.turn(true) { "output closed!" }
throw :maxed_out
ret = false
end
ret
end
def open?
@open
end
private
def add_history val
@history << val
if @history.length > MAX_HISTORY
@history = @history[1..-1]
end
end
def history
sum = 0
@history.each { |h| sum += h }
sum
end
def hist_to_s
"#{ history }/#{ @history.length }"
end
end