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

246
LINES

< > BotCompany Repo | #1006846 // A. I. Game 3.2 / Find The Main Program [UNSOLVED]

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Uses 3874K of libraries. Click here for Pure Java version (7318L/51K/185K).

!7

///////////////////////////
// Your API to work with //
///////////////////////////

abstract sclass GameForAI {
  abstract RGBImage getImage();
  abstract L<Rect> submit(Pt point); // returns correct solution so AI can learn from it
}

abstract sclass AI {
  // stuff you get
  
  GameForAI game;
  RGBImage image;
  int steps;
  RGBImage image() { ret image; }
  int w() { ret image.w(); }
  int h() { ret image.h(); }
  L<Rect> submit(Pt p) { ret game.submit(p); }
  L<Rect> submit(Rect r) { ret submit(middleOfRect(r)); }
  L<Rect> submitNothing() { ret game.submit(null); }

  // implement this method and call submit()
  abstract void go();
  
  void done() {}
}

//////////////////////////////////////
// Test AIs. Just add your own here //
//////////////////////////////////////

AI > ClickAnyBLOB {
  void go {
    submit(random(segment(image;
  }
}

static L<Rect> segment(RGBImage img) {
  ret autoSegment(new BWImage(img), 3); // 2 is too small
}

///////////////
// Main Game //
///////////////

static S instruction = "Find The Main Program!";
static int w = 150, h = 150;
static int border = 10, fontSize = 30, numberMargin = 3;
static int rounds = 1000, numbers = 2;
static S font = #1004887;
static bool alwaysNewImage = true; // prevents AIs being stuck on an image
static int fps = 50;

static int points, clicks;
static ImageSurface is, isWrong;
static long isWrongLast;
static RGBImage img;
static new HashMap<Rect, Int> words;
static L<Rect> solution;
volatile sbool aiMode;
static JLabel lblScore, lblTiming;
static new HashMap<Class, AI> ais;

p-substance {
  thread { loadBinarySnippet(#1004373); } // preload applause animation
  nextImage();
  addToWindow(is, withMargin(lblScore = jcenteredBoldLabel("Your score: 0 of 0")));
  for (final Class c : myNonAbstractClassesImplementing(AI)) {
    final S name = shortClassName(c);
    final JButton btn = jbutton(name);
    onClick(btn, r {
      if (aiMode) ret;
      btn.setText(name + " Running...");
      thread {
        Game game = testAI(c, voidfunc(Game game) {
          if (game.step < 50 || (game.step % 10) == 0 || game.step == rounds) {
            S text = name + " scored " + game.points + " of " + game.step;
            if (game.error != null)
              text += " - ERROR: " + game.error;
            setText_noWait(btn, text);
          }
        });
      }
    });
    addToWindow(is, withMargin(btn));
  }
  addToWindow(is, lblTiming = jCenteredLabel(;
  titlePopupMenuItem(is, "Restart AIs", r { clearMapWithCleanUp(ais); });
  addToWindow(is, withMargin(jbutton("Restart AIs", r { clearMapWithCleanUp(ais); })));
  
  packFrame(is);
  setFrameWidth(is, 400);
  centerTopFrame(is);
  hideConsole();
}

sclass Puzzle {
  RGBImage image;
  L<Rect> solution;
  
  *() {}
  *(BufferedImage image, L<Rect> *solution) {
    this.image = new RGBImage(image);
  }
  *(RGBImage *image, L<Rect> *solution) {}
}

svoid nextImage {
  Puzzle puzzle = makePuzzle();
  main.img = puzzle.image;
  solution = puzzle.solution;
  if (aiMode) ret; // occasional updates only when AI is running
  showTheImage();
}

svoid showTheImage {
  bool first = is == null;
  is = showZoomedImage_centered(is, img, instruction, 1.5);
  if (first) {
    onLeftClick(is, voidfunc(Pt p) {
      ++clicks;
      if (anyRectContains(solution, is.pointFromComponentCoordinates(p))) {
        ++points;
        nextImage();
      } else if (alwaysNewImage) nextImage();
      lblScore.setText(print("Your score: " + points + " of " + clicks));
    });
    disableImageSurfaceSelector(is);
    
    // animate if idle
    awtEvery(is, 1000, r {
      if (!aiMode && isInForeground(is) && !mouseInComponent(is))
        nextImage();
    });
    
    // show current image occasionally when AI is running
    awtEvery(is, 1000/fps, r {
      if (aiMode) showTheImage();
    });
  }
}

// AI stuff

sclass Game extends GameForAI {
  int points, step;
  Pt submitted;
  Throwable error;
  
  RGBImage getImage() { ret img; }

  L<Rect> submit(Pt p) {
    if (submitted != null) fail("No multi-submit please");
    submitted = p == null ? new Pt(-9, -9) : p;
    if (p != null && anyRectContains(solution, p)) {
      ++points;
      if (!alwaysNewImage) nextImage();
    }
    ret solution;
  }
}

static Game scoreAI(AI ai, O onScore) {
  aiMode = true;
  final long start = sysNow();
  try {
    final new Game game;
    setOpt(ai, +game);
    while (game.step < rounds) {
      ++game.step;
      ++ai.steps;
      game.submitted = null;
      int points = game.points;
      RGBImage image = img;
      try {
        setOpt(ai, +image);
        ai.go();
      } catch e {
        if (game.error == null) { // print first error to console
          showConsole();
          printStackTrace(e);
        }
        game.error = e;
      } finally {
        setOpt(ai, image := null);
      }
      if (points == game.points && hasElapsed(isWrongLast, 50)) {
        isWrongLast = sysNow();
        bool first = isWrong == null;
        S guess = ""; // game.submitted == null ? "no click" : game.submitted.x + "/" + game.submitted.y;
        isWrong = showImage(isWrong, "Last Blunder" + (nempty(guess) ? " (" + guess + ")" : ""), rgbMarkPoint(rgbClone(image), game.submitted, Color.red, 3));
        if (first) {
          setFrameWidth(isWrong, 230);
          moveToTopRightCorner(isWrong);
          moveFrameDown(isWrong, 100);
        }
      }
      pcallF(onScore, game);
      if (alwaysNewImage) nextImage();
    }
    print("AI " + shortClassName(ai) + " points after " + rounds + " rounds: " + game.points);
    ai.done();
    if (game.points >= rounds) thread { showAnimationInTopLeftCorner(#1004373, game.points + " of " + rounds + " points!!", 3.0); }
    ret game;
  } finally {
    aiMode = false;
    awt {
      lblTiming.setText(formatDouble(toSeconds(sysNow()-start), 1) + " s");
      nextImage();
    }
  }
}

static AI getAI(Class<? extends AI> c) {
  AI ai = ais.get(c);
  if (ai == null) ais.put(c, ai = nu(c));
  ret ai;
}

// onScore: voidfunc(Game)
static Game testAI(Class<? extends AI> c, O onScore) {
  ret scoreAI(getAI(c), onScore);
}

//////////////////
// PUZZLE MAKER //
//////////////////

static Puzzle makePuzzle() {
  S text = "!7\n\n";
  int n = random(4);
  for i to n: text += "static int " + lowerCaseLetter(i+1) + ";\n";
  if (n > 0) text += "\n";
  text += "p { print(\"hello\"); }\n";
  n = random(2);
  if (n > 0) text += "\n";
  for i to n: text += "static void " + lowerCaseLetter(i+5) + " () {}\n";
  BufferedImage img = renderSourceCode_1(text);
  int solutionLine = indexOfStartsWith(toLines(text), "p {")+1;
  int lh = renderSourceCode_1_lineHeight();
  L<Rect> solution = ll(new Rect(0, (solutionLine-1)*lh, img.getWidth(), lh));
  ret new Puzzle(img, solution);
}

Author comment

Began life as a copy of #1006753

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1006846
Snippet name: A. I. Game 3.2 / Find The Main Program [UNSOLVED]
Eternal ID of this version: #1006846/24
Text MD5: acfb6183a90b1f1bd1e74a3b4f9df4f7
Transpilation MD5: b1475c8511d27d80debe9c073b428c15
Author: stefan
Category: javax / gui
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-03-05 21:18:56
Source code size: 7029 bytes / 246 lines
Pitched / IR pitched: No / No
Views / Downloads: 531 / 676
Version history: 23 change(s)
Referenced in: [show references]