Пример #1
0
    public void run() {
      try {
        while (scriptRunning) {
          if (!parent.isPaused() && parent.game.isLoggedIn() && status != "Logging back in") {
            int rand = randomGenerator.nextInt(30);
            switch (rand) {
              case 1:
                parent.camera.setAngle(Methods.random(0, 360));
                break;
              case 2:
                parent.camera.setPitch(Methods.random(40, 100));
                break;
              case 3:
                parent.mouse.setSpeed(Methods.random(5, 9));
                break;
              case 5:
                parent.camera.setPitch(Methods.random(40, 100));
                parent.camera.setAngle(Methods.random(0, 360));
                break;
              default:
                break;
            }
          }

          sleep(Methods.random(2000, 5000));
        }
      } catch (InterruptedException e) {
        log(e.getMessage());
      }
    }
  public static void main(String[] args) {
    JFrame frame = new JFrame("options");

    frame.setSize(new Dimension(500, 300));
    frame.getContentPane().add(new PackagerOptionsPanel(null));

    frame.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            e.getWindow().dispose();
          }

          @Override
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          }
        });

    try {
      SwingUtilities.invokeAndWait(new PackAndShowFrameWorker(frame));
    } catch (InterruptedException e) {
      // Immediately reasserts the exception by interrupting the caller thread itself
      Thread.currentThread().interrupt();

      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
Пример #3
0
  public void run() {
    MOVE_PREV = MOVE_DOWN;

    System.out.println("INIT!");
    map = new int[mapX][mapY];

    for (int i = 0; i < map.length; i++) {
      for (int j = 0; j < map[i].length; j++) {
        map[i][j] = 0;
      }
    }
    map[blockP.x][blockP.y] = 1;
    //    	map[0][20] = 1;

    StdDraw.setXscale(-1.0, 1.0);
    StdDraw.setYscale(-1.0, 1.0);

    // initial values

    // double vx = 0.015, vy = 0.023;     // velocity

    // main animation loop
    while (true) {

      drawGame();
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      movePrev();
    }
  }
 public void run() {
   try {
     performIntersection(this.gridPosition);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Пример #5
0
    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {

      try {

        String value = get();
        myMessage.messageChanged(value);

      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      } catch (CancellationException e) {
        myMessage.messageChanged("Operation Cancelled");
      } catch (Exception e) {
        e.printStackTrace();
      }

      Toolkit.getDefaultToolkit().beep();
      // startButton.setEnabled(true);
      // cancelButton.setEnabled(false);
      setCursor(null); // turn off the wait cursor
      StartButton.setEnabled(true);
      cancelButton.setEnabled(false);
      taskOutput.append("Done!\n");
    }
Пример #6
0
 public void run() {
   while (true) {
     repaint();
     try {
       Thread.sleep(FLASH_TIME);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
 public void progress() {
   int i = 1;
   int j = 0;
   for (i = 1; i <= 100; i++) {
     progressbar1.setValue(i);
     try {
       Thread.sleep(25);
     } catch (InterruptedException e1) {
       e1.printStackTrace();
     }
   }
 }
Пример #8
0
 public void go() {
   // TODO Pause the game after several blocks
   do {
     try {
       Thread.sleep(1000L);
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     movedown();
     rowcheck();
   } while (bottom == false);
   bottom = false;
   blockgen();
 }
Пример #9
0
  public void appear(final CardGui card) {
    moving = card;
    player1.animations.add(moving);
    Thread t =
        new Thread(
            () -> {
              moving.setBounds(925 - 62, 609 - 93, 0, 0);
              int i = 0, j = 0;
              while (i <= 124 || j <= 186) {
                try {
                  if (i <= 124) {
                    i++;
                    moving.setBounds(925 - 62, 609 - 93, i, j);
                    Thread.sleep(1);
                  }
                  if (j <= 186) {
                    j++;
                    moving.setBounds(925 - 62, 609 - 93, i, j);

                    Thread.sleep(1);
                  }
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }
              i = 925 - 62;

              while (i >= 652) {
                i--;
                try {
                  Thread.sleep(1);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                moving.setLocation(i, 609 - 93);
              }

              player1.animations.remove(moving);
              player1.repairListeners(false);
              PlayGui.player.pdeck.textField.setText(
                  "cards left " + PlayGui.player.pdeck.Deck.cardsLeft());
              player1.cardDrawn = 1;
              PlayGui.player.pdeck.textField.repaint();
              setVisible(true);
              repaint();
            });
    t.start();
  }
Пример #10
0
  public void run() {
    try {
      while (running) {

        try {
          Thread.sleep(framerate);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        repaint();
        updateObjects();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #11
0
    public void run() {
      try {
        // System.out.println("right before the while loop of the thread");
        // layeredPane.add(background,99);

        while (true) {

          startTime = System.nanoTime();
          try {
            // System.out.println("before Sleep");
            Thread.sleep(30);
            // System.out.println("after sleep");
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          panel.remove(layeredPane);
          Iterator<PlayerMob> allPlayers = players.iterator();
          PlayerMob aPlayer = null;
          while (allPlayers.hasNext()) {
            aPlayer = (PlayerMob) allPlayers.next();
            // System.out.println("INTHELOOP:info.getUsername ="******"
            // myChat.getUsername ="******"for loop index catch");
          	continue;
          }*/

        }
      } catch (NullPointerException ed) {
        System.err.println("for loop null catch");
        startDrawingPanelThread();
      } catch (Exception ev) {
        System.err.println("for loop catch");
        ev.printStackTrace();
      }
    }
Пример #12
0
 @Override
 public void run() {
   // TODO �Զ����ɵķ������
   while (true) {
     for (int i = 0; i < num; i++) {
       for (int j = 0; j < balls.length; j++) {
         balls[j].move();
       }
       repaint();
       try {
         Thread.sleep(3);
       } catch (InterruptedException e) {
         // TODO �Զ����ɵ� catch ��
         e.printStackTrace();
       }
     }
   }
 }
Пример #13
0
  public void init() {
    MediaTracker mt = new MediaTracker(this);

    URL url = getClass().getResource("tiger.gif");

    try {
      image = createImage((ImageProducer) url.getContent());
      mt.addImage(image, 0);
      mt.waitForID(0);
    } catch (Exception e) {
      e.printStackTrace();
    }
    imw = image.getWidth(this);
    imh = image.getWidth(this);
    pixels = new int[imw * imh];

    try {
      PixelGrabber pg = new PixelGrabber(image, 0, 0, imw, imh, pixels, 0, imw);
      pg.grabPixels();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    addMouseMotionListener(
        new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent e) {
            int mx = e.getX(), my = e.getY();

            if (mx > 0 && mx < imw && my > 0 && my < imh) {
              int pixel = ((int[]) pixels)[my * imw + mx];

              int red = defaultRGB.getRed(pixel),
                  green = defaultRGB.getGreen(pixel),
                  blue = defaultRGB.getBlue(pixel),
                  alpha = defaultRGB.getAlpha(pixel);

              showStatus("red=" + red + " green=" + green + " blue=" + blue + " alpha=" + alpha);
            }
          }
        });
  }
Пример #14
0
  private static int[] makeGradientPallet() {
    BufferedImage image = new BufferedImage(100, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    Point2D start = new Point2D.Float(0f, 0f);
    Point2D end = new Point2D.Float(99f, 0f);
    float[] dist = {0f, .5f, 1f};
    Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};
    g2.setPaint(new LinearGradientPaint(start, end, dist, colors));
    g2.fillRect(0, 0, 100, 1);
    g2.dispose();

    int width = image.getWidth(null);
    int[] pallet = new int[width];
    PixelGrabber pg = new PixelGrabber(image, 0, 0, width, 1, pallet, 0, width);
    try {
      pg.grabPixels();
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
    return pallet;
  }
Пример #15
0
  public static void main(String[] args) {
    // TODO main
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("h", "help"), "Show this help dialog.");
    OptionSpec<String> serverOption =
        parser
            .acceptsAll(Arrays.asList("s", "server"), "Server to join.")
            .withRequiredArg()
            .describedAs("server-address[:port]");
    OptionSpec<String> proxyOption =
        parser
            .acceptsAll(
                Arrays.asList("P", "proxy"),
                "SOCKS proxy to use. Ignored in presence of 'socks-proxy-list'.")
            .withRequiredArg()
            .describedAs("proxy-address");
    OptionSpec<String> ownerOption =
        parser
            .acceptsAll(
                Arrays.asList("o", "owner"), "Owner of the bot (username of in-game control).")
            .withRequiredArg()
            .describedAs("username");
    OptionSpec<?> offlineOption =
        parser.acceptsAll(
            Arrays.asList("O", "offline"),
            "Offline-mode. Ignores 'password' and 'account-list' (will "
                + "generate random usernames if 'username' is not supplied).");
    OptionSpec<?> autoRejoinOption =
        parser.acceptsAll(Arrays.asList("a", "auto-rejoin"), "Auto-rejoin a server on disconnect.");
    OptionSpec<Integer> loginDelayOption =
        parser
            .acceptsAll(
                Arrays.asList("d", "login-delay"),
                "Delay between bot joins, in milliseconds. 5000 is "
                    + "recommended if not using socks proxies.")
            .withRequiredArg()
            .describedAs("delay")
            .ofType(Integer.class);
    OptionSpec<Integer> botAmountOption =
        parser
            .acceptsAll(
                Arrays.asList("b", "bot-amount"),
                "Amount of bots to join. Must be <= amount of accounts.")
            .withRequiredArg()
            .describedAs("amount")
            .ofType(Integer.class);

    OptionSpec<String> accountListOption =
        parser
            .accepts(
                "account-list",
                "File containing a list of accounts, in username/email:password format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> socksProxyListOption =
        parser
            .accepts(
                "socks-proxy-list",
                "File containing a list of SOCKS proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> httpProxyListOption =
        parser
            .accepts(
                "http-proxy-list",
                "File containing a list of HTTP proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");

    OptionSet options;
    try {
      options = parser.parse(args);
    } catch (OptionException exception) {
      try {
        parser.printHelpOn(System.out);
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
      return;
    }

    if (options.has("help")) {
      printHelp(parser);
      return;
    }

    final boolean offline = options.has(offlineOption);
    final boolean autoRejoin = options.has(autoRejoinOption);

    final List<String> accounts;
    if (options.has(accountListOption)) {
      accounts = loadAccounts(options.valueOf(accountListOption));
    } else if (!offline) {
      System.out.println("Option 'accounts' must be supplied in " + "absence of option 'offline'.");
      printHelp(parser);
      return;
    } else accounts = null;

    final String server;
    if (!options.has(serverOption)) {
      System.out.println("Option 'server' required.");
      printHelp(parser);
      return;
    } else server = options.valueOf(serverOption);

    final String owner;
    if (!options.has(ownerOption)) {
      System.out.println("Option 'owner' required.");
      printHelp(parser);
      return;
    } else owner = options.valueOf(ownerOption);

    final List<String> socksProxies;
    if (options.has(socksProxyListOption))
      socksProxies = loadProxies(options.valueOf(socksProxyListOption));
    else socksProxies = null;
    final boolean useProxy = socksProxies != null;

    final List<String> httpProxies;
    if (options.has(httpProxyListOption))
      httpProxies = loadLoginProxies(options.valueOf(httpProxyListOption));
    else if (!offline && accounts != null) {
      System.out.println(
          "Option 'http-proxy-list' required if " + "option 'account-list' is supplied.");
      printHelp(parser);
      return;
    } else httpProxies = null;

    final int loginDelay;
    if (options.has(loginDelayOption)) loginDelay = options.valueOf(loginDelayOption);
    else loginDelay = 0;

    final int botAmount;
    if (!options.has(botAmountOption)) {
      System.out.println("Option 'bot-amount' required.");
      printHelp(parser);
      return;
    } else botAmount = options.valueOf(botAmountOption);

    initGui();
    while (!sessions.get()) {
      synchronized (sessions) {
        try {
          sessions.wait(5000);
        } catch (InterruptedException exception) {
        }
      }
    }

    final Queue<Runnable> lockQueue = new ArrayDeque<Runnable>();

    ExecutorService service = Executors.newFixedThreadPool(botAmount + (loginDelay > 0 ? 1 : 0));
    final Object firstWait = new Object();
    if (loginDelay > 0) {
      service.execute(
          new Runnable() {
            @Override
            public void run() {
              synchronized (firstWait) {
                try {
                  firstWait.wait();
                } catch (InterruptedException exception) {
                }
              }
              while (true) {
                if (die) return;
                while (slotsTaken.get() >= 2) {
                  synchronized (slotsTaken) {
                    try {
                      slotsTaken.wait(500);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
                synchronized (lockQueue) {
                  if (lockQueue.size() > 0) {
                    Runnable thread = lockQueue.poll();
                    synchronized (thread) {
                      thread.notifyAll();
                    }
                    lockQueue.offer(thread);
                  } else continue;
                }
                try {
                  Thread.sleep(loginDelay);
                } catch (InterruptedException exception) {
                }
                while (!sessions.get()) {
                  synchronized (sessions) {
                    try {
                      sessions.wait(5000);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
              }
            }
          });
    }
    final List<String> accountsInUse = new ArrayList<String>();
    for (int i = 0; i < botAmount; i++) {
      final int botNumber = i;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              if (loginDelay > 0)
                synchronized (lockQueue) {
                  lockQueue.add(this);
                }
              Random random = new Random();

              if (!offline) {
                boolean authenticated = false;
                user:
                while (true) {
                  if (authenticated) {
                    authenticated = false;
                    sessionCount.decrementAndGet();
                  }
                  Session session = null;
                  String loginProxy;
                  String account = accounts.get(random.nextInt(accounts.size()));
                  synchronized (accountsInUse) {
                    if (accountsInUse.size() == accounts.size()) System.exit(0);
                    while (accountsInUse.contains(account))
                      account = accounts.get(random.nextInt(accounts.size()));
                    accountsInUse.add(account);
                  }
                  String[] accountParts = account.split(":");
                  while (true) {
                    while (!sessions.get()) {
                      synchronized (sessions) {
                        try {
                          sessions.wait(5000);
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    loginProxy = httpProxies.get(random.nextInt(httpProxies.size()));
                    try {
                      session = Util.retrieveSession(accountParts[0], accountParts[1], loginProxy);
                      // addAccount(session);
                      sessionCount.incrementAndGet();
                      authenticated = true;
                      break;
                    } catch (AuthenticationException exception) {
                      System.err.println("[Bot" + botNumber + "] " + exception);
                      if (!exception.getMessage().startsWith("Exception"))
                        // && !exception.getMessage().equals(
                        // "Too many failed logins"))
                        continue user;
                    }
                  }
                  System.out.println(
                      "["
                          + session.getUsername()
                          + "] Password: "******", Session ID: "
                          + session.getSessionId());
                  while (!joins.get()) {
                    synchronized (joins) {
                      try {
                        joins.wait(5000);
                      } catch (InterruptedException exception) {
                      }
                    }
                  }
                  if (loginDelay > 0) {
                    synchronized (this) {
                      try {
                        synchronized (firstWait) {
                          firstWait.notifyAll();
                        }
                        wait();
                      } catch (InterruptedException exception) {
                      }
                    }
                  }

                  while (true) {
                    String proxy =
                        useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                    try {
                      new DarkBotMCSpambot(
                          DARK_BOT,
                          server,
                          session.getUsername(),
                          session.getPassword(),
                          session.getSessionId(),
                          null,
                          proxy,
                          owner);
                      if (die) break user;
                      else if (!autoRejoin) break;
                    } catch (Exception exception) {
                      exception.printStackTrace();
                      System.out.println(
                          "["
                              + session.getUsername()
                              + "] Error connecting: "
                              + exception.getCause().toString());
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] Account failed");
                }
              } else {
                while (true) {
                  String proxy =
                      useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                  try {
                    String username = "";
                    if (accounts != null) {
                      username = accounts.get(random.nextInt(accounts.size())).split(":")[0];
                      synchronized (accountsInUse) {
                        while (accountsInUse.contains(username))
                          username = accounts.get(random.nextInt(accounts.size()));
                        accountsInUse.add(username);
                      }
                    } else
                      for (int i = 0; i < 10 + random.nextInt(6); i++)
                        username += alphas[random.nextInt(alphas.length)];
                    if (loginDelay > 0) {
                      synchronized (this) {
                        try {
                          synchronized (firstWait) {
                            firstWait.notifyAll();
                          }
                          wait();
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    new DarkBotMCSpambot(DARK_BOT, server, username, "", "", null, proxy, owner);
                    if (die || !autoRejoin) break;
                    else continue;
                  } catch (Exception exception) {
                    System.out.println(
                        "[Bot" + botNumber + "] Error connecting: " + exception.toString());
                  }
                }
              }
            }
          };
      service.execute(runnable);
    }
    service.shutdown();
    while (!service.isTerminated()) {
      try {
        service.awaitTermination(9000, TimeUnit.DAYS);
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
    }
    System.exit(0);
  }
Пример #16
0
  @Override
  public void onTick() {
    if (!bot.hasSpawned() || !bot.isConnected()) return;
    if (ticksToGo > 0) {
      ticksToGo--;
      return;
    }

    MainPlayerEntity player = bot.getPlayer();
    if (player == null) return;
    if (firstStart) {
      bot.say("/tpa DarkStorm_");
      ticksToGo = 15;
      firstStart = false;
      return;
    } else if (asdfasdfasdf) {
      bot.say("/warp arena");
      ticksToGo = 200;
      asdfasdfasdf = false;
      return;
    } else if (asdfasdf) {
      bot.say("/pay DarkStorm_ 1000");
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      /*try {
      	PlayerInventory inventory = player.getInventory();
      	for(int i = 0; i < 44; i++) {
      		ItemStack item = inventory.getItemAt(i);
      		if(item != null) {
      			inventory.selectItemAt(i);
      			inventory.dropSelectedItem();
      		}
      	}
      } catch(Exception exception) {}*/
      bot.say("\247bai");
      asdfasdf = false;
      return;
    }
    // connectionHandler.disconnect("");
    // return;
    // } else if("".equals(""))
    // return;
    // if(player.getDistanceTo(spawn) < 7 && player.getZ() < 589.5) {
    // player.setZ(player.getZ() + 0.12);
    // bot.updateMovement();
    // } else
    // canSpam = true;

    // if(player.getDistanceTo(spawn) < 10 && player.getY() < 72) {
    // if(player.getZ() < -37.6)
    // player.setZ(player.getZ() + 0.1);
    // else if(player.getX() < 232.4)
    // player.setX(player.getX() + 0.1);
    // else
    // player.setY(player.getY() + 0.1);
    // bot.updateMovement();
    // } else if(player.getZ() > -38 && player.getZ() < -36.6
    // && player.getX() > 232 && player.getX() < 233) {
    // player.setZ(player.getZ() + 0.1);
    // bot.updateMovement();
    // } else

    // if(player.getDistanceToSquared(spawn) > 49)
    // mode = 3;
    // if(mode == 0)
    // mode = player.getZ() > 295 ? 2 : 1;
    // switch(mode) {
    // case -1:
    // canSpam = true;
    // break;
    // case 1:
    // canSpam = false;
    // if(player.getZ() < 296.3) {
    // player.setZ(player.getZ() + 0.1);
    // bot.updateMovement();
    // } else
    // mode = -1;
    // break;
    // case 2:
    // canSpam = false;
    // if(player.getZ() > 286.6) {
    // player.setZ(player.getZ() - 0.1);
    // bot.updateMovement();
    // } else
    // mode = -1;
    // break;
    // default:
    // connectionHandler.disconnect("Bad location!");
    // break;
    // }

    canSpam = true;
  }
Пример #17
0
  private DarkBotMCSpambot(
      DarkBot darkBot,
      String server,
      String username,
      String password,
      String sessionId,
      String loginProxy,
      String proxy,
      String owner) {
    synchronized (bots) {
      bots.add(this);
      // slotsTaken.incrementAndGet();
      synchronized (slotsTaken) {
        slotsTaken.notifyAll();
      }
    }
    MinecraftBotData.Builder builder = MinecraftBotData.builder();
    // botData.nickname = "";
    // for(int i = 0; i < 10; i++)
    // botData.nickname += alphas[random.nextInt(alphas.length)];
    if (proxy != null && !proxy.isEmpty()) {
      int port = 80;
      ProxyType type = ProxyType.SOCKS;
      if (proxy.contains(":")) {
        String[] parts = proxy.split(":");
        proxy = parts[0];
        port = Integer.parseInt(parts[1]);
        if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1];
      }
      builder.withSocksProxy(new ProxyData(proxy, port, type));
      this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port));
    }
    if (loginProxy != null && !loginProxy.isEmpty()) {
      int port = 80;
      if (loginProxy.contains(":")) {
        String[] parts = loginProxy.split(":");
        loginProxy = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP));
      this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port));
    }
    builder.withUsername(username);
    if (sessionId != null) builder.withSessionId(sessionId);
    else builder.withPassword(password);
    if (server != null && !server.isEmpty()) {
      int port = 25565;
      if (server.contains(":")) {
        String[] parts = server.split(":");
        server = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withServer(server).withPort(port);
    } else throw new IllegalArgumentException("Unknown server!");

    this.owner = owner;
    MinecraftBotData botData = builder.build();
    System.setProperty("socksProxyHost", "");
    System.setProperty("socksProxyPort", "");
    System.out.println("[" + username + "] Connecting...");
    bot = new MinecraftBot(darkBot, botData);
    bot.setMovementDisabled(true);
    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    // System.gc();
    System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")");
    bot.getEventManager().registerListener(this);
    bot.getGameHandler().registerListener(this);

    long lastShoutTime = System.currentTimeMillis();
    while (bot.isConnected()) {
      if (die) {
        connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye"));
        return;
      }
      try {
        Thread.sleep(3000 + random.nextInt(1000));
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
      if (!bot.hasSpawned()) continue;
      connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt()));
      if (spamMessage == null || !canSpam) continue;
      String message = spamMessage;
      if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]);
      if (nextSkill >= skills.length) nextSkill = 0;
      if (message.contains("%bot")) {
        synchronized (bots) {
          message =
              message.replace(
                  "%bot",
                  bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++)
                      .bot
                      .getSession()
                      .getUsername());
        }
      }
      if (message.contains("%spamlist"))
        message = message.replace("%spamlist", spamList[nextSpamList++]);
      if (nextSpamList >= spamList.length) nextSpamList = 0;
      if (message.contains("%rnd")) {
        int length = 1;
        int index = message.indexOf("%rnd") + "%rnd".length();
        int lastIndex;
        for (lastIndex = index; lastIndex < message.length(); lastIndex++)
          if (Character.isDigit(message.charAt(lastIndex))) lastIndex++;
          else break;
        if (lastIndex > message.length()) lastIndex--;
        try {
          System.out.println(index + "," + lastIndex + "," + message.length());
          length = Integer.parseInt(message.substring(index, lastIndex));
        } catch (Exception exception) {
        }

        String randomChars = "";
        for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)];
        message = message.replace("%rnd", randomChars);
      }
      if (message.contains("%msg"))
        message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", "");
      if (message.contains("%ernd")) {
        message = message.replace("%ernd", "");
        int extraMessageLength = 15 + random.nextInt(6);
        message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " [";
        extraMessageLength -= 3;
        for (int i = 0; i < extraMessageLength; i++)
          message += alphas[random.nextInt(alphas.length)];
        message += "]";
      } else message = message.substring(0, Math.min(100, message.length()));
      connectionHandler.sendPacket(new Packet3Chat(message));
    }
    synchronized (bots) {
      bots.remove(this);
    }
    amountJoined.decrementAndGet();
    slotsTaken.decrementAndGet();
    synchronized (slotsTaken) {
      slotsTaken.notifyAll();
    }
  }
Пример #18
0
 @Override
 public void keyPressed(KeyEvent e) {
   this.voix.stop();
   if (!end) {
     if (e.getKeyCode() == KeyEvent.VK_F2) {
       this.voix.playText(
           " Pour répéter la question, veuillez appuyer sur F1"
               + "Vous pouvez jouer avec la souris ou avec F1 et les chiffres");
       try {
         Thread.sleep(3000);
       } catch (InterruptedException e1) {
         e1.printStackTrace();
       }
       this.voix.playText(
           "Appuyer sur un chiffre pour écouter une réponse, puis appuyer sur entré pour valider");
     }
     if (e.getKeyCode() == KeyEvent.VK_F1) {
       GestionQuestion gestionQuestion = this.game.getQuestion();
       this.voix.playText(
           gestionQuestion.getAleaObjectQuestion(gestionQuestion.getRdm()).afficherQuestion());
     }
     if (e.getKeyCode() == KeyEvent.VK_1) {
       this.voix.stop();
       this.voix.playText(answers.get(0));
       this.choixReponse = answers.get(0);
     }
     if (e.getKeyCode() == KeyEvent.VK_2) {
       this.voix.stop();
       this.voix.playText(answers.get(1));
       this.choixReponse = answers.get(1);
     }
     if (e.getKeyCode() == KeyEvent.VK_3) {
       this.voix.stop();
       this.voix.playText(answers.get(2));
       this.choixReponse = answers.get(2);
     }
     if (e.getKeyCode() == KeyEvent.VK_4) {
       this.voix.stop();
       this.voix.playText(answers.get(3));
       this.choixReponse = answers.get(3);
     }
     if (e.getKeyCode() == KeyEvent.VK_5) {
       this.voix.stop();
       this.voix.playText(answers.get(4));
       this.choixReponse = answers.get(4);
     }
     if (e.getKeyCode() == KeyEvent.VK_6) {
       this.voix.stop();
       this.voix.playText(answers.get(5));
       this.choixReponse = answers.get(5);
     }
     if (e.getKeyCode() == KeyEvent.VK_ENTER) {
       if (!choixReponse.equals(goodAnswer)) {
         this.clean();
         gc.weightx = 2;
         gc.weighty = 2;
         gc.gridx = 0;
         gc.gridy = 0;
         JPanel wrongAnswer = new WrongAnswer(this.goodAnswer, this.game);
         wrongAnswer.requestFocus();
         this.add(wrongAnswer, gc);
         this.revalidate();
         this.bonneReponse = false;
       } else {
         this.clean();
         gc.weightx = 2;
         gc.weighty = 2;
         gc.gridx = 0;
         gc.gridy = 0;
         JPanel goodAnswer = new GoodAnswer(this.game, 4);
         goodAnswer.requestFocus();
         this.add(goodAnswer, gc);
         this.revalidate();
         this.bonneReponse = true;
       }
       end = true;
     }
   } else {
     if (e.getKeyCode() == KeyEvent.VK_F2) {
       this.voix.playText(" Pour aller à la question suivante, veuillez appuyer sur entrée");
     }
     if (e.getKeyCode() == KeyEvent.VK_ENTER) {
       if (bonneReponse) {
         this.game.maj(4, true);
       } else {
         this.game.maj(0, false);
       }
     }
   }
 }
Пример #19
0
  public void run() {
    long lastTime = System.nanoTime();
    double unprocessed = 0;
    int frames = 0;
    long lastTimer1 = System.currentTimeMillis();

    try {
      init();
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }

    // if (!isMultiplayer) {
    // createLevel();
    // }

    int toTick = 0;

    long lastRenderTime = System.nanoTime();
    int min = 999999999;
    int max = 0;

    while (running) {
      if (!this.hasFocus()) {
        keys.release();
      }

      double nsPerTick = 1000000000.0 / framerate;
      boolean shouldRender = false;
      while (unprocessed >= 1) {
        toTick++;
        unprocessed -= 1;
      }

      int tickCount = toTick;
      if (toTick > 0 && toTick < 3) {
        tickCount = 1;
      }
      if (toTick > 20) {
        toTick = 20;
      }

      for (int i = 0; i < tickCount; i++) {
        toTick--;
        // long before = System.nanoTime();
        tick();
        // long after = System.nanoTime();
        // System.out.println("Tick time took " + (after - before) *
        // 100.0 / nsPerTick + "% of the max time");
        shouldRender = true;
      }
      // shouldRender = true;

      BufferStrategy bs = getBufferStrategy();
      if (bs == null) {
        createBufferStrategy(3);
        continue;
      }
      if (shouldRender) {
        frames++;
        Graphics g = bs.getDrawGraphics();

        Random lastRandom = TurnSynchronizer.synchedRandom;
        TurnSynchronizer.synchedRandom = null;

        render(g);

        TurnSynchronizer.synchedRandom = lastRandom;

        long renderTime = System.nanoTime();
        int timePassed = (int) (renderTime - lastRenderTime);
        if (timePassed < min) {
          min = timePassed;
        }
        if (timePassed > max) {
          max = timePassed;
        }
        lastRenderTime = renderTime;
      }

      long now = System.nanoTime();
      unprocessed += (now - lastTime) / nsPerTick;
      lastTime = now;

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      if (shouldRender) {
        if (bs != null) {
          bs.show();
        }
      }

      if (System.currentTimeMillis() - lastTimer1 > 1000) {
        lastTimer1 += 1000;
        fps = frames;
        frames = 0;
      }
    }
  }
Пример #20
0
  public void actionPerformed(ActionEvent e) {
    if (dados != null) {
      if (e.getSource() == dados.pane.rollButton) {
        Thread t =
            new Thread(
                () -> {
                  try {
                    Thread.sleep(3000);
                  } catch (InterruptedException e1) {
                    e1.printStackTrace();
                  }

                  if (Objects.equals(dados.pane.text.getText(), "3")) {
                    dados.label.setBounds(70, 316 + 50, 507, 41);
                    dados.label.setText("Tie, Roll again");
                    dados.label.setVisible(true);
                    try {
                      Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                      e1.printStackTrace();
                    }
                    b2.doClick();
                    dados.label.setBounds(70, 316 + 50, 507, 41);
                    dados.label.setText("Tie, Roll again");
                    dados.label.setVisible(true);
                  } else {
                    dados.label.setBounds(150, 316, 507, 41);
                    dados.pane.rollButton.setVisible(false);
                    dados.pane.setVisible(false);
                    try {
                      turno = new FileWriter("turno.txt");
                      pw = new PrintWriter(turno);
                    } catch (IOException e1) {
                      e1.printStackTrace();
                    }

                    if (Objects.equals(dados.pane.text.getText(), "1")) {
                      dados.label.setText("Congratulations , fate is on your side");
                      dados.label.setVisible(true);
                      try {
                        Thread.sleep(500);
                      } catch (InterruptedException e1) {
                        e1.printStackTrace();
                      }

                      dados.label.setText("Now select who is playing first");
                      dados.label.setBounds(295, 316, 507, 41);
                      add(dados.label);

                      Aifirst = new JButton();
                      Aifirst.setBounds(650, 400, 200, 200);
                      Aifirst.setIcon(new ImageIcon("seccond.png"));
                      add(Aifirst);

                      playerfirst = new JButton();
                      playerfirst.setBounds(250, 400, 200, 200);
                      playerfirst.setIcon(new ImageIcon("first.png"));
                      add(playerfirst);

                      player = new JLabel("Player");
                      player.setBounds(350, 620, 200, 30);
                      player.setAlignmentX(CENTER_ALIGNMENT);
                      player.setForeground(Color.WHITE);
                      add(player);

                      ai = new JLabel("Ai");
                      ai.setBounds(750, 620, 200, 30);
                      ai.setAlignmentX(CENTER_ALIGNMENT);
                      ai.setForeground(Color.WHITE);
                      add(ai);

                      playerfirst.addActionListener(this);
                      Aifirst.addActionListener(this);

                      repaint();
                      pw.println(1);
                    } else {
                      dados.label.setText("AI player gets the  first turn");
                      dados.pane.setVisible(true);
                      dados.label.setVisible(true);
                      dados.btnPlay.setVisible(true);
                      repaint();
                      pw.println(2);
                    }

                    try {
                      turno.close();
                    } catch (IOException e1) {
                      e1.printStackTrace();
                    }
                  }
                });
        t.start();
      }

      if (e.getSource() == Aifirst) {
        dados.pane.text.setText("2");
        dados.btnPlay.doClick();
      }

      if (e.getSource() == playerfirst) {
        dados.pane.text.setText("1");
        dados.btnPlay.doClick();
      }

      if (e.getSource() == dados.btnPlay) {
        try {
          player1 = new PlayGui(0, 0, Nombre1, this);
          Thread t =
              new Thread(
                  () -> {
                    try {
                      Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                      e1.printStackTrace();
                    }
                    if (Objects.equals(dados.pane.text.getText(), "2")) {
                      try {
                        player1.Aiturn();
                        player1.contTurn++;
                      } catch (IOException
                          | UnsupportedAudioFileException
                          | LineUnavailableException
                          | InterruptedException e1) {
                        e1.printStackTrace();
                      }
                    } else {
                      player1.firstPlayerTurn();
                    }
                  });
          t.start();
        } catch (IOException | UnsupportedAudioFileException | LineUnavailableException e1) {
          e1.printStackTrace();
        }

        PlayGui.player.pdeck.btnNewButton_1.addMouseListener(this);
        PlayGui.player.pdeck.btnNewButton.addMouseListener(this);
        PlayGui.player.pdeck.textField.addMouseListener(this);

        try {
          addbackground3(this);
        } catch (IOException e1) {
          e1.printStackTrace();
        }
        getContentPane().setBackground(new Color(153, 204, 204));
        getContentPane().setLayout(null);

        player1.repaint.addActionListener(this);
        add(player1);

        setVisible(true);
      }
    }

    if (e.getSource() == b2) {
      try {
        dados = new RollDice();
        addbackground4(this);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      getContentPane().setLayout(null);

      dados.pane.rollButton.addActionListener(this);
      dados.btnPlay.addActionListener(this);
      add(dados);

      setVisible(true);
    }

    if (player1 != null) {
      if (e.getSource() == player1.repaint) {
        repaint();
      }

      if (e.getSource() == accionarAgarreAutomatico) {
        if (this.player1.getPhaseActual() == 0) {
          if (player1.cardDrawn == 0) {
            if (PlayGui.player.pdeck.Deck.cardsLeft() != 0) {
              CardGui nueva = null;
              try {
                nueva = new CardGui(PlayGui.player.pdeck.Deck.extractCard(), 0, 0);
              } catch (IOException e1) {
                e1.printStackTrace();
              }
              appear(nueva);
              final CardGui finalNueva = nueva;
              Thread t1 =
                  new Thread(
                      () -> {
                        try {
                          Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                          e1.printStackTrace();
                        }
                        try {
                          PlayGui.player.hand.draw(finalNueva);
                        } catch (UnsupportedAudioFileException
                            | IOException
                            | LineUnavailableException e1) {
                          e1.printStackTrace();
                        }
                        repaint();
                      });
              t1.start();
            } else {
              doGameOver();
            }
          } else {
            JOptionPane.showMessageDialog(null, "Sorry , u can pick only a card per turn");
          }
        } else {
          JOptionPane.showMessageDialog(null, "Sorry , u can only pick cards on the draw phase");
        }
      }
    }
  }
Пример #21
0
  /**
   * A Test to guarantee that the Dancing UI bug will not rear its ugly head again. Basically, add a
   * component listener to the leftComponent of _docSplitPane and make certain its size does not
   * change while closing an OpenDefinitionsDocument outside the event thread.
   */
  public void testDancingUIFileClosed() throws IOException {
    /**
     * Maybe this sequence of calls should be incorporated into one function createTestDir(), which
     * would get the username and create the temporary directory. Only sticky part is deciding where
     * to put it, in FileOps maybe?
     */
    String user = System.getProperty("user.name");
    _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");
    File forceOpenClass1_file = new File(_tempDir, "ForceOpenClass1.java");
    String forceOpenClass1_string =
        "public class ForceOpenClass1 {\n"
            + "  ForceOpenClass2 class2;\n"
            + "  ForceOpenClass3 class3;\n\n"
            + "  public ForceOpenClass1() {\n"
            + "    class2 = new ForceOpenClass2();\n"
            + "    class3 = new ForceOpenClass3();\n"
            + "  }\n"
            + "}";

    IOUtil.writeStringToFile(forceOpenClass1_file, forceOpenClass1_string);
    forceOpenClass1_file.deleteOnExit();

    final ComponentAdapter listener =
        new ComponentAdapter() {
          public void componentResized(ComponentEvent event) {
            _testFailed = true;
            fail("testDancingUI: Open Documents List danced!");
          }
        };
    final SingleDisplayModelFileClosedListener closeListener =
        new SingleDisplayModelFileClosedListener();

    _closeDone = false;
    Utilities.invokeAndWait(
        new Runnable() {
          public void run() {
            //       _frame.setVisible(true);
            _frame.pack();
            _frame.addComponentListenerToOpenDocumentsList(listener);
            _frame.open(
                new FileOpenSelector() {
                  public File[] getFiles() {
                    File[] return_me = new File[1];
                    return_me[0] = new File(_tempDir, "ForceOpenClass1.java");
                    return return_me;
                  }
                });
            _frame.getModel().addListener(closeListener);
          }
        });
    Utilities.clearEventQueue();

    /* Asynchronously close the file */
    Utilities.invokeLater(
        new Runnable() {
          public void run() {
            _frame.getCloseButton().doClick();
          }
        });

    _log.log("Waiting for file closing");

    synchronized (_closeLock) {
      try {
        while (!_closeDone) _closeLock.wait();
      } catch (InterruptedException e) {
        fail(e.toString());
      }
    }

    if (!IOUtil.deleteRecursively(_tempDir)) {
      System.err.println(
          "Couldn't fully delete directory " + _tempDir.getAbsolutePath() + "\nDo it by hand.\n");
    }
    _log.log("testDancingUIFileClosed completed");
  }
Пример #22
0
  /**
   * A Test to guarantee that the Dancing UI bug will not rear its ugly head again. Basically, add a
   * component listener to the leftComponent of _docSplitPane and make certain its size does not
   * change while compiling a class which depends on another class.
   */
  public void testDancingUIFileOpened() throws IOException {
    // System.out.println("DEBUG: Entering messed up test");
    /**
     * Maybe this sequence of calls should be incorporated into one function createTestDir(), which
     * would get the username and create the temporary directory. Only sticky part is deciding where
     * to put it, in FileOps maybe?
     */
    _log.log("Starting testingDancingUIFileOpened");

    final GlobalModel _model = _frame.getModel();

    String user = System.getProperty("user.name");
    _tempDir = IOUtil.createAndMarkTempDirectory("DrJava-test-" + user, "");

    File forceOpenClass1_file = new File(_tempDir, "ForceOpenClass1.java");
    String forceOpenClass1_string =
        "public class ForceOpenClass1 {\n"
            + "  ForceOpenClass2 class2;\n"
            + "  ForceOpenClass3 class3;\n\n"
            + "  public ForceOpenClass1() {\n"
            + "    class2 = new ForceOpenClass2();\n"
            + "    class3 = new ForceOpenClass3();\n"
            + "  }\n"
            + "}";

    File forceOpenClass2_file = new File(_tempDir, "ForceOpenClass2.java");
    String forceOpenClass2_string = "public class ForceOpenClass2 {\n" + "  inx x = 4;\n" + "}";

    File forceOpenClass3_file = new File(_tempDir, "ForceOpenClass3.java");
    String forceOpenClass3_string =
        "public class ForceOpenClass3 {\n" + "  String s = \"asf\";\n" + "}";

    IOUtil.writeStringToFile(forceOpenClass1_file, forceOpenClass1_string);
    IOUtil.writeStringToFile(forceOpenClass2_file, forceOpenClass2_string);
    IOUtil.writeStringToFile(forceOpenClass3_file, forceOpenClass3_string);
    forceOpenClass1_file.deleteOnExit();
    forceOpenClass2_file.deleteOnExit();
    forceOpenClass3_file.deleteOnExit();

    _log.log("DancingUIFileOpened Set Up");

    // _frame.setVisible(true);

    // set up listeners and signal flags

    final ComponentAdapter listener =
        new ComponentAdapter() {
          public void componentResized(ComponentEvent event) {
            _testFailed = true;
            fail("testDancingUI: Open Documents List danced!");
          }
        };
    final SingleDisplayModelFileOpenedListener openListener =
        new SingleDisplayModelFileOpenedListener();
    final SingleDisplayModelCompileListener compileListener =
        new SingleDisplayModelCompileListener();

    _openDone = false;

    Utilities.invokeAndWait(
        new Runnable() {
          public void run() {
            //       _frame.setVisible(true);
            _frame.pack();
            _frame.addComponentListenerToOpenDocumentsList(listener);
          }
        });
    Utilities.clearEventQueue();

    _model.addListener(openListener);

    _log.log("opening file");

    Utilities.invokeLater(
        new Runnable() {
          public void run() {
            _frame.open(
                new FileOpenSelector() {
                  public File[] getFiles() {
                    File[] return_me = new File[1];
                    return_me[0] = new File(_tempDir, "ForceOpenClass1.java");
                    return return_me;
                  }
                });
          }
        });
    Utilities.clearEventQueue();

    /* wait until file has been open and active document changed. */
    synchronized (_openLock) {
      try {
        while (!_openDone) _openLock.wait();
      } catch (InterruptedException e) {
        fail(e.toString());
      }
    }

    _model.removeListener(openListener);

    _log.log("File opened");

    _compileDone = false;
    _model.addListener(compileListener);

    // save and compile the new file asynchronously

    Utilities.invokeLater(
        new Runnable() {
          public void run() {
            _log.log("saving all files");
            _frame._saveAll();
            _log.log("invoking compileAll action");
            _frame.getCompileAllButton().doClick();
          }
        });
    Utilities.clearEventQueue();

    synchronized (_compileLock) {
      try {
        while (!_compileDone) _compileLock.wait();
      } catch (InterruptedException e) {
        fail(e.toString());
      }
    }
    _log.log("File saved and compiled");

    if (!IOUtil.deleteRecursively(_tempDir))
      System.err.println(
          "Couldn't fully delete directory " + _tempDir.getAbsolutePath() + "\nDo it by hand.\n");

    _log.log("testDancingUIFileOpened completed");
  }
Пример #23
0
  public static void main(String[] args) {
    // TODO main
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("h", "help"), "Show this help dialog.");
    OptionSpec<String> serverOption =
        parser
            .acceptsAll(Arrays.asList("s", "server"), "Server to join.")
            .withRequiredArg()
            .describedAs("server-address[:port]");
    OptionSpec<String> proxyOption =
        parser
            .acceptsAll(
                Arrays.asList("P", "proxy"),
                "SOCKS proxy to use. Ignored in presence of 'socks-proxy-list'.")
            .withRequiredArg()
            .describedAs("proxy-address");
    OptionSpec<String> ownerOption =
        parser
            .acceptsAll(
                Arrays.asList("o", "owner"), "Owner of the bot (username of in-game control).")
            .withRequiredArg()
            .describedAs("username");
    OptionSpec<?> offlineOption =
        parser.acceptsAll(
            Arrays.asList("O", "offline"),
            "Offline-mode. Ignores 'password' and 'account-list' (will "
                + "generate random usernames if 'username' is not supplied).");
    OptionSpec<?> autoRejoinOption =
        parser.acceptsAll(Arrays.asList("a", "auto-rejoin"), "Auto-rejoin a server on disconnect.");
    OptionSpec<Integer> loginDelayOption =
        parser
            .acceptsAll(
                Arrays.asList("d", "login-delay"),
                "Delay between bot joins, in milliseconds. 5000 is "
                    + "recommended if not using socks proxies.")
            .withRequiredArg()
            .describedAs("delay")
            .ofType(Integer.class);
    OptionSpec<Integer> botAmountOption =
        parser
            .acceptsAll(
                Arrays.asList("b", "bot-amount"),
                "Amount of bots to join. Must be <= amount of accounts.")
            .withRequiredArg()
            .describedAs("amount")
            .ofType(Integer.class);
    OptionSpec<String> protocolOption =
        parser
            .accepts(
                "protocol",
                "Protocol version to use. Can be either protocol number or Minecraft version.")
            .withRequiredArg();
    OptionSpec<?> protocolsOption =
        parser.accepts("protocols", "List available protocols and exit.");

    OptionSpec<String> accountListOption =
        parser
            .accepts(
                "account-list",
                "File containing a list of accounts, in username/email:password format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> socksProxyListOption =
        parser
            .accepts(
                "socks-proxy-list",
                "File containing a list of SOCKS proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> httpProxyListOption =
        parser
            .accepts(
                "http-proxy-list",
                "File containing a list of HTTP proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> captchaListOption =
        parser
            .accepts("captcha-list", "File containing a list of chat baised captcha to bypass.")
            .withRequiredArg()
            .describedAs("file");

    OptionSet options;
    try {
      options = parser.parse(args);
    } catch (OptionException exception) {
      try {
        parser.printHelpOn(System.out);
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
      return;
    }

    if (options.has("help")) {
      printHelp(parser);
      return;
    }
    if (options.has(protocolsOption)) {
      System.out.println("Available protocols:");
      for (ProtocolProvider provider : ProtocolProvider.getProviders())
        System.out.println(
            "\t"
                + provider.getMinecraftVersion()
                + " ("
                + provider.getSupportedVersion()
                + "): "
                + provider.getClass().getName());
      System.out.println(
          "If no protocols are listed above, you may attempt to specify a protocol version in case the provider is actually in the class-path.");
      return;
    }

    final boolean offline = options.has(offlineOption);
    final boolean autoRejoin = options.has(autoRejoinOption);

    final List<String> accounts;
    if (options.has(accountListOption)) {
      accounts = loadAccounts(options.valueOf(accountListOption));
    } else if (!offline) {
      System.out.println("Option 'accounts' must be supplied in " + "absence of option 'offline'.");
      printHelp(parser);
      return;
    } else accounts = null;

    final List<String> captcha;
    if (options.has(captchaListOption)) readCaptchaFile(options.valueOf(captchaListOption));

    final String server;
    if (!options.has(serverOption)) {
      System.out.println("Option 'server' required.");
      printHelp(parser);
      return;
    } else server = options.valueOf(serverOption);

    final String owner;
    if (!options.has(ownerOption)) {
      System.out.println("Option 'owner' required.");
      printHelp(parser);
      return;
    } else owner = options.valueOf(ownerOption);

    final int protocol;
    if (options.has(protocolOption)) {
      String protocolString = options.valueOf(protocolOption);
      int parsedProtocol;
      try {
        parsedProtocol = Integer.parseInt(protocolString);
      } catch (NumberFormatException exception) {
        ProtocolProvider foundProvider = null;
        for (ProtocolProvider provider : ProtocolProvider.getProviders())
          if (protocolString.equals(provider.getMinecraftVersion())) foundProvider = provider;
        if (foundProvider == null) {
          System.out.println("No provider found for Minecraft version '" + protocolString + "'.");
          return;
        } else parsedProtocol = foundProvider.getSupportedVersion();
      }
      protocol = parsedProtocol;
    } else protocol = MinecraftBot.LATEST_PROTOCOL;

    final List<String> socksProxies;
    if (options.has(socksProxyListOption))
      socksProxies = loadProxies(options.valueOf(socksProxyListOption));
    else socksProxies = null;
    final boolean useProxy = socksProxies != null;

    final List<String> httpProxies;
    if (options.has(httpProxyListOption))
      httpProxies = loadLoginProxies(options.valueOf(httpProxyListOption));
    else if (!offline && accounts != null) {
      System.out.println(
          "Option 'http-proxy-list' required if " + "option 'account-list' is supplied.");
      printHelp(parser);
      return;
    } else httpProxies = null;

    final int loginDelay;
    if (options.has(loginDelayOption)) loginDelay = options.valueOf(loginDelayOption);
    else loginDelay = 0;

    final int botAmount;
    if (!options.has(botAmountOption)) {
      System.out.println("Option 'bot-amount' required.");
      printHelp(parser);
      return;
    } else botAmount = options.valueOf(botAmountOption);

    initGui();
    while (!sessions.get()) {
      synchronized (sessions) {
        try {
          sessions.wait(5000);
        } catch (InterruptedException exception) {
        }
      }
    }

    final Queue<Runnable> lockQueue = new ArrayDeque<Runnable>();

    ExecutorService service = Executors.newFixedThreadPool(botAmount + (loginDelay > 0 ? 1 : 0));
    final Object firstWait = new Object();
    if (loginDelay > 0) {
      service.execute(
          new Runnable() {
            @Override
            public void run() {
              synchronized (firstWait) {
                try {
                  firstWait.wait();
                } catch (InterruptedException exception) {
                }
              }
              while (true) {
                try {
                  Thread.sleep(loginDelay);
                } catch (InterruptedException exception) {
                }
                synchronized (lockQueue) {
                  if (lockQueue.size() > 0) {
                    Runnable thread = lockQueue.poll();
                    synchronized (thread) {
                      thread.notifyAll();
                    }
                    lockQueue.offer(thread);
                  } else continue;
                }
                while (!sessions.get()) {
                  synchronized (sessions) {
                    try {
                      sessions.wait(5000);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
              }
            }
          });
    }
    final List<String> accountsInUse = new ArrayList<String>();
    final Map<String, AtomicInteger> workingProxies = new HashMap<String, AtomicInteger>();
    for (int i = 0; i < botAmount; i++) {
      final int botNumber = i;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              if (loginDelay > 0)
                synchronized (lockQueue) {
                  lockQueue.add(this);
                }
              Random random = new Random();

              if (!offline) {
                AuthService authService = new LegacyAuthService();
                boolean authenticated = false;
                user:
                while (true) {
                  if (authenticated) {
                    authenticated = false;
                    sessionCount.decrementAndGet();
                  }
                  Session session = null;
                  String loginProxy;
                  String account = accounts.get(random.nextInt(accounts.size()));
                  synchronized (accountsInUse) {
                    if (accountsInUse.size() == accounts.size()) System.exit(0);
                    while (accountsInUse.contains(account))
                      account = accounts.get(random.nextInt(accounts.size()));
                    accountsInUse.add(account);
                  }
                  String[] accountParts = account.split(":");
                  while (true) {
                    while (!sessions.get()) {
                      synchronized (sessions) {
                        try {
                          sessions.wait(5000);
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    synchronized (workingProxies) {
                      Iterator<String> iterator = workingProxies.keySet().iterator();
                      if (iterator.hasNext()) loginProxy = iterator.next();
                      else loginProxy = httpProxies.get(random.nextInt(httpProxies.size()));
                      ;
                    }
                    try {
                      session =
                          authService.login(
                              accountParts[0],
                              accountParts[1],
                              toProxy(loginProxy, Proxy.Type.HTTP));
                      // addAccount(session);
                      synchronized (workingProxies) {
                        AtomicInteger count = workingProxies.get(loginProxy);
                        if (count != null) count.set(0);
                        else workingProxies.put(loginProxy, new AtomicInteger());
                      }
                      sessionCount.incrementAndGet();
                      authenticated = true;
                      break;
                    } catch (IOException exception) {
                      synchronized (workingProxies) {
                        workingProxies.remove(loginProxy);
                      }
                      System.err.println("[Bot" + botNumber + "] " + loginProxy + ": " + exception);
                    } catch (AuthenticationException exception) {
                      if (exception.getMessage().contains("Too many failed logins")) {
                        synchronized (workingProxies) {
                          AtomicInteger count = workingProxies.get(loginProxy);
                          if (count != null && count.incrementAndGet() >= 5)
                            workingProxies.remove(loginProxy);
                        }
                      }
                      System.err.println("[Bot" + botNumber + "] " + loginProxy + ": " + exception);
                      continue user;
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] " + session);
                  while (!joins.get()) {
                    synchronized (joins) {
                      try {
                        joins.wait(5000);
                      } catch (InterruptedException exception) {
                      }
                    }
                  }
                  if (loginDelay > 0) {
                    synchronized (this) {
                      try {
                        synchronized (firstWait) {
                          firstWait.notifyAll();
                        }
                        wait();
                      } catch (InterruptedException exception) {
                      }
                    }
                  }

                  while (true) {
                    String proxy =
                        useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                    try {
                      DarkBotMCSpambot bot =
                          new DarkBotMCSpambot(
                              generateData(
                                  server,
                                  session.getUsername(),
                                  session.getPassword(),
                                  authService,
                                  session,
                                  protocol,
                                  null,
                                  proxy),
                              owner);
                      while (bot.getBot().isConnected()) {
                        try {
                          Thread.sleep(500);
                        } catch (InterruptedException exception) {
                          exception.printStackTrace();
                        }
                      }
                      if (!autoRejoin) break;
                    } catch (Exception exception) {
                      exception.printStackTrace();
                      System.out.println(
                          "["
                              + session.getUsername()
                              + "] Error connecting: "
                              + exception.getCause().toString());
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] Account failed");
                }
              } else {
                while (true) {
                  String proxy =
                      useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                  try {
                    String username;
                    if (accounts != null) {
                      username = accounts.get(random.nextInt(accounts.size())).split(":")[0];
                      synchronized (accountsInUse) {
                        while (accountsInUse.contains(username))
                          username = accounts.get(random.nextInt(accounts.size()));
                        accountsInUse.add(username);
                      }
                    } else username = Util.generateRandomString(10 + random.nextInt(6));
                    if (loginDelay > 0) {
                      synchronized (this) {
                        try {
                          synchronized (firstWait) {
                            firstWait.notifyAll();
                          }
                          wait();
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    DarkBotMCSpambot bot =
                        new DarkBotMCSpambot(
                            generateData(server, username, null, null, null, protocol, null, proxy),
                            owner);
                    while (bot.getBot().isConnected()) {
                      try {
                        Thread.sleep(500);
                      } catch (InterruptedException exception) {
                        exception.printStackTrace();
                      }
                    }
                    if (!autoRejoin) break;
                    else continue;
                  } catch (Exception exception) {
                    System.out.println(
                        "[Bot" + botNumber + "] Error connecting: " + exception.toString());
                  }
                }
              }
            }
          };
      service.execute(runnable);
    }
    service.shutdown();
    while (!service.isTerminated()) {
      try {
        service.awaitTermination(9000, TimeUnit.DAYS);
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
    }
    System.exit(0);
  }
Пример #24
0
  ////////////////////////////////////////////////////////////
  // 			OVERRIDEN
  ////////////////////////////////////////////////////////////
  @Override
  public void actionPerformed(ActionEvent e) {
    // System.out.println( "timer event (1) !");
    if (e.getActionCommand().equals("remote bead animator")) {

      availableBeads[currentBead - 1].animation(5);

      int tolerance = 5;
      if (availableBeads[currentBead - 1].getY()
          > (int)
              (pegs[insertedInPegNum - 1].getBounds().getMaxY()
                  - availableBeads[currentBead - 1].getBounds().getHeight()
                  - (availableBeads[currentBead - 1].getBounds().getHeight() + tolerance)
                      * (pegs[insertedInPegNum - 1].amountOfBeads2() - 1))) {

        // here the remote player finished moving
        remoteBeadAnimTimer.stop();

        // keep reading from refereee!!!!!!
        try {
          receiveFromReferee();
        } catch (InterruptedException e1) {
          e1.printStackTrace();
        }
      } // end if
      repaint(); // happens every time the animationTimer triggers an event

    } else if (e.getActionCommand().equals("images are loaded")) {
      // images are loaded, then just paint them
      // this only happens one time after user
      // clicked in new game menu
      repaint();
    } else if (e.getActionCommand().equals("is win_lose")) {
      // images are loaded, then just paint them
      // this only happens one time after user
      // clicked in new game menu
      repaint();
      startImageLoader(LOSE_IMAGE_FILE);
      updateWhenLoaded.stop();
    } else if (e.getActionCommand().equals("Gertrude vs Computer")) {

      // starts the worker that receives from refereee
      try {
        receiveFromReferee(); // this is a worker
      } catch (InterruptedException e1) {
        System.out.println("COuldnt receive from referee");
      }

    } else if (e.getActionCommand().equals("animation")) {
      availableBeads[currentBead - 1].animation(5);

      int tolerance = 5;
      if (availableBeads[currentBead - 1].getY()
          > pegs[insertedInPegNum - 1].getBounds().getMaxY()
              - availableBeads[currentBead - 1].getBounds().getHeight()
              - (availableBeads[currentBead - 1].getBounds().getWidth() + tolerance)
                  * (pegs[insertedInPegNum - 1].amountOfBeads2() - 1)) {

        animationTimer.stop();
        // send to the referee the user's move
        System.out.println("GUI, I sent " + insertedInPegNum);
        sendToReferee(Integer.toString(insertedInPegNum));

        // here the local player finished moving a piece,
        // now its turn of the remote player to go!
        // starts the worker that receives from refereee
        try {
          receiveFromReferee(); // this is a worker
        } catch (InterruptedException e1) {
          System.out.println("Couldnt receive from referee");
        }
      } // end if
      repaint();
    } // end if-else
  }