Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

271
LINES

< > BotCompany Repo | #1009151 // AI Game 7.1 Include [dev.]

JavaX fragment (include)

1  
///////////////////////////
2  
// Your API to work with //
3  
///////////////////////////
4  
5  
sinterface GameForAI {
6  
  int round(); // starting from 1
7  
  double submit(Submission data); // returns score (0-100)
8  
}
9  
10  
abstract sclass AI {
11  
  // stuff you get
12  
  
13  
  GameForAI game;
14  
  RGBImage image;
15  
  bool visualize = true;
16  
  
17  
  RGBImage image() { ret image; }
18  
  int w() { ret image.w(); }
19  
  int h() { ret image.h(); }
20  
  int round() { ret game.round(); }
21  
  double submit(Submission data) { ret game.submit(data); }
22  
  <A extends AI> A initSubAI(A ai) { setOptAll(ai, +game, +image); ret ai; }
23  
24  
  // implement this method and call submit()
25  
  abstract void go();
26  
  
27  
  void done() {}
28  
}
29  
30  
///////////////
31  
// Main Game //
32  
///////////////
33  
34  
static int rounds = 10000;
35  
static double targetScore = 99.0; // stop when this score is reached
36  
static int fps = 50;
37  
sS newImageText = "New Image";
38  
sS instruction = "Reproduce this image:";
39  
sS aiTitle = "AI";
40  
sbool showConsoleOnError;
41  
42  
static int w, h;
43  
static new UserGame userGame;
44  
static int halfTime;
45  
static ImageSurface is, isUser, isRepro;
46  
static RGBImage img; // the main image
47  
static double[][] integralImage;
48  
static new HashMap<Rect, Int> words;
49  
static L<Rect> solution;
50  
volatile sbool aiMode;
51  
static JLabel lblScore, lblTiming, lblInstruction;
52  
static new HashMap<Class, AI> ais;
53  
static S winner;
54  
static JCheckBox keepRunning;
55  
56  
svoid pGame {
57  
  substance();
58  
  swing {
59  
    thread { loadBinarySnippet(#1004373); } // preload applause animation
60  
    lblInstruction = jcenteredBoldLabel(instruction);
61  
    lblScore = jcenteredBoldLabel();
62  
    nextImage();
63  
    addToWindowTop(is, withMargin(lblInstruction));
64  
    addToWindow(is, withMargin(lblScore));
65  
    for (final Class c : myNonAbstractClassesImplementing(AI)) {
66  
      final S name = shortClassName(c);
67  
      final JButton btn = jbutton(name);
68  
      final Runnable go = r {
69  
        if (aiMode) ret;
70  
        setText(btn, name + " Running...");
71  
        final Runnable again = this;
72  
        thread {
73  
          Game game = testAI(c, voidfunc(Game game) {
74  
            if (!(game.step >= rounds || (game.step % 10) == 0)) ret;
75  
            S text = name + " scored " + formatScore(game.score) + " in " + n(game.step, "round");
76  
            if (game.error != null)
77  
              text += " - ERROR: " + game.error;
78  
            setText_noWait_sync(btn, text);
79  
          });
80  
          if (isChecked(keepRunning)) again.run();
81  
        }
82  
      };
83  
      onClick(btn, r { if (aiMode) setChecked(keepRunning, false); else go.run(); });
84  
      addToWindow(is, withMargin(btn));
85  
    }
86  
    addToWindow(is, lblTiming = jCenteredLabel(;
87  
    titlePopupMenuItem(is, "Show Winner Code", f showWinnerCode);
88  
    titlePopupMenuItem(is, "Restart AIs", r { restartAIs() });
89  
    addToWindow(is, withMargin(jRightAlignedLine(keepRunning = jcheckbox("Keep AI Running", true))));
90  
    addToWindow(is, withMargin(jbutton("Restart AIs", r { clearMapWithCleanUp(ais); })));
91  
    addToWindow(is, withMargin(jbutton(newImageText, r {
92  
      nextImage();
93  
      if (aiMode) showTheImage();
94  
      restartAIs();
95  
    })));
96  
97  
    packFrame(is);
98  
    setFrameWidth(is, 400);
99  
    centerTopFrame(is);
100  
    //hideConsole();
101  
  }
102  
}
103  
104  
svoid nextImage {
105  
  img = makeImage();
106  
  w = img.w();
107  
  h = img.h();
108  
  integralImage = integralImage(img);
109  
  if (aiMode) ret; // occasional updates only when AI is running
110  
  showTheImage();
111  
}
112  
113  
svoid showTheImage {
114  
  bool first = is == null;
115  
  is = showZoomedImage_centered(is, img, 1);
116  
    
117  
  if (first) {
118  
    disableImageSurfaceSelector(is);
119  
    
120  
    isUser = new ImageSurface(newBufferedImage(w, h, Color.white));
121  
    JComponent form = makeTheForm(userGame);
122  
    
123  
    if (form != null) {
124  
      addToWindow(is, withTitle("Your Reproduction:", jscroll_centered(isUser)));
125  
      addToWindow(is, form);
126  
    }
127  
    
128  
    // animate if idle
129  
    /*awtEvery(is, 1000, r {
130  
      if (!aiMode && isInForeground(is) && !mouseInFrame(is))
131  
        nextImage();
132  
    });*/
133  
    
134  
    // show current image occasionally when AI is running
135  
    /*awtEvery(is, 1000/fps, r {
136  
      if (aiMode) showTheImage();
137  
    });*/
138  
  }
139  
}
140  
141  
// AI stuff
142  
143  
sclass Game implements GameForAI {
144  
  int step;
145  
  new Best<Submission> best;
146  
  double score;
147  
  Submission submitted; // what was submitted in this round
148  
  Throwable error;
149  
  
150  
  public int round() { ret step; }
151  
  
152  
  public double submit(Submission data) {
153  
    if (data == null) ret 0;
154  
    if (submitted != null) fail("No multi-submit please");
155  
    submitted = data;
156  
    double score = scoreSubmission(data);
157  
    //print("Score " + score + " for submission: " + sfu(submitted));
158  
    if (best.put(data, score))
159  
      this.score = best.score;
160  
    ret score;
161  
  }
162  
}
163  
164  
Game > UserGame {
165  
  public double submit(Submission data) {
166  
    submitted = null;
167  
    double score = super.submit(data);
168  
    RGBImage image = renderImage(data);
169  
    isUser.setImage(image);
170  
    lblScore.setText("Current score: " + formatScore(score)
171  
      + " / Best: " + formatScore(userGame.score));
172  
    ret score;
173  
  }
174  
}
175  
176  
static S formatScore(double score) {
177  
  ret formatDouble(score, 2) + " %";
178  
}
179  
180  
svoid initAI(AI ai, GameForAI game) {
181  
  setOpt(ai, +game);
182  
}
183  
184  
static Game scoreAI(final AI ai, O onScore) {
185  
  aiMode = true;
186  
  final long start = sysNow();
187  
  try {
188  
    final new Game game;
189  
    initAI(ai, game);
190  
    halfTime = rounds/2;
191  
    game.step = 0;
192  
    while (game.step < rounds) {
193  
      ++game.step;
194  
      game.submitted = null;
195  
      double score = game.score;
196  
      RGBImage image = img;
197  
      try {
198  
        setOpt(ai, +image);
199  
        ai.go();
200  
      } catch e {
201  
        if (game.error == null) { // print first error to console
202  
          if (showConsoleOnError) showConsole();
203  
          printStackTrace(e);
204  
        }
205  
        game.error = e;
206  
      } finally {
207  
        setOpt(ai, image := null);
208  
      }
209  
      if (game.score > score) {
210  
        bool first = isRepro == null;
211  
        isRepro = showZoomedImage_centered(isRepro, aiTitle, renderWithHints(game.best.get()), 2);
212  
        if (first)
213  
          moveToTopRightCorner(isRepro);
214  
      }
215  
      pcallF(onScore, game);
216  
      //if (alwaysNewImage) nextImage();
217  
    }
218  
    ai.done();
219  
    
220  
    // TODO: winner saving
221  
    /*if (game.points-game.halfTimeScore >= rounds-halfTime) thread {
222  
      titleStatus(is, "Solved!");
223  
      showAnimationInTopLeftCorner(#1004373, game.points + " of " + rounds + " points!!", 3.0);
224  
      winner = structure(ai);
225  
      save("winner");
226  
    }*/
227  
    ret game;
228  
  } finally {
229  
    aiMode = false;
230  
    awt {
231  
      lblTiming.setText(formatDouble(toSeconds(sysNow()-start), 1) + " s");
232  
      //nextImage();
233  
    }
234  
  }
235  
}
236  
237  
static AI getAI(Class<? extends AI> c) {
238  
  AI ai = ais.get(c);
239  
  if (ai == null) ais.put(c, ai = nu(c));
240  
  ret ai;
241  
}
242  
243  
// onScore: voidfunc(Game)
244  
static Game testAI(Class<? extends AI> c, O onScore) {
245  
  ret scoreAI(getAI(c), onScore);
246  
}
247  
248  
svoid showWinnerCode {
249  
  if (winner == null) load("winner");
250  
  if (winner == null) messageBox("No winner yet");
251  
  else showWrappedText("Winner Code - " + programTitle(), winner);
252  
}
253  
254  
svoid restartAIs {
255  
  clearMapWithCleanUp(ais);
256  
}
257  
258  
svoid setInstruction(S s) {
259  
  setText(lblInstruction, instruction = s);
260  
}
261  
262  
static double scoreSubmission(Submission data) {
263  
  double sum = 0;
264  
  new L<Rect> rects;
265  
  for (Haar h : data.features)
266  
    addAll(rects, h.black, h.white);
267  
  if (anyRectsOverlap(rects)) ret 0;
268  
  for (Haar h : data.features)
269  
    sum += calcHaar(integralImage, h.black, h.white);
270  
  ret sum;
271  
}

Author comment

Began life as a copy of #1006931

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1009151
Snippet name: AI Game 7.1 Include [dev.]
Eternal ID of this version: #1009151/13
Text MD5: 469f48e8575e8baa95be2337f04243ec
Author: stefan
Category: javax / a.i.
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-07-06 01:19:52
Source code size: 7628 bytes / 271 lines
Pitched / IR pitched: No / No
Views / Downloads: 562 / 913
Version history: 12 change(s)
Referenced in: [show references]