!752 !include #1000522 // image helper functions static RGBImage targetImg; static S bestScript; static double score; static long tries; static ImageSurface imageSurface; //static S strategy = "random;"; static S strategy = "random; vary;"; static boolean warned; p { targetImg = new RGBImage(200, 200, Color.blue); while (score < 100) { for (L s : statements(strategy)) { if (jmatch("random;", s)) { S scriptSchema = "fill();"; tryScript(makeScript(scriptSchema)); } else if (jmatch("vary;", s)) { if (bestScript != null) { S variation = varyScript(bestScript); if (variation != null && neq(bestScript, variation)) tryScript(variation); } } else if (!warned) { print("Unknown strategy statement: " + join(s)); warned = true; } } } } static S varyScript(S script) { L tok = javaTok(script); for (int i = 1; i < l(tok); i += 2) if (isQuoted(tok.get(i))) { S s = unquote(tok.get(i)); tok.set(i, quote(varyColor(s))); } ret join(tok); } static S varyColor(S color) { ret varyColor(new RGB(color)).toString(); } static void tryScript(S script) { ++tries; //print ("Script: " + script); RGBImage img = new RGBImage(200, 200, Color.white); render(img, script); double newScore = diffToPercent(diff(img, targetImg)); if (newScore > score /*|| (newScore == score && l(script) < l(bestScript))*/) { score = newScore; bestScript = script; print("Try " + tries + ". New best score: " + score + ", script: " + script); imageSurface = showImage(img, imageSurface); } } // assumes diff is between 0.0 (full score) and 1.0 (least score) static double diffToPercent(double diff) { ret 100*(1-diff); } static S makeScript(S schema) { L tok = javaTok(schema); int i = findCodeTokens(tok, "<", "color1", ">"); if (i >= 0) { clearAllTokens(tok, i, i+5); tok.set(i, quote(randomColor().toString())); tok = javaTok(tok); } ret join(tok); } static void render(RGBImage img, S script) { L tok = javaTok(script); new Matches m; for (L s : statements(tok)) { if (jmatch("fill(*);", s, m)) { fill(img, m.unq(0)); } else fail("unknown statement: " + join(s)); } }