/** 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();
  }
Exemple #2
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;
   }
 }
  protected void moveBall() {
    // System.out.println("I'm in the moveBall() function!");
    int width = getWidth();
    int height = getHeight();
    int min, max, randomX, randomY;
    min = 0;
    max = 200;
    randomX = min + (int) (Math.random() * ((max - min) + 1));
    randomY = min + (int) (Math.random() * ((max - min) + 1));
    // System.out.println(randomX + ", " + randomY);

    Rectangle ballBounds = ball.getBounds();
    //      //System.out.println(ballBounds.x + ", " + ballBounds.y);
    //      if (ballBounds.x + randomX < 0) {
    //          randomX = 200;
    //      } else if (ballBounds.x + ballBounds.width + randomX > width) {
    //          randomX = -200;
    //      }
    //      if (ballBounds.y + randomY < 0) {
    //          randomY = 200;
    //      } else if (ballBounds.y + ballBounds.height + randomY > height) {
    //          randomY = -200;
    //      }

    ballBounds.x = randomX;
    ballBounds.y = randomY;
    _ballXpos = ballBounds.x;
    _ballYpos = ballBounds.y;
    ball.setFrame(ballBounds);
    thePlacebo.repaint();
  }
Exemple #4
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);
      }
    }
  }
Exemple #5
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;
  }
 // -------------------------------------------------------------------------------------------------------------------------------------------------------
 // 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);
   }
 }
  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;
  }
Exemple #8
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);
 }
Exemple #9
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
 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;
 }
Exemple #11
0
 private void spawnBomb() {
   float x, y;
   for (int i = 0; i < bombN; i++) {
     if (Math.random() > .5) { // top/bottom
       y = (Math.random() > .5) ? borders[1] : borders[3];
       x = (float) Math.random() * borders[2] - borders[0]; // width
     } else {
       x = (Math.random() > .5) ? borders[0] : borders[2];
       y = (float) Math.random() * borders[3] - borders[1]; // height
     }
     enemies.add(new EnemyTypes.Bomb(x, y, 1f, borders, scbInstance));
   }
 }
 /**
  * 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]);
   }
 }
Exemple #13
0
 public void update(Graphics g) {
   Dimension newSize = getSize();
   if (size.equals(newSize)) {
     // Erase old box
     g.setColor(getBackground());
     g.drawRect(mx, my, (size.width / 10) - 1, (size.height / 10) - 1);
   } else {
     size = newSize;
     g.clearRect(0, 0, size.width, size.height);
   }
   // Calculate new position
   mx = (int) (Math.random() * 1000) % (size.width - (size.width / 10));
   my = (int) (Math.random() * 1000) % (size.height - (size.height / 10));
   paint(g);
 }
Exemple #14
0
  private void levelSetup() {
    reset();

    switch (level) {
      case 1:
        distance = 600;
        monsterN = 0;
        randomN = 0;
        rainN = 30;
        defaultDistance = 600;
        timeLast = 10000;
        spawnCircleB = true;
        break;
      case 2:
        distance = 600;
        monsterN = 0;
        randomN = 30;
        rainN = 30;
        defaultDistance = 600;
        timeLast += 10000;
        spawnCircleB = true;
        break;
      case 3:
        distance = 600;
        monsterN = 30;
        randomN = 0;
        rainN = 0;
        defaultDistance = 600;
        timeLast += 10000;
        spawnCircleB = true;
        break;
      default:
        distance = (float) (Math.random() * 200 + 400 - level * 5);
        monsterN = (int) (Math.random() * 25 + 10 + level);
        randomN = (int) (Math.random() * 25 + 10 + level);
        rainN = (int) (Math.random() * 10 + 10 + level);
        defaultDistance = distance;
        timeLast += 5000 + level * 1000;
        spawnCircleB = true;
    }

    monsterN *= monsterMultiplier;
    randomN *= monsterMultiplier;
    spawnMonsterB = true;
    spawnRandomersB = true;
    spawnIncrease = true;
    spawnRainB = true;
  }
Exemple #15
0
 public void blockgen() {
   Component temporaryLostComponent = null;
   pos[0] = 0;
   pos[1] = 1;
   rand = (int) (Math.floor(Math.random() * 7 + 1));
   centralx = 4;
   centraly = 0;
   System.out.print(rand);
   if ((b[4 + prof[pos[0]][0][rand - 1].x][prof[pos[0]][0][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][1][rand - 1].x][prof[pos[0]][1][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][2][rand - 1].x][prof[pos[0]][2][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][3][rand - 1].x][prof[pos[0]][3][rand - 1].y].getBackground()
           == Color.DARK_GRAY)) {
     b[4 + prof[pos[0]][0][rand - 1].x][prof[pos[0]][0][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][1][rand - 1].x][prof[pos[0]][1][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][2][rand - 1].x][prof[pos[0]][2][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][3][rand - 1].x][prof[pos[0]][3][rand - 1].y].setBackground(rnd[rand - 1]);
     go();
   } else {
     JOptionPane.showMessageDialog(
         temporaryLostComponent, "Game Over! You cleared " + rowsclrd + " rows, well done!");
     System.exit(0);
   }
 }
Exemple #16
0
 public void makeSHButtonActionPerformed(ActionEvent evt) {
   String name = "Stakeholder " + (this.stakeholders.size());
   boolean a, b, c, d, e;
   a = b = c = d = e = false;
   int random = (int) (Math.random() * 32);
   System.out.println(random);
   if (random >= 16) {
     a = true;
     random -= 16;
   }
   if (random >= 8) {
     b = true;
     random -= 8;
   }
   if (random >= 4) {
     c = true;
     random -= 4;
   }
   if (random >= 2) {
     d = true;
     random -= 2;
   }
   if (random >= 1) {
     e = true;
     random -= 1;
   }
   System.out.printf("Stakeholder(%s, ,%b,%b,%b,%b,%b)%n", name, a, b, c, d, e);
   Stakeholder s = new Stakeholder(name, "", a, b, c, d, e);
   stakeholders.add(s);
   pushAllSHButton.setText("Push " + stakeholders.size() + " to View");
 }
Exemple #17
0
 // Add a random tetris shape to the arraylist
 // Add the shape to the tool bar
 // Also find the ai command when ai is enabled
 public void addShape() {
   shapeTrack = new ArrayList<Integer>();
   int n = (int) (Math.random() * 7);
   switch (n) {
     case (0):
       shapes.add(new Block(THA.WIDTH / 2 - 40, -80, new Color(0, 0, 128)));
       break;
     case (1):
       shapes.add(new Line(THA.WIDTH / 2 - 40, -80, new Color(75, 0, 130)));
       break;
     case (2):
       shapes.add(new LeftZ(THA.WIDTH / 2 - 40, -80, new Color(255, 215, 0)));
       break;
     case (3):
       shapes.add(new RightZ(THA.WIDTH / 2 - 40, -80, new Color(255, 20, 147)));
       break;
     case (4):
       shapes.add(new T(THA.WIDTH / 2 - 40, -80, new Color(205, 0, 0)));
       break;
     case (5):
       shapes.add(new LeftL(THA.WIDTH / 2 - 40, -80, new Color(255, 165, 0)));
       break;
     case (6):
       shapes.add(new RightL(THA.WIDTH / 2 - 40, -80, new Color(0, 128, 0)));
       break;
     default:
       System.out.println("Impossible Error!!!");
       break;
   }
   ns.clear();
   ns.addShape(shapes);
   if (shapeAI.getAI()) {
     aiCommand = shapeAI.initAI(map, shapes.get(0));
   }
 }
 // -------------------------------------------------------------------------------------------------------------------------------------------------------
 // Patterns
 public void newPattern() {
   int prob = (int) (Math.random() * probs.get(level - 1) + 1);
   Pattern p = new Pattern(0, -300, prob, (int) (backy * 0.1));
   if (checkSpawn(new Rectangle(p.getX(), p.getY(), p.getWidth(), p.getHeight())) == true) {
     for (Coin i : p.getCoins()) {
       coinList.add(i);
     }
     for (Star i : p.getStars()) {
       starList.add(i);
     }
     for (Box i : p.getBoxes()) {
       boxList.add(i);
     }
     for (Jumper i : p.getJumpers()) {
       jumperList.add(i);
     }
     for (Enemy i : p.getEnemies()) {
       enemyList.add(i);
     }
     for (Spikes i : p.getSpikes()) {
       spikeList.add(i);
     }
     for (Powerup i : p.getPowerUps()) {
       pupList.add(i);
     }
     for (Rectangle i : p.getRects()) {
       rectList.add(i);
     }
   }
 }
 /**
  * Constructs a Sorter.
  *
  * @param values the array to be sorted
  * @param comp the component on which to display the sorting progress
  */
 public Sorter(ArrayComponent comp) {
   values = new Double[VALUES_LENGTH];
   for (int i = 0; i < values.length; i++) values[i] = new Double(Math.random());
   this.component = comp;
   this.gate = new Semaphore(1);
   this.run = false;
 }
Exemple #20
0
  public void makeField() {
    int vector[] = new int[rows * cols];
    int temp = 0;
    int limit, m, n;
    field = new int[rows][cols];
    for (m = 0; m < rows; m++)
      for (n = 0; n < cols; n++)
        vector[(n * rows) + m] = field[m][n] = (int) (Math.random() * 10000);
    Sort(vector, 0, vector.length - 1);
    limit = vector[nummines - 1];
    for (m = 0; m < rows; m++)
      for (n = 0; n < cols; n++) {
        field[m][n] = (field[m][n] <= limit ? (-1) : (0));
        if (field[m][n] == -1) {
          minerowlist[temp] = m;
          minecollist[temp++] = n;
        }
      }

    for (m = 0; m < rows; m++)
      for (n = 0; n < cols; n++)
        if (field[m][n] == 0) {
          int v = countmines(m, n);
          field[m][n] = v;
        }
    // printField();
  }
  // FUNCTION TO GENERATE A STRING OF 10 ADDRESS REFERENCES
  public void autoGenerateString() {
    int random;

    for (int i = 0; i < 10; i++) {

      // RANDOMLY SELECT AN INDEX BETWEEN 0 AND 255
      random = (int) (Math.random() * 256);

      // ADD THE ADDRESS AT THIS INDEX IN ARRAY addresses TO THE LIST OF ADDRESS REFERENCE STRINGS
      //	listData[i] = addresses[random];
      listData.add(addresses[random]);
    }

    // ADD THIS LIST TO THE LISTBOX
    addRefStrList.setListData(listData);

    // ENABLE THE Next BUTTON AND DISABLE Back BUTTON
    //		moveStatus = 0;
    next.setEnabled(true);
    back.setEnabled(false);

    // UPDATE THE PROGRESS FIELD
    tProgress.setText(
        "We have automatically generated an address string of 10 addresses for you to work with."
            + "\nClick on \"Next\" to continue.");
  } // END FUNCTION autoGenerateString
Exemple #22
0
  /** Setzt alle Spielparameter zurück und verteilt die Spieler entlang der Main-Ebene */
  public void restartGame() {
    for (int c = 1; c < player.length; c++) {
      if (player[c] != null) {
        player[c].x = (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]);
        player[c].y = 0;
        player[c].health = 100;
        player[c].jumpheigth = 200;
        player[c].speed = 5;
        player[c].sperrzeit = 40;
        player[c].freezeControls = false;
        gamerunner.neu = false;
        gamerunner.schonneu = true;
        player[c].amstartwarten = 42;
        player[c].perkzählerjump = -1;
        player[c].perkzählerrun = -1;
        player[c].perkzählershoot = -1;
        player[c].boomRight = 0;
        player[c].boomUp = 0;
        player[c].boomLeft = 0;
        gamerunner.wellenModus.wAnzeige = -1;
        gamerunner.wellenModus.wNeu = false;
        gamerunner.wellenModus.nNeu = false;
        gamerunner.storyModus.amanfang = true;
        gamerunner.wellenModus.amanfang = true;
      } // end of if
    } // end of for

    for (int c = 0; c < gamerunner.shot.length; c++) {
      gamerunner.shot[c] = null;
      DamageLogig.shot[c] = null;
    } // end of for
    DamageLogig.counter = 0;
  }
  public void newGame() {
    timerOn = true;
    time = 0;
    timer.start();

    board = new Square[16][16];
    length = board.length;
    numBears = 40;
    maxFlags = 40;
    currentFlags = 0;
    bearsCovered = 0;

    // Set up the board with new Squares
    for (int row = 0; row < length; row++) {
      for (int col = 0; col < length; col++) {
        board[row][col] = new Square(row, col);
      }
    }

    // Randomise Bears into the board
    while (numBears > 0) {
      int row = (int) (Math.random() * 16);
      int column = (int) (Math.random() * 16);

      if (!board[row][column].isBear()) {
        board[row][column].addBear();
        numBears--;
      }
    }

    // Insert the number of bears adjacent to each square
    for (int row = 0; row < length; row++) {
      for (int col = 0; col < length; col++) {
        if (board[row][col].isBear()) {
          if (col - 1 > -1 && row - 1 > -1) board[row - 1][col - 1].addAdjacent();
          if (row - 1 > -1) board[row - 1][col].addAdjacent();
          if (col + 1 < length && row - 1 > -1) board[row - 1][col + 1].addAdjacent();
          if (col - 1 > -1) board[row][col - 1].addAdjacent();
          if (col + 1 < length) board[row][col + 1].addAdjacent();
          if (col - 1 > -1 && row + 1 < length) board[row + 1][col - 1].addAdjacent();
          if (row + 1 < length) board[row + 1][col].addAdjacent();
          if (col + 1 < length && row + 1 < length) board[row + 1][col + 1].addAdjacent();
        }
      }
    }
    repaint();
  }
  public CubeRunner() {

    t.start();
    set50.stop();

    addKeyListener(this); // Add this key listener
    setFocusable(true); // Sets the focus to this so I can use KeyListener
    setFocusTraversalKeysEnabled(false); // Allows keys to act normal

    for (int k = 0; k < 30; k++) {
      x = Math.random() * 500;

      y = Math.random() * -500;

      boxes[k] = object.getRec(x, y);
    }
  }
Exemple #25
0
  public void paintComponent(Graphics g) {
    // необходиом чтобы текст коректно отрисовывался в окне
    super.paintComponent(g);
    // рисуем текст в окне
    Graphics2D g2 = (Graphics2D) g;
    AffineTransform t = g2.getTransform();
    g.drawString("It is text", 5, 5);
    // создание шрифта
    Font f = new Font("SanasSerif", Font.ITALIC, 20);
    g2.setFont(f);
    g2.drawString("It is new text", 5, 33);
    String[] fontNames =
        GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    for (int i = 5; i < 20; i++) {
      g2.rotate(-0.05);
      g2.setColor(
          new Color(
              (int) (Math.random() * 255),
              (int) (Math.random() * 255),
              (int) (Math.random() * 255)));
      Font f1 = new Font(fontNames[i], Font.BOLD, 20);
      g2.setFont(f1);
      g2.drawString(fontNames[i], 5, 20 * i);
    }
    // текст в центре

    g2.setTransform(t); // возращение к кординатам, которые запонилив начале
    Font f2 = new Font("SanasSerif", Font.ITALIC, 20);
    g2.setFont(f2);
    String s = "It is center!";
    FontRenderContext context = g2.getFontRenderContext();
    Rectangle2D r = f2.getStringBounds(s, context);
    double x1 = (getWidth() - r.getWidth()) / 2;
    double y1 = (getHeight() - r.getHeight()) / 2;
    double ascent = -r.getY(); // узнаем высоту текста
    double y2 = y1 + ascent;
    Rectangle2D rect = new Rectangle2D.Double(x1, y1, r.getWidth(), r.getHeight());
    g2.setColor(Color.YELLOW);
    g2.fill(rect);
    g2.setColor(Color.red);
    g2.drawString(s, (int) x1, (int) y2);
    g2.setColor(Color.blue);
    g2.draw(new Line2D.Double(x1, y2, x1 + r.getWidth(), y2));

    g2.draw(rect);
  }
  public static void main(String[] args) {
    ChartWindow cw = new ChartWindow("test");

    double[] c1 = new double[100];
    for (int i = 0; i < c1.length; i++) {
      c1[i] = Math.random();
    }

    cw.draw(c1);

    double[] c2 = new double[100];
    for (int i = 0; i < c2.length; i++) {
      c2[i] = Math.random();
    }

    cw.draw(c2);
  }
Exemple #27
0
  public void paint(Graphics g) {
    super.paint(g);

    Dimension size = getSize();
    double w = size.getWidth() - 50;
    double h = size.getHeight() + 20;

    try {
      readFile();
    } catch (IOException e) {
      System.err.println("IO issue");
    }

    barWidth = ((int) (w / numBars)) - 20;
    pos = 5;

    int xPos[] = {pos, pos, pos, pos};
    int yPos[] = {pos, pos, pos, pos};

    maxVal = maxValue(values);
    double barH, ratio;

    for (int i = 0; i < numBars - 1; i++) {
      Color col[] = new Color[numBars];
      for (int j = 0; j < numBars - 1; j++) {
        col[j] = new Color((int) (Math.random() * 0x1000000));
      }

      ratio = (double) values[i] / (double) maxVal;
      barH = ((h) * ratio) - 10;

      xPos[0] = pos;
      xPos[2] = pos + barWidth;
      xPos[1] = xPos[0];
      xPos[3] = xPos[2];
      yPos[0] = (int) h;
      yPos[1] = (int) barH;
      yPos[2] = yPos[1];
      yPos[3] = yPos[0];

      System.out.println(
          "xPos:" + xPos[1] + " yPos:" + yPos[0] + " h:" + h + " barH:" + barH + " ratio:" + ratio
              + " pos:" + pos);

      int stringPtsY[] = {
        ((i + 1) * 20) + 180, ((i + 1) * 20) + 200, ((i + 1) * 20) + 200, ((i + 1) * 20) + 180
      };
      int stringPtsX[] = {600, 600, 580, 580};

      g.setColor(col[i]);
      g.fillPolygon(xPos, yPos, xPos.length);

      g.fillPolygon(stringPtsX, stringPtsY, 4);
      g.setColor(Color.black);
      g.drawString(labels[i], 610, ((i + 1) * 20) + 195);
      pos = pos + barWidth + 10;
    }
  }
 public void start() {
   Dimension size = getSize();
   for (int i = 0; i < animpts.length; i += 2) {
     animpts[i + 0] = (float) (Math.random() * size.width);
     animpts[i + 1] = (float) (Math.random() * size.height);
     deltas[i + 0] = (float) (Math.random() * 4.0 + 2.0);
     deltas[i + 1] = (float) (Math.random() * 4.0 + 2.0);
     if (animpts[i + 0] > size.width / 6.0f) {
       deltas[i + 0] = -deltas[i + 0];
     }
     if (animpts[i + 1] > size.height / 6.0f) {
       deltas[i + 1] = -deltas[i + 1];
     }
   }
   anim = new Thread(this);
   anim.setPriority(Thread.MIN_PRIORITY);
   anim.start();
 }
  /**
   * The user has clicked in the applet. Figure out where and see if a legal move is possible. If it
   * is a legal move, respond with a legal move (if possible).
   */
  public void mouseReleased(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();

    switch (status()) {
      case WIN:
      case LOSE:
      case STALEMATE:
        play(getCodeBase(), "audio/return.au");
        white = black = 0;
        if (first) {
          white |= 1 << (int) (Math.random() * 9);
        }
        first = !first;
        repaint();
        return;
    }

    // Figure out the row/column
    Dimension d = getSize();
    int c = (x * 3) / d.width;
    int r = (y * 3) / d.height;
    if (yourMove(c + r * 3)) {
      repaint();

      switch (status()) {
        case WIN:
          play(getCodeBase(), "audio/yahoo1.au");
          break;
        case LOSE:
          play(getCodeBase(), "audio/yahoo2.au");
          break;
        case STALEMATE:
          break;
        default:
          if (myMove()) {
            repaint();
            switch (status()) {
              case WIN:
                play(getCodeBase(), "audio/yahoo1.au");
                break;
              case LOSE:
                play(getCodeBase(), "audio/yahoo2.au");
                break;
              case STALEMATE:
                break;
              default:
                play(getCodeBase(), "audio/ding.au");
            }
          } else {
            play(getCodeBase(), "audio/beep.au");
          }
      }
    } else {
      play(getCodeBase(), "audio/beep.au");
    }
  }
Exemple #30
0
 public void updateRoll(int i) {
   _dieRoll = i;
   twoDice =
       new int[] {
         (int) Math.max(Math.floor(Math.random() * Math.min(_dieRoll - 1, 5)) + 1, _dieRoll - 6), 1
       };
   twoDice[1] = _dieRoll - twoDice[0];
   repaint();
 }