-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNaiveAgent.java
299 lines (256 loc) · 8.96 KB
/
NaiveAgent.java
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
/*****************************************************************************
** ANGRYBIRDS AI AGENT FRAMEWORK
** Copyright (c) 2014, XiaoYu (Gary) Ge, Stephen Gould, Jochen Renz
** Sahan Abeyasinghe,Jim Keys, Andrew Wang, Peng Zhang
** All rights reserved.
**This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
**To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
*or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*****************************************************************************/
package ab.demo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import ab.demo.other.ActionRobot;
import ab.demo.other.Shot;
import ab.planner.TrajectoryPlanner;
import ab.utils.StateUtil;
import ab.vision.ABObject;
import ab.vision.GameStateExtractor.GameState;
import ab.vision.Vision;
import ab.vision.VisionMBR;
public class NaiveAgent implements Runnable {
private ActionRobot aRobot;
private Random randomGenerator;
public int currentLevel = 1;
public static int time_limit = 12;
private Map<Integer,Integer> scores = new LinkedHashMap<Integer,Integer>();
TrajectoryPlanner tp;
private boolean firstShot;
private Point prevTarget;
// a standalone implementation of the Naive Agent
public NaiveAgent() {
aRobot = new ActionRobot();
tp = new TrajectoryPlanner();
prevTarget = null;
firstShot = true;
randomGenerator = new Random();
// --- go to the Poached Eggs episode level selection page ---
ActionRobot.GoFromMainMenuToLevelSelection();
}
// run the client
public void run() {
aRobot.loadLevel(currentLevel);
while (true) {
GameState state = solve();
if (state == GameState.WON) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int score = StateUtil.getScore(ActionRobot.proxy);
if(!scores.containsKey(currentLevel))
scores.put(currentLevel, score);
else
{
if(scores.get(currentLevel) < score)
scores.put(currentLevel, score);
}
int totalScore = 0;
for(Integer key: scores.keySet()){
totalScore += scores.get(key);
System.out.println(" Level " + key
+ " Score: " + scores.get(key) + " ");
}
System.out.println("Total Score: " + totalScore);
aRobot.loadLevel(++currentLevel);
// make a new trajectory planner whenever a new level is entered
tp = new TrajectoryPlanner();
// first shot on this level, try high shot first
firstShot = true;
} else if (state == GameState.LOST) {
System.out.println("Restart");
aRobot.restartLevel();
} else if (state == GameState.LEVEL_SELECTION) {
System.out
.println("Unexpected level selection page, go to the last current level : "
+ currentLevel);
aRobot.loadLevel(currentLevel);
} else if (state == GameState.MAIN_MENU) {
System.out
.println("Unexpected main menu page, go to the last current level : "
+ currentLevel);
ActionRobot.GoFromMainMenuToLevelSelection();
aRobot.loadLevel(currentLevel);
} else if (state == GameState.EPISODE_MENU) {
System.out
.println("Unexpected episode menu page, go to the last current level : "
+ currentLevel);
ActionRobot.GoFromMainMenuToLevelSelection();
aRobot.loadLevel(currentLevel);
}
}
}
private double distance(Point p1, Point p2) {
return Math
.sqrt((double) ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y)
* (p1.y - p2.y)));
}
public GameState solve()
{
// capture Image
BufferedImage screenshot = ActionRobot.doScreenShot();
// process image
Vision vision = new Vision(screenshot);
// find the slingshot
Rectangle sling = vision.findSlingshotMBR();
// confirm the slingshot
while (sling == null && aRobot.getState() == GameState.PLAYING) {
System.out
.println("No slingshot detected. Please remove pop up or zoom out");
ActionRobot.fullyZoomOut();
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
sling = vision.findSlingshotMBR();
}
// get all the pigs
List<ABObject> pigs = vision.findPigsMBR();
visualRecognition(screenshot);
GameState state = aRobot.getState();
// if there is a sling, then play, otherwise just skip.
if (sling != null) {
if (!pigs.isEmpty()) {
Point releasePoint = null;
Shot shot = new Shot();
int dx,dy;
{
// random pick up a pig
ABObject pig = pigs.get(randomGenerator.nextInt(pigs.size()));
Point _tpt = pig.getCenter();// if the target is very close to before, randomly choose a
// point near it
if (prevTarget != null && distance(prevTarget, _tpt) < 10) {
double _angle = randomGenerator.nextDouble() * Math.PI * 2;
_tpt.x = _tpt.x + (int) (Math.cos(_angle) * 10);
_tpt.y = _tpt.y + (int) (Math.sin(_angle) * 10);
System.out.println("Randomly changing to " + _tpt);
}
prevTarget = new Point(_tpt.x, _tpt.y);
// estimate the trajectory
ArrayList<Point> pts = tp.estimateLaunchPoint(sling, _tpt);
// do a high shot when entering a level to find an accurate velocity
if (firstShot && pts.size() > 1)
{
releasePoint = pts.get(1);
}
else if (pts.size() == 1)
releasePoint = pts.get(0);
else if (pts.size() == 2)
{
// randomly choose between the trajectories, with a 1 in
// 6 chance of choosing the high one
if (randomGenerator.nextInt(6) == 0)
releasePoint = pts.get(1);
else
releasePoint = pts.get(0);
}
else
if(pts.isEmpty())
{
System.out.println("No release point found for the target");
System.out.println("Try a shot with 45 degree");
releasePoint = tp.findReleasePoint(sling, Math.PI/4);
}
// Get the reference point
Point refPoint = tp.getReferencePoint(sling);
//Calculate the tapping time according the bird type
if (releasePoint != null) {
double releaseAngle = tp.getReleaseAngle(sling,
releasePoint);
System.out.println("Release Point: " + releasePoint);
System.out.println("Release Angle: "
+ Math.toDegrees(releaseAngle));
int tapInterval = 0;
switch (aRobot.getBirdTypeOnSling())
{
case RedBird:
tapInterval = 0; break; // start of trajectory
case YellowBird:
tapInterval = 65 + randomGenerator.nextInt(25);break; // 65-90% of the way
case WhiteBird:
tapInterval = 70 + randomGenerator.nextInt(20);break; // 70-90% of the way
case BlackBird:
tapInterval = 70 + randomGenerator.nextInt(20);break; // 70-90% of the way
case BlueBird:
tapInterval = 65 + randomGenerator.nextInt(20);break; // 65-85% of the way
default:
tapInterval = 60;
}
int tapTime = tp.getTapTime(sling, releasePoint, _tpt, tapInterval);
dx = (int)releasePoint.getX() - refPoint.x;
dy = (int)releasePoint.getY() - refPoint.y;
shot = new Shot(refPoint.x, refPoint.y, dx, dy, 0, tapTime);
}
else
{
System.err.println("No Release Point Found");
return state;
}
}
// check whether the slingshot is changed. the change of the slingshot indicates a change in the scale.
{
ActionRobot.fullyZoomOut();
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
Rectangle _sling = vision.findSlingshotMBR();
if(_sling != null)
{
double scale_diff = Math.pow((sling.width - _sling.width),2) + Math.pow((sling.height - _sling.height),2);
if(scale_diff < 25)
{
if(dx < 0)
{
aRobot.cshoot(shot);
state = aRobot.getState();
if ( state == GameState.PLAYING )
{
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
List<Point> traj = vision.findTrajPoints();
tp.adjustTrajectory(traj, sling, releasePoint);
firstShot = false;
}
}
}
else
System.out.println("Scale is changed, can not execute the shot, will re-segement the image");
}
else
System.out.println("no sling detected, can not execute the shot, will re-segement the image");
}
}
}
return state;
}
public static void main(String args[]) {
NaiveAgent na = new NaiveAgent();
if (args.length > 0)
na.currentLevel = Integer.parseInt(args[0]);
na.run();
}
public static void visualRecognition(BufferedImage screenshot){
VisionMBR vb=new VisionMBR(screenshot);
List<ABObject> bl=vb.findBlocks();
for(int i=0;i<bl.size();i++){
ABObject obj=bl.get(i);
System.out.println("Type="+obj.getType());
System.out.println("Number="+obj.id);
System.out.println("Shape="+obj.shape);
}
}
}