Exemplo n.º 1
1
 static void rand() // 중복되지 않는 랜덤 숫자배열 두개 만들기
     {
   int su = 0; // 난수 발생시 저장할 변수
   boolean bDash = false; // 중복여부 확인
   for (int i = 0; i < 75; i++) {
     bDash = true;
     while (bDash) // 난수발생, 중복 학인
     {
       su = (int) (Math.random() * 75) + 1; // 판 크기+10개(상대가 못맞출 수도 있게)의 난수 입력
       bDash = false;
       for (int j = 0; j < i; j++) {
         if (numArr1[j] == su) {
           bDash = true; // 중복이 있으면 멈추고 while문을 다시 수행(랜덤값을 다시 줌)
           break;
         }
       }
     }
     numArr1[i] = su;
   }
   for (int i = 0; i < 75; i++) {
     bDash = true;
     while (bDash) // 난수발생, 중복 학인
     {
       su = (int) (Math.random() * 75) + 1; // 판 크기+10개(상대가 못맞출 수도 있게)의 난수 입력
       bDash = false;
       for (int j = 0; j < i; j++) {
         if (numArr2[j] == su) {
           bDash = true; // 중복이 있으면 멈추고 while문을 다시 수행(랜덤값을 다시 줌)
           break;
         }
       }
     }
     numArr2[i] = su;
   }
 }
  /** Start the background thread. */
  public void start() {
    // create a random list of cities

    cities = new City[TravelingSalesman.CITY_COUNT];
    for (int i = 0; i < TravelingSalesman.CITY_COUNT; i++) {
      cities[i] =
          new City(
              (int) (Math.random() * (getBounds().width - 10)),
              (int) (Math.random() * (getBounds().height - 60)));
    }

    // create the initial chromosomes

    chromosomes = new Chromosome[TravelingSalesman.POPULATION_SIZE];
    for (int i = 0; i < TravelingSalesman.POPULATION_SIZE; i++) {
      chromosomes[i] = new Chromosome(cities);
      chromosomes[i].setCut(cutLength);
      chromosomes[i].setMutation(TravelingSalesman.MUTATION_PERCENT);
    }
    Chromosome.sortChromosomes(chromosomes, TravelingSalesman.POPULATION_SIZE);

    // start up the background thread
    started = true;
    map.update(map.getGraphics());

    generation = 0;

    if (worker != null) worker = null;
    worker = new Thread(this);
    // worker.setPriority(Thread.MIN_PRIORITY);
    worker.start();
  }
Exemplo n.º 3
0
  private void spawnRandomers() {
    for (int i = 0; i < randomN; i++) {
      float x = (float) Math.random() * width;
      float y = (float) Math.random() * height;
      float r =
          (float)
              Math.sqrt(
                  Math.pow(((Player) players.get(0)).getX() - x, 2)
                      + Math.pow(((Player) players.get(0)).getY() - x, 2));

      while (r < distanceLimit) {
        x = (float) Math.random() * width;
        y = (float) Math.random() * height;
        r =
            (float)
                Math.sqrt(
                    Math.pow(((Player) players.get(0)).getX() - x, 2)
                        + Math.pow(((Player) players.get(0)).getY() - y, 2));
      }

      enemies.add(new EnemyTypes.Random(x, y, 0.5f, borders));
    }

    spawnRandomersB = false;
  }
Exemplo n.º 4
0
  @Override
  public void actionPerformed(ActionEvent e) {

    if (firstClick) {
      firstClick = false;
      lastIcon = buttons[0][0].getIcon();
      buttons[0][0].setIcon(null);
      for (int i = 0; i < 10000; i++) {
        int zufallY = (int) ((Math.random() * YY) + 0);
        int zufallX = (int) ((Math.random() * XX) + 0);
        switchButton(zufallY, zufallX);
      }
      // ToDo: unwiederrufbare Operationen vermeiden?
      // funktion klären und abfangen
      /*while(lastButton % XX != 0)
          switchButton(lastButton-1);
      while (lastButton != "00")
          switchButton(lastButton-XX);*/

    } else {
      PuzzButton tmp = (PuzzButton) e.getSource();
      int posY = tmp.getPosY();
      int posX = tmp.getPosX();

      switchButton(posY, posX);
      if (isDone()) {
        buttons[0][0].setIcon(lastIcon);
        firstClick = true;
      }
    }
  }
Exemplo n.º 5
0
  /**
   * Spawn a character on the map
   *
   * @param MiX Minimum X value
   * @param MiY Minimum Y value
   * @param MaX Maximum X value
   * @param MaY Maximum Y value
   */
  public void Spawn(int MiX, int MiY, int MaX, int MaY) {
    double Nx = 0, Ny = 0;

    // Random coordinate
    Nx = Math.random() * MaX + MiX;
    Ny = Math.random() * MaY + MiY;

    // Store block number
    int BNum = MAP.elementAt(0).getBlockNum(Nx + W / 2, Ny + H / 2);

    // if invalid block number
    if (BNum == -1) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if invalid surface
    else if (!isValidSurface(MAP.elementAt(0).Fill[BNum])) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if colliding with something
    else if (this.Collision(Nx + W / 2, Ny + H / 2)) {
      Spawn(MiX, MiY, MaX, MaY);
    } else {
      X = Nx;
      Y = Ny;
    }
  }
Exemplo n.º 6
0
  // Proceso para posicionar las imagenes en el concentrece
  public void cargarImagenes() {
    int x, y = 0;
    int numero = -1;
    double x1, y1 = 0;
    ficha = new int[a][b];
    // Incializacion de la matriz entera en -1
    for (int i = 0; i < getA(); i++) {
      for (int j = 0; j < getB(); j++) {
        ficha[i][j] = -1;
      }
    }

    // Proceso de introduccion de imagenes en posiciones aleatorias para
    // obtener mas variaciones del juego
    for (int i = 0; i < getA(); i++) {
      for (int j = 0; j < getB(); j++) {
        do {
          x1 = Math.random() * getA();
          y1 = Math.random() * getB();
          x = (int) x1;
          y = (int) y1;
        } while (ficha[x][y] != -1);
        numero++;
        if (numero == getC()) {
          numero = 0;
        }
        ficha[x][y] = numero;
        parejas[i][j].setIcon(vacio);
      }
    }
  }
Exemplo n.º 7
0
 public void update(double prob_slowdown, double prob_create) {
   int i = 0;
   while (i < LENGTH && speed[i] == -1) i++;
   while (i < LENGTH) {
     if (Math.random() <= prob_slowdown && speed[i] > 0) speed[i]--;
     else if (speed[i] < MAXSPEED) speed[i]++;
     int inext = i + 1;
     while (inext < LENGTH && speed[inext] == -1) inext++;
     if (inext < LENGTH) {
       if (speed[i] >= inext - i) speed[i] = inext - i - 1;
     }
     if (speed[i] > 0) {
       if (i + speed[i] < LENGTH) {
         int ni = i + speed[i];
         speed[ni] = speed[i];
         colors[ni] = colors[i];
       }
       speed[i] = -1;
     }
     i = inext;
   }
   if (Math.random() <= prob_create && speed[0] == -1) {
     speed[0] = (int) (5.99 * Math.random());
     colors[0] = ++count % 10 == 0 ? Color.red : Color.black;
   }
 }
Exemplo n.º 8
0
  /** @param override true if should kill even if invulerable, false if not */
  public void kill(boolean override) {
    if (!override) {
      if (star || invulerable || piped) return;
    }
    deathPos.setLocation(pos);
    if (deathPos.y < 0) {
      deathPos.y = 0;
    }
    if (metal) {
      metal = false;
      startInvulnerable();
      invulerableTime = 3000 / 15;
      Point2D.Double v = new Point2D.Double(Math.random() * 8 - 4, Math.random() * 4 + 7);

      TMetalCap cap = new TMetalCap();
      cap.setPos(pos.x, pos.y);
      cap.kill(v);
      this.addSpawn(cap);
      return;
    }
    cape = false;
    dead = true;
    numBullets = 0;
    falling = false;
    acc = new Point2D.Double();
    vel = new Point2D.Double();
    deadTime = 25;
  }
Exemplo n.º 9
0
 // -------------------------------------------------------------------------------------------------------------------------------------------------------
 // Decorations
 public void newDecos() {
   int prob = (int) (Math.random() * 100); // randomly spawnst he decoration
   if (prob == 1) {
     if (decoList.size() < 1) {
       int prob2 = (int) (Math.random() * 2);
       if (prob2 == 1) { // right side or left side
         decoList.add(new Decorations(-700, (int) (backy * 0.1) % 23080, false));
       } else {
         decoList.add(new Decorations(-700, (int) (backy * 0.1) % 23080, true));
       }
     }
   }
   Boolean check = true;
   for (Decorations i : decoList) {
     if (i.getYTop() >= 2000) {
       check = false;
       break;
     }
   }
   if (check == false
       && decoList.size()
           > 0) { // theres only on in the lsit but for consitency we kept it as a list
     decoList.remove(0);
   }
 }
Exemplo n.º 10
0
  public void reset() {

    // init the location of the rocket to the center.
    rocketXPos = getWidth2() / 2;
    rocketYPos = getHeight2() / 2;
    // rocket direction
    rocketRight = true;
    // rocket speed.
    rocketXSpeed = 0;
    rocketYSpeed = 0;
    rocketMaxSpeed = 10;
    // rocket lives
    rocketLife = 3;
    // star position.
    starXPos = new int[numStars];
    starYPos = new int[numStars];
    starActive = new boolean[numStars];

    for (int index = 0; index < numStars; index++) {
      starXPos[index] = (int) (Math.random() * getWidth2());
      starYPos[index] = (int) (Math.random() * getHeight2());
      starActive[index] = true;
    }
    // score stuff
    score = 0;
    // missile stuff
    missile = new Missile[Missile.numMissile];
    for (int index = 0; index < missile.length; index++) {
      missile[index] = new Missile();
    }
    Missile.currentIndex = 0;
    starHit = -1;
    gameOver = false;
  }
Exemplo n.º 11
0
  private void DoAI(int pnum) {
    int[] dx = {0, 1, 0, -1};
    int[] dy = {-1, 0, 1, 0};
    int tdir;

    if (palive[pnum] != 1) return;
    if (map[(px[pnum] + dx[pdir[pnum]]) + (py[pnum] + dy[pdir[pnum]]) * SIZE_X] != 0) {
      if (Math.random() > 0.5) {
        tdir = (pdir[pnum] + 1) % 4;
        if (map[(px[pnum] + dx[tdir]) + (py[pnum] + dy[tdir]) * SIZE_X] == 0) pdir[pnum] = tdir;
        else pdir[pnum] = (pdir[pnum] + 3) % 4;
      } else {
        tdir = (pdir[pnum] + 3) % 4;
        if (map[(px[pnum] + dx[tdir]) + (py[pnum] + dy[tdir]) * SIZE_X] == 0) pdir[pnum] = tdir;
        else pdir[pnum] = (pdir[pnum] + 1) % 4;
      }
    } else if (Math.random() > 0.985) {
      if (Math.random() > 0.5) {
        tdir = (pdir[pnum] + 1) % 4;
        if (map[(px[pnum] + dx[tdir]) + (py[pnum] + dy[tdir]) * SIZE_X] == 0) pdir[pnum] = tdir;
      } else {
        tdir = (pdir[pnum] + 3) % 4;
        if (map[(px[pnum] + dx[tdir]) + (py[pnum] + dy[tdir]) * SIZE_X] == 0) pdir[pnum] = tdir;
      }
    }
  }
Exemplo n.º 12
0
  public static void main(String[] args) {
    Plot2DPanel p = new Plot2DPanel();

    double[] X = new double[10];
    double[] Y = new double[10];
    for (int j = 0; j < X.length; j++) {
      X[j] = j;
      Y[j] = Math.random();
    }
    p.addStaircasePlot("toto", X, Y);

    new FrameView(p).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Color[] c = new Color[10];

    p = new Plot2DPanel();

    X = new double[10];
    Y = new double[10];
    for (int j = 0; j < X.length; j++) {
      X[j] = j;
      Y[j] = Math.random();
      c[j] = new Color((int) (Math.random() * 0x1000000));
    }
    p.addStaircasePlot("toto", c, X, Y);

    new FrameView(p).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
 /**
  * This method is what calculates the amount of health baron has and how big the health bar is. It
  * generates a random number, which varies under the set circumstances, which is the number used
  * to subtract from barons health. That number is that converted into a percentage, then
  * multiplied by 500 to get the length of the health bar. This method gets called every 0.6
  * seconds. When Barons health decreases, it is suppose to represent a player doing damage to it
  * overtime, but since making that happen is a bit too complicated, it simply subtracts an amount
  * of his health to represent a player doing damage.
  */
 public void hp() {
   if (!smiteDone) {
     hpDecrease = (int) ((Math.random() * 300) + 100);
     if (baronHealth <= smiteDmg + 200) hpDecrease = (int) (Math.random() * 100);
     hpDecreaseDec = ((((baronHealth - hpDecrease) / maxHealth)) * 500);
     baronHealth -= hpDecrease;
   }
 }
Exemplo n.º 14
0
 /**
  * ****************************************************************************
  * setTargetLocation() method. * Selects random place to aim for. *
  * ****************************************************************************
  */
 void setTargetLocation() {
   if (m_targetPosSampleInterval == 0 || reachedTarget() == true) {
     // Choose a new place to aim for
     m_targetPos.x = (int) (Math.random() * 512.0); // TBD use applet size instead
     m_targetPos.y = (int) (Math.random() * 512.0); // TBD use applet size instead
     m_targetPosSampleInterval = m_targetPosSampleIntervalReset;
   } else m_targetPosSampleInterval--;
 }
Exemplo n.º 15
0
 private void addTile() {
   List<Tile> list = availableSpace();
   if (!availableSpace().isEmpty()) {
     int index = (int) (Math.random() * list.size()) % list.size();
     Tile emptyTime = list.get(index);
     emptyTime.value = Math.random() < 0.9 ? 2 : 4;
   }
 }
Exemplo n.º 16
0
 private String getRandWord(int max_length) {
     int length = (int) Math.random() * max_length + 1;
     String ret = "";
     for (int _ = 0; _ < length; _++) {
         ret += characters.charAt((int) Math.random() * numChars);
     }
     return ret;
 }
Exemplo n.º 17
0
 public Ball(Color c, int x, int y) {
   color = c;
   this.x = x;
   this.y = y;
   dx = (Math.random() < .5) ? 1 : -1;
   dy = (Math.random() < .5) ? 1 : -1;
   speed = 4;
 }
Exemplo n.º 18
0
 public void randomKernel(double w) {
   weight = w;
   kmx = xsiz * Math.random();
   kmy = ysiz * Math.random();
   ksx = xsiz / 4 + mins;
   ksy = ysiz / 4 + mins;
   ksxy = 0;
 }
Exemplo n.º 19
0
 protected void fillArray() {
   for (int i = 0; i < 1000; i++) {
     int randomR = (int) (Math.random() * cells.length);
     int randomC = (int) (Math.random() * cells[0].length);
     lastGeneration[randomR][randomC] = new Cell(1);
     cells[randomR][randomC] = new Cell(1);
   }
 }
Exemplo n.º 20
0
 // Starts this die rolling
 public void roll() {
   super.roll();
   int width = tableRight - tableLeft;
   int height = tableBottom - tableTop;
   xCenter = tableLeft;
   yCenter = tableTop + height / 2;
   xSpeed = width * (Math.random() + 1) * speedFactor;
   ySpeed = height * (Math.random() - .5) * 2. * speedFactor;
 }
Exemplo n.º 21
0
 public static void main(String[] args) {
   double[] X = new double[500];
   for (int i = 0; i < X.length; i++) {
     X[i] = Math.random() + Math.random();
   }
   Plot2DPanel p = new Plot2DPanel("SOUTH");
   p.addHistogramPlot("test", X, 10);
   new FrameView(p);
 }
Exemplo n.º 22
0
 public Ball(Color c, Bar b) {
   color = c;
   bar = b;
   double x = (Cwiczenie5_4.SIZE.width - SIZE) * Math.random();
   double y = (Cwiczenie5_4.SIZE.height - Bar.SIZE.height - SIZE) * Math.random();
   pos = new Point((int) x, (int) y);
   int d = MAX_VEL - MIN_VEL;
   dy = (-1) * (int) (d * Math.random() + MIN_VEL);
   dx = (int) (2 * MAX_VEL * Math.random() - MAX_VEL);
 }
Exemplo n.º 23
0
 public void shuffle() {
   for (int x = 0; x < deck.size() * 5; x++) {
     int spot1 = (int) (Math.random() * deck.size());
     int spot2 = (int) (Math.random() * deck.size());
     Card holder = deck.get(spot1);
     Card holder2 = deck.get(spot2);
     deck.set(spot1, holder2);
     deck.set(spot2, holder);
   }
 }
  public void addParticle(int x, int y) {
    // TODO configurable
    int dx, dy;
    dx = (int) (Math.random() * 4) * (Math.random() > 0.5 ? -1 : 1);
    dy = (int) (Math.random() * -3 - 1);

    int size = (int) (Math.random() * 3 + 1);
    int life = 15;
    final Particle e = new Particle(x, y, dx, dy, size, life, JBColor.darkGray);
    particles.add(e);
  }
Exemplo n.º 25
0
 public void animate(float[] pts, float[] deltas, int index, int limit) {
   float newpt = pts[index] + deltas[index];
   if (newpt <= 0) {
     newpt = -newpt;
     deltas[index] = (float) (Math.random() * 3.0 + 2.0);
   } else if (newpt >= (float) limit) {
     newpt = 2.0f * limit - newpt;
     deltas[index] = -(float) (Math.random() * 3.0 + 2.0);
   }
   pts[index] = newpt;
 }
Exemplo n.º 26
0
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
Exemplo n.º 27
0
 public String generateRandomEmailAddress(String domain) {
   String emailAddress = "";
   // Generate random email address
   String alphabet = "abcdefghijklmnopqrstuvwxyz";
   while (emailAddress.length() < 5) {
     int character = (int) (Math.random() * 26);
     emailAddress += alphabet.substring(character, character + 1);
   }
   emailAddress += Integer.valueOf((int) (Math.random() * 99)).toString();
   emailAddress += "@" + domain;
   return emailAddress;
 }
Exemplo n.º 28
0
  // Draws this die when rolling with a random number of dots
  private void drawRolling(Graphics g) {
    int x = xCenter - dieSize / 2 + (int) (3 * Math.random()) - 1;
    int y = yCenter - dieSize / 2 + (int) (3 * Math.random()) - 1;
    g.setColor(Color.RED);

    if (x % 2 != 0) g.fillRoundRect(x, y, dieSize, dieSize, dieSize / 4, dieSize / 4);
    else g.fillOval(x - 2, y - 2, dieSize + 4, dieSize + 4);

    Die die = new Die();
    die.roll();
    drawDots(g, x, y, die.getNumDots());
  }
Exemplo n.º 29
0
  public Colony() {
    initCells();
    initLastGeneration();

    gridOn = false;

    for (int i = 0; i < 1000; i++) {
      lastGeneration[(int) (Math.random() * cells.length)][
              (int) (Math.random() * cells[0].length)] =
          new Cell(1);
    }
  }
Exemplo n.º 30
0
 /**
  * The run method just posts messages to the transcript at random intervals of 2 to 10 seconds.
  */
 public void run() {
   //
   postMessage("RECEIVED: Hey, hello there! Nice to chat with you.");
   while (running) {
     try {
       // Wait a random time from 2000 to 10000 milliseconds.
       Thread.sleep(2000 + (int) (8000 * Math.random()));
     } catch (InterruptedException e) {
     }
     int msgNum = (int) (Math.random() * incomingMessages.length);
     postMessage("RECEIVED: " + incomingMessages[msgNum]);
   }
 }