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

319
LINES

< > BotCompany Repo | #1006931 // AI Game For Reproducing Images [Old Include, use #1015048 now]

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 = 1000;
35  
static double targetScore = 99.0; // stop when this score is reached
36  
static int fps = 50;
37  
sS gameTitle;
38  
sS newImageText = "New Image";
39  
sS instruction = "Reproduce this image:";
40  
sS aiTitle = "AI";
41  
sbool showConsoleOnError;
42  
static double reproZoom = 2;
43  
44  
static int w, h;
45  
static new UserGame userGame;
46  
static int halfTime;
47  
static ImageSurface is, isUser, isRepro;
48  
static RGBImage img;
49  
static new HashMap<Rect, Int> words;
50  
static L<Rect> solution;
51  
volatile sbool aiMode;
52  
static JLabel lblScore, lblTiming, lblInstruction, lblImageName;
53  
static new HashMap<Class, AI> ais;
54  
static S winner;
55  
static JCheckBox keepRunning;
56  
static L<JButton> aiButtons;
57  
static Game game;
58  
59  
svoid pGame {
60  
  substance();
61  
  swing {
62  
    thread { loadBinarySnippet(#1004373); } // preload applause animation
63  
    lblInstruction = jcenteredBoldLabel(instruction);
64  
    lblScore = jcenteredBoldLabel();
65  
    nextImage();
66  
    addToWindowTop(is, withMargin(lblInstruction));
67  
    addToWindow(is, withMargin(lblScore));
68  
    addToWindow(is, withMargin(lblImageName = jcenteredlabel()));
69  
    
70  
    // add AI bjuttons
71  
    aiButtons = ll();
72  
    for (final Class c : myNonAbstractClassesImplementing(AI)) {
73  
      final S name = shortClassName(c);
74  
      final JButton btn = jbutton(name);
75  
      final Runnable go = r {
76  
        if (aiMode) ret;
77  
        setText(btn, name + " Running...");
78  
        final Runnable again = this;
79  
        thread {
80  
          /*game =*/ testAI(c, voidfunc(Game game) {
81  
            if (!(game.step >= rounds || (game.step % 10) == 0)) ret;
82  
            S text = name + " scored " + formatScore(game.score) + " in " + n(game.step, "round");
83  
            if (game.error != null)
84  
              text += " - ERROR: " + game.error;
85  
            setText_noWait_sync(btn, text);
86  
          });
87  
          if (isChecked(keepRunning)) again.run();
88  
        }
89  
      };
90  
      onClick(btn, r { if (aiMode) setChecked(keepRunning, false); else go.run(); });
91  
      aiButtons.add(btn);
92  
      addToWindow(is, withMargin(btn));
93  
    }
94  
    
95  
    addToWindow(is, lblTiming = jCenteredLabel(;
96  
    titlePopupMenuItem(is, "Show Winner Code", f showBestCode);
97  
    titlePopupMenuItem(is, "Restart AIs", r { restartAIs() });
98  
    titlePopupMenuItem(is, "Diff", r {
99  
      setImage(subtractRGBImages(img, renderImage(game.best!)))
100  
    });
101  
    addToWindow(is, withMargin(jRightAlignedLine(keepRunning = jcheckbox("Keep AI Running", true))));
102  
    addToWindow(is, withMargin(jbutton("Restart AIs", r { clearMapWithCleanUp(ais); })));
103  
    addToWindow(is, withMargin(jbutton(newImageText, r {
104  
      nextImage();
105  
      setImage(main.img);
106  
    })));
107  
    addToWindow(is, withMargin(jbutton("Load image...", r {
108  
      frameTitle("Load image", selectSnippetID_v1(voidfunc(S imageID) {
109  
        loadImageSnippet(imageID);
110  
      }));
111  
    })));
112  
    addToWindow(is, withMargin(jbutton("Scale down", f scaleDown)));
113  
    addToWindow(is, withMargin(jbutton("Random image", r-thread {
114  
      loadImageSnippet(randomImageServerID());
115  
    })));
116  
117  
    packFrame(is);
118  
    setFrameWidth(is, 500);
119  
    centerTopFrame(is);
120  
    hideConsole();
121  
  }
122  
}
123  
124  
svoid nextImage {
125  
  main.img = makeImage();
126  
  if (aiMode) ret; // occasional updates only when AI is running
127  
  showTheImage();
128  
}
129  
130  
svoid showTheImage {
131  
  bool first = is == null;
132  
  is = showZoomedImage_centered(is, img, 1);
133  
  w = img.w();
134  
  h = img.h();
135  
    
136  
  if (first) {
137  
    if (gameTitle == null) gameTitle = programTitle();
138  
    setFrameTitle(is, gameTitle);
139  
140  
    disableImageSurfaceSelector(is);
141  
    
142  
    isUser = new ImageSurface(newBufferedImage(w, h, Color.white));
143  
    JComponent form = cast callOptMC('makeTheForm, userGame); // make form for user participation
144  
    
145  
    if (form != null) {
146  
      addToWindow(is, withTitle("Your Reproduction:", jscroll_centered(isUser)));
147  
      addToWindow(is, form);
148  
    }
149  
    
150  
    // animate if idle
151  
    /*awtEvery(is, 1000, r {
152  
      if (!aiMode && isInForeground(is) && !mouseInFrame(is))
153  
        nextImage();
154  
    });*/
155  
    
156  
    // show current image occasionally when AI is running
157  
    /*awtEvery(is, 1000/fps, r {
158  
      if (aiMode) showTheImage();
159  
    });*/
160  
  }
161  
}
162  
163  
// AI stuff
164  
165  
sclass Game implements GameForAI {
166  
  volatile int step;
167  
  new Best<Submission> best;
168  
  RGBImage bestImage;
169  
  double score;
170  
  Submission submitted; // what was submitted in this round
171  
  Throwable error;
172  
  volatile bool cancelled;
173  
  
174  
  public int round() { ret step; }
175  
  
176  
  public double submit(Submission data) {
177  
    if (data == null) ret 0;
178  
    if (submitted != null) fail("No multi-submit please");
179  
    submitted = data;
180  
    RGBImage image = renderImage(data);
181  
    double score = scoreImage(image);
182  
    if (best.put(data, score)) {
183  
      bestImage = image;
184  
      this.score = best.score;
185  
    }
186  
    ret score;
187  
  }
188  
}
189  
190  
Game > UserGame {
191  
  public double submit(Submission data) {
192  
    submitted = null;
193  
    double score = super.submit(data);
194  
    RGBImage image = renderImage(data);
195  
    isUser.setImage(image);
196  
    lblScore.setText("Current score: " + formatScore(score)
197  
      + " / Best: " + formatScore(userGame.score));
198  
    ret score;
199  
  }
200  
}
201  
202  
static S formatScore(double score) {
203  
  ret formatDouble(score, 2) + " %";
204  
}
205  
206  
svoid initAI(AI ai, GameForAI game) {
207  
  setOpt(ai, +game);
208  
}
209  
210  
static Game scoreAI(final AI ai, O onScore) {
211  
  aiMode = true;
212  
  final long start = sysNow();
213  
  try {
214  
    final new Game game;
215  
    initAI(ai, game);
216  
    halfTime = rounds/2;
217  
    game.step = 0;
218  
    main.game = game;
219  
    while (game.step < rounds && !game.cancelled) {
220  
      ++game.step;
221  
      game.submitted = null;
222  
      double score = game.score;
223  
      RGBImage image = img;
224  
      try {
225  
        setOpt(ai, +image);
226  
        ai.go();
227  
      } catch e {
228  
        if (game.error == null) { // print first error to console
229  
          if (showConsoleOnError) showConsole();
230  
          printStackTrace(e);
231  
        }
232  
        game.error = e;
233  
      } finally {
234  
        setOpt(ai, image := null);
235  
      }
236  
      if (game.score > score) {
237  
        bool first = isRepro == null;
238  
        S title = dropSpaces(formatScore(game.score)) + " - " + aiTitle;
239  
        isRepro = showZoomedImage_centered(isRepro, title, renderWithHints(game.best.get()), reproZoom);
240  
        if (first) {
241  
          //coActivateAllMyFrames();
242  
          moveToTopRightCorner(isRepro);
243  
          enlargeFrameLeftAndBottom(isRepro, 100, 100);
244  
        }
245  
      }
246  
      pcallF(onScore, game);
247  
      //if (alwaysNewImage) nextImage();
248  
    }
249  
    ai.done();
250  
    
251  
    // TODO: winner saving
252  
    /*if (game.points-game.halfTimeScore >= rounds-halfTime) thread {
253  
      titleStatus(is, "Solved!");
254  
      showAnimationInTopLeftCorner(#1004373, game.points + " of " + rounds + " points!!", 3.0);
255  
      winner = structure(ai);
256  
      save("winner");
257  
    }*/
258  
    ret game;
259  
  } finally {
260  
    aiMode = false;
261  
    awt {
262  
      lblTiming.setText(formatDouble(toSeconds(sysNow()-start), 1) + " s");
263  
      //nextImage();
264  
    }
265  
  }
266  
}
267  
268  
static AI getAI(Class<? extends AI> c) {
269  
  AI ai = ais.get(c);
270  
  if (ai == null) ais.put(c, ai = nu(c));
271  
  ret ai;
272  
}
273  
274  
// onScore: voidfunc(Game)
275  
static Game testAI(Class<? extends AI> c, O onScore) {
276  
  ret scoreAI(getAI(c), onScore);
277  
}
278  
279  
svoid showBestCode {
280  
  Submission s = game.best!;
281  
  showWrappedText("Best code (" + formatScore(game.best.score()) + ")", structure(s));
282  
}
283  
284  
svoid showWinnerCode {
285  
  if (winner == null) load("winner");
286  
  if (winner == null) messageBox("No winner yet");
287  
  else showWrappedText("Winner Code - " + programTitle(), winner);
288  
}
289  
290  
static double scoreImage(RGBImage image) {
291  
  ret 100*(1.0-rgbDistance(image, img));
292  
}
293  
294  
svoid restartAIs {
295  
  clearMapWithCleanUp(ais);
296  
  // whatever I do, it doesn't get cancelled, haha
297  
  //if (game != null) game.cancelled = true;
298  
}
299  
300  
svoid setInstruction(S s) {
301  
  setText(lblInstruction, instruction = s);
302  
}
303  
304  
svoid setImage(final RGBImage img) {
305  
  swing {
306  
    main.img = img;
307  
    showTheImage();
308  
    restartAIs();
309  
  }
310  
}
311  
312  
svoid scaleDown() {
313  
  setImage(rgbScale(main.img, 0.5));
314  
}
315  
316  
svoid loadImageSnippet(S id) {
317  
  setImage(RGBImage(changeTransparencyToWhiteBackground(loadImage2(id))));
318  
  setText(lblImageName, snippetWithTitle(id));
319  
}

Author comment

Began life as a copy of #1006891

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: #1006931
Snippet name: AI Game For Reproducing Images [Old Include, use #1015048 now]
Eternal ID of this version: #1006931/107
Text MD5: 015ee824c98f9a36e48576b29cba2c8d
Author: stefan
Category: javax / a.i.
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-05-07 14:16:29
Source code size: 9082 bytes / 319 lines
Pitched / IR pitched: No / No
Views / Downloads: 580 / 1964
Version history: 106 change(s)
Referenced in: [show references]