public void UnScramble() {
   mPuzzle.UnScramblePuzzle();
   mBrickGrid = mPuzzle.GetPuzzle();
   enabled = false;
   mStatusText.setText(mPuzzle.getScore());
   mStatusText.setVisibility(View.VISIBLE);
   invalidate();
 }
  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    Resources r = this.getContext().getResources();

    // mBrickGrid = mPuzzle.CreateNewPuzzle(mXBrickCount, mYBrickCount);

    mXBrickCount = mPuzzle.getXBrickCount();
    mYBrickCount = mPuzzle.getYBrickCount();

    mBrickGrid = mPuzzle.GetPuzzle();

    if (w > h) {
      mBrickSize = (int) Math.floor(h / mYBrickCount);
    } else {
      mBrickSize = (int) Math.floor(w / mXBrickCount);
    }

    resetBricks(29);

    loadBrick(NUM_0, r.getDrawable(R.drawable.pic_0_def));
    loadBrick(NUM_1, r.getDrawable(R.drawable.pic_1_def));
    loadBrick(NUM_2, r.getDrawable(R.drawable.pic_2_def));
    loadBrick(NUM_3, r.getDrawable(R.drawable.pic_3_def));
    loadBrick(NUM_4, r.getDrawable(R.drawable.pic_4_def));
    loadBrick(NUM_5, r.getDrawable(R.drawable.pic_5_def));
    loadBrick(NUM_6, r.getDrawable(R.drawable.pic_6_def));
    loadBrick(NUM_7, r.getDrawable(R.drawable.pic_7_def));
    loadBrick(NUM_8, r.getDrawable(R.drawable.pic_8_def));
    loadBrick(NUM_9, r.getDrawable(R.drawable.pic_9_def));
    loadBrick(OP_PL, r.getDrawable(R.drawable.pic_add_def));
    loadBrick(OP_MN, r.getDrawable(R.drawable.pic_min_def));
    loadBrick(OP_MT, r.getDrawable(R.drawable.pic_mul_def));
    loadBrick(OP_EQ, r.getDrawable(R.drawable.pic_eq_def));
    loadBrick(BLANK, r.getDrawable(R.drawable.pic_blk));
    loadBrick(NUM_0_D, r.getDrawable(R.drawable.pic_0_d));
    loadBrick(NUM_1_D, r.getDrawable(R.drawable.pic_1_d));
    loadBrick(NUM_2_D, r.getDrawable(R.drawable.pic_2_d));
    loadBrick(NUM_3_D, r.getDrawable(R.drawable.pic_3_d));
    loadBrick(NUM_4_D, r.getDrawable(R.drawable.pic_4_d));
    loadBrick(NUM_5_D, r.getDrawable(R.drawable.pic_5_d));
    loadBrick(NUM_6_D, r.getDrawable(R.drawable.pic_6_d));
    loadBrick(NUM_7_D, r.getDrawable(R.drawable.pic_7_d));
    loadBrick(NUM_8_D, r.getDrawable(R.drawable.pic_8_d));
    loadBrick(NUM_9_D, r.getDrawable(R.drawable.pic_9_d));
    loadBrick(OP_PL_D, r.getDrawable(R.drawable.pic_add_d));
    loadBrick(OP_MN_D, r.getDrawable(R.drawable.pic_min_d));
    loadBrick(OP_MT_D, r.getDrawable(R.drawable.pic_mul_d));
    loadBrick(OP_EQ_D, r.getDrawable(R.drawable.pic_eq_d));

    mXOffset = ((w - (mBrickSize * mXBrickCount)) / 2);
    mYOffset = ((h - (mBrickSize * mYBrickCount)) / 2);
  }
示例#3
0
  private void agafarDades() {
    CO.tl = (TableLayout) findViewById(R.id.tl);

    agafarCaselles();
    // CO.intentMax =
    // CO.miss = (TextView) findViewById(R.id.missatge);
    CO.missCorrectes = (TextView) findViewById(R.id.editAciertos);
    CO.cas1 = (TextView) findViewById(R.id.cas1);
    CO.name = (TextView) findViewById(R.id.titulo);

    // CO.miss.setTextColor(Color.WHITE);
    // CO.missCorrectes.setTextColor(Color.WHITE);
    CO.name.setTextColor(Color.WHITE);
    // CO.cas1.setTextColor(Color.WHITE);

    CO.p1 = "<buit>";
    CO.p2 = "<buit>";

    if (Parser.getActivitats().elementAt(CO.activitatActual).getName() != null)
      CO.name.setText(Parser.getActivitats().elementAt(CO.activitatActual).getName());
    else CO.name.setText("Activitat JClic");

    if (CO.rows == 1) CO.tl.setPadding(0, 100, 0, 0);
    else if (CO.rows == 2) {
      CO.tl.setPadding(0, 30, 0, 0);
    } else CO.tl.setPadding(0, 0, 0, 0);

    if (CO.colorBG != null) {
      CO.bg = Puzzle.agafarColor(CO.colorBG);
    } else CO.bg = Color.BLACK;

    if (CO.colorFG != null) {
      CO.fg = Puzzle.agafarColor(CO.colorFG);
    } else CO.fg = Color.WHITE;

    for (int i = 0; i < CO.vecCaselles.size(); i++) {
      if (CO.vecCaselles.elementAt(i) != null) {
        CO.vecCaselles.elementAt(i).setBackgroundColor(CO.bg);
        CO.vecCaselles.elementAt(i).setTextColor(CO.fg);
        CO.vecCaselles.elementAt(i).setPadding(10, 15, 10, 10);
        CO.vecCaselles.elementAt(i).setMaxLines(3);
        CO.vecCaselles.elementAt(i).setText(CO.entrada.elementAt(i));
        if (CO.imatge != null) {
          CO.vecCaselles.elementAt(i).setBackgroundColor(Color.TRANSPARENT);
          CO.vecCaselles.elementAt(i).setTextColor(Color.TRANSPARENT);
        }
        reestructurarCaselles(CO.vecCaselles.elementAt(i));
      }
    }
    bloquejarJoc(false);
  }
 // enters puzzles into the listmodel
 void enterPuzzle(String catagoryName) {
   CategoryNode tmp = ChessApplication.l.head;
   while (tmp != null) {
     if (catagoryName.equalsIgnoreCase(tmp.categoryName)) {
       Puzzle temp = tmp.h;
       while (temp != null) {
         listmodel.addElement(temp.getFenString());
         temp = temp.next;
       }
       break;
     }
     tmp = tmp.next;
   }
 }
  public void setTextView(TextView newView) {
    mStatusText = newView;

    // Set the StatusText to the current score.
    mStatusText.setText(mPuzzle.getScore());
    mStatusText.setVisibility(View.VISIBLE);
  }
 private boolean repetido(Puzzle no) {
   for (int i = 0; i < usados.size(); i++) {
     if (no.isIgual((Puzzle) usados.get(i))) {
       return true;
     }
   }
   return false;
 }
示例#7
0
 public ArrayList<Integer> solve(Puzzle puzzle) {
   // create an empty queue as an ArrayList<ArrayList<Integer>>
   ArrayList<ArrayList<Integer>> queue = new ArrayList<ArrayList<Integer>>();
   // create an ArrayList<Integer> of one element from the starting config and enqueue it
   ArrayList<Integer> element = new ArrayList<Integer>(1);
   element.add(puzzle.getStart());
   queue.add(element);
   // set found to whether the starting config is the goal config, or not
   boolean found = false;
   if (puzzle.getStart() == puzzle.getGoal()) found = true;
   // while the queue is not empty and not found:
   while (!queue.isEmpty() && !found) {
     // dequeue the front element from the queue and set it to current
     element = queue.get(0);
     queue.remove(0);
     // for each neighbor of the last element in current:
     for (Integer i : puzzle.getNeighbors(element.get(element.size() - 1))) {
       // create an ArrayList<Integer> for the next config and make it a copy of current
       ArrayList<Integer> nextConfig = new ArrayList(element);
       // append the neighbor to the next config
       nextConfig.add(i);
       // if the next config is the goal:
       if (i == puzzle.getGoal()) {
         element = nextConfig;
         found = true;
         break;
       }
       // enqueue the next config
       else {
         queue.add(nextConfig);
       }
     }
   }
   // if found:
   if (found)
     // current is the solution
     return element;
   else
     // there is no solution
     return null;
 }
示例#8
0
  /**
   * Computes a grid representation of the state. In particular, an nxn two-dimensional integer
   * array is computed and returned, where n is the size of the puzzle grid. The <tt>(i,j)</tt>
   * element of this grid is equal to -1 if square <tt>(i,j)</tt> is unoccupied, and otherwise
   * contains the index of the car occupying this square. Note that the grid is recomputed each time
   * this method is called.
   */
  public int[][] getGrid() {
    int gridsize = puzzle.getGridSize();
    int grid[][] = new int[gridsize][gridsize];

    for (int i = 0; i < gridsize; i++) for (int j = 0; j < gridsize; j++) grid[i][j] = -1;

    int num_cars = puzzle.getNumCars();

    for (int v = 0; v < num_cars; v++) {
      boolean orient = puzzle.getCarOrient(v);
      int size = puzzle.getCarSize(v);
      int fp = puzzle.getFixedPosition(v);
      if (v == 0 && varPos[v] + size > gridsize) size--;
      if (orient) {
        for (int d = 0; d < size; d++) grid[fp][varPos[v] + d] = v;
      } else {
        for (int d = 0; d < size; d++) grid[varPos[v] + d][fp] = v;
      }
    }
    return grid;
  }
示例#9
0
  /**
   * Returns <tt>true</tt> if and only if this state is considered equal to the given object. In
   * particular, equality is defined to hold if the given object is also a <tt>State</tt> object, if
   * it is associated with the same <tt>Puzzle</tt> object, and if the cars in both states are in
   * the identical positions. This method overrides <tt>Object.equals</tt>.
   */
  public boolean equals(Object o) {
    State s;
    try {
      s = (State) o;
    } catch (ClassCastException e) {
      return false;
    }
    if (hashcode != s.hashcode || !puzzle.equals(s.puzzle)) return false;

    for (int i = 0; i < varPos.length; i++) if (varPos[i] != s.varPos[i]) return false;
    return true;
  }
示例#10
0
 private int valueInt(String s) {
   if (s == Normal.toString()) {
     return 0;
   } else if (s == Math.toString()) {
     return 1;
   } else if (s == Puzzle.toString()) {
     return 2;
   } else if (s == Shake.toString()) {
     return 3;
   }
   return -1;
 }
示例#11
0
  /**
   * Computes all of the states immediately reachable from this state and returns them as an array
   * of states. You probably will not need to use this method directly, since ordinarily you will be
   * expanding <tt>Node</tt>s, not <tt>State</tt>s.
   */
  public State[] expand() {
    int gridsize = puzzle.getGridSize();
    int grid[][] = getGrid();
    int num_cars = puzzle.getNumCars();

    ArrayList<State> new_states = new ArrayList<State>();

    for (int v = 0; v < num_cars; v++) {
      int p = varPos[v];
      int fp = puzzle.getFixedPosition(v);
      boolean orient = puzzle.getCarOrient(v);
      for (int np = p - 1; np >= 0 && (orient ? grid[fp][np] : grid[np][fp]) < 0; np--) {
        int[] newVarPos = (int[]) varPos.clone();
        newVarPos[v] = np;
        new_states.add(new State(puzzle, newVarPos));
      }

      int carsize = puzzle.getCarSize(v);
      for (int np = p + carsize;
          (np < gridsize && (orient ? grid[fp][np] : grid[np][fp]) < 0)
              || (v == 0 && np == gridsize);
          np++) {
        int[] newVarPos = (int[]) varPos.clone();
        newVarPos[v] = np - carsize + 1;
        new_states.add(new State(puzzle, newVarPos));
      }
    }

    puzzle.incrementSearchCount(new_states.size());

    return (State[]) new_states.toArray(new State[0]);
  }
示例#12
0
 public static String valueString(int i) {
   switch (i) {
     case 0:
       return Normal.toString();
     case 1:
       return Math.toString();
     case 2:
       return Puzzle.toString();
     case 3:
       return Shake.toString();
   }
   return null;
 }
 public Puzzle solve() {
   long start = System.nanoTime();
   Puzzle solution;
   if (p.isSolved()) {
     solution = p;
   } else {
     Stack<Puzzle> stack = new Stack<Puzzle>();
     stack.push(p);
     solution = solve_r(stack);
   }
   this.time = System.nanoTime() - start;
   return solution;
 }
  public void imprimir() {
    Vector list = new Vector();
    Puzzle no = getSolucaoPuzzle();
    // adicionar a lista de add to answer list
    list.add(no);
    // encontrar no pai
    int idPai = no.getIdPai();
    while (idPai != -1) {
      no = (Puzzle) usados.elementAt(idPai);
      list.add(no);
      idPai = no.getIdPai();
    }

    for (int i = 1; i <= list.size(); i++) {
      if (i == 1) {
        System.out.println("Inicial:");
        System.out.println(list.elementAt(list.size() - i));
      } else {
        System.out.println("Movimento nº " + (i - 1) + ":");
        System.out.println(list.elementAt(list.size() - i));
      }
    }
    System.out.println("FIM!");
  }
示例#15
0
  public Generator(int width, int height, double countrySize, String pathSolver) {
    this.width = width;
    this.height = height;
    this.countrySize = countrySize;
    int countryID = 1;

    puzzle = new Puzzle(width, height, pathSolver);

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        if (puzzle.getCountry(x, y) == -1) {
          settingBoarders(new Pair(x, y), countryID);
          countryID++;
        }
      }
    }

    shuffled = new Shuffler(puzzle, width, height);

    puzzle.print();

    Puzzle copy = puzzle.clonePuzzle();
    copy.generateSMTPiping();
  }
  public Puzzle solve_r(Stack<Puzzle> stack) {

    while (!stack.empty()) {
      Puzzle current = stack.pop();
      if (current.isSolved()) {
        return current;
      }
      int hashCode = current.hashCode();
      if (current.getNumMoves() < maxDepth
          && (!visited.containsKey(hashCode)
              || (visited.containsKey(hashCode)
                  && visited.get(hashCode) > current.getNumMoves()))) {
        visited.put(hashCode, current.getNumMoves());
        for (Puzzle.Move move : current.getPossibleMoves()) {
          stack.push(current.swap(move));
        }
      }
    }
    return null;
  }
示例#17
0
  /** Prints to standard output a primitive text representation of the state. */
  public void print() {
    int grid[][] = getGrid();
    int gridsize = puzzle.getGridSize();

    System.out.print("+-");
    for (int x = 0; x < gridsize; x++) {
      System.out.print("--");
    }
    System.out.println("+");

    for (int y = 0; y < gridsize; y++) {

      System.out.print("| ");
      for (int x = 0; x < gridsize; x++) {
        int v = grid[x][y];
        if (v < 0) {
          System.out.print(". ");
        } else {
          int size = puzzle.getCarSize(v);
          if (puzzle.getCarOrient(v)) {
            System.out.print((y == varPos[v] ? "^ " : ((y == varPos[v] + size - 1) ? "v " : "| ")));
          } else {
            System.out.print(x == varPos[v] ? "< " : ((x == varPos[v] + size - 1) ? "> " : "- "));
          }
        }
      }
      System.out.println(
          (puzzle.getCarOrient(0) || y != puzzle.getFixedPosition(0))
              ? "|"
              : (isGoal() ? ">" : " "));
    }

    System.out.print("+-");
    for (int x = 0; x < gridsize; x++) {
      System.out.print(
          (!puzzle.getCarOrient(0) || x != puzzle.getFixedPosition(0))
              ? "--"
              : (isGoal() ? "v-" : " -"));
    }
    System.out.println("+");
  }
 private Puzzle encontrarMelhNodo() {
   Puzzle melhor;
   Puzzle test;
   if (lista.size() == 0) {
     melhor = (Puzzle) usados.elementAt(0);
   } else {
     melhor = (Puzzle) lista.elementAt(0);
   }
   for (int i = 1; i < lista.size(); i++) {
     test = (Puzzle) lista.get(i);
     int melhorHeu = melhor.getPerfundidade() + melhor.getHeuCurt();
     int tempHeu = test.getPerfundidade() + test.getHeuCurt();
     // quanto mais pequeno melhor
     if (tempHeu < melhorHeu) {
       melhor = test;
     }
   }
   return melhor;
 }
示例#19
0
  // WE NEED TO GO OVER THIS BECAUSE IT IS SORT OF CONFUSING
  // pre condition:
  // post condition:
  // bigO notation:
  private boolean solve(int count, int last, String stack) {
    if (_puzzle.isSolved()) {
      if ((_count == 0) || (_count > count)) {
        _count = count;
        _moves = stack;
      }
      // System.out.println(stack);
      return true;
    }

    count++;
    if ((count > 31) || ((_count != 0) && (count >= _count))) return false;

    // move the one over
    if (last != 2) {
      if (_puzzle.move(-1, 0)) {
        solve(count, 0, stack + _puzzle.emptyPos() + ":");
        _puzzle.move(1, 0);
      }
    }
    // move the one to the right
    if (last != 3) {
      if (_puzzle.move(0, 1)) {
        solve(count, 1, stack + _puzzle.emptyPos() + ":");
        _puzzle.move(0, -1);
      }
    }
    // move the one below
    if (last != 0) {
      if (_puzzle.move(1, 0)) {
        solve(count, 2, stack + _puzzle.emptyPos() + ":");
        _puzzle.move(-1, 0);
      }
    }
    // move the one to the left
    if (last != 1) {
      if (_puzzle.move(0, -1)) {
        solve(count, 3, stack + _puzzle.emptyPos() + ":");
        _puzzle.move(0, 1);
      }
    }
    return false;
  }
示例#20
0
 /** Returns true if and only if this state is a goal state. */
 public boolean isGoal() {
   return (varPos[0] == puzzle.getGridSize() - 1);
 }
示例#21
0
 private void computeHashCode() {
   hashcode = puzzle.hashCode();
   for (int i = 0; i < varPos.length; i++) hashcode = 31 * hashcode + varPos[i];
 }
 private void adicinarLista(Puzzle p) {
   if (!repetido(p)) {
     p.contaJogada();
     lista.add(p);
   }
 }
 private boolean expandiNos(Puzzle p) {
   int[] test;
   Puzzle temp;
   lista.remove(p);
   int parentID = usados.size();
   usados.add(p);
   // se heuristica = 0, esta no obejectivo
   if (p.getHeuCurt() == 0) {
     return false;
   }
   test = p.cima();
   temp = new Puzzle(test, p.eCurto(), p.getPerfundidade(), parentID);
   adicinarLista(temp);
   test = p.baixo();
   temp = new Puzzle(test, p.eCurto(), p.getPerfundidade(), parentID);
   adicinarLista(temp);
   test = p.esquerda();
   temp = new Puzzle(test, p.eCurto(), p.getPerfundidade(), parentID);
   adicinarLista(temp);
   test = p.direita();
   temp = new Puzzle(test, p.eCurto(), p.getPerfundidade(), parentID);
   adicinarLista(temp);
   return true;
 }
 /*
  *
  * 28 October 2011 - FWS Added the Scramble() and UnScramble() methods
  */
 public void Scramble() {
   enabled = true;
   mPuzzle.ScramblePuzzle();
   mBrickGrid = mPuzzle.GetPuzzle();
   invalidate();
 }
  public boolean onTouch(View v, MotionEvent event) {
    // Don't do anything until started.
    if (!enabled) return true;

    Index index;

    float x = event.getX();
    float y = event.getY();

    // The touch was outside the grid, ignore it
    index = CoordinateToIndex(x, y);
    if (index.x == 2012 || index.y == 2012) {
      clearSelected();
      return true;
    }

    // The initial touch downward
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:

        // Record the initial down coordinates
        downX = event.getX();
        downY = event.getY();

        break;
      case MotionEvent.ACTION_MOVE:
        // What to do while the finger is moving.

        // Commenting out the break will fall through to ACTION_UP.

        // This will change the tiles while moving.
        // Need to undo this on ACTION_UP
        if (mBrickGrid[index.x][index.y] < 2012) {
          if (mBrickGrid[index.x][index.y] < BLANK) {
            mBrickGrid[index.x][index.y] = mBrickGrid[index.x][index.y] + 15;

            invalidate();
          }
        }
        break;
      case MotionEvent.ACTION_UP:
        clearSelected();

        // Record the up coordinates
        upX = event.getX();
        upY = event.getY();

        // ((TextView)findViewById(R.id.score)).setText("Up");

        Index downIndex;
        Index upIndex;

        downIndex = CoordinateToIndex(downX, downY);
        upIndex = CoordinateToIndex(upX, upY);

        // Check for drag on column
        if ((upIndex.x == downIndex.x) && (Math.abs(upIndex.y - downIndex.y) == 4)) {
          int points = mPuzzle.submit(columnToString(upIndex.x));

          if (points == -2) {
            AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());

            alert.setMessage("You Win!");
            CharSequence ok = "Ok";
            alert.setPositiveButton(
                ok,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                  }
                });
            alert.show();
            mStatusText.setText(mPuzzle.getScore());
          } else if (points > 0) {
            popUpPoints(v, Integer.toString(points));
            mStatusText.setText(mPuzzle.getScore());
            mStatusText.setVisibility(View.VISIBLE);
            popUpPoints(v, Integer.toString(points));
          } else {
            // Play a sound and vibrate?
          }

          // Break out of the on up to avoid tile press detection.
          break;
        }

        // Check for drag on row
        if ((upIndex.y == downIndex.y) && (Math.abs(upIndex.x - downIndex.x) == 4)) {
          int points = mPuzzle.submit(rowToString(upIndex.y));
          if (points > 0) {
            popUpPoints(v, Integer.toString(points));
            mStatusText.setText(mPuzzle.getScore());
            mStatusText.setVisibility(View.VISIBLE);
          }

          // Break out of the on up to avoid tile press detection.
          break;
        }

        // No drag, then it should be a tile press.
        if (mBrickGrid[index.x][index.y] < 2012) {
          if (mBrickGrid[index.x][index.y] > BLANK) {
            mBrickGrid[index.x][index.y] = mBrickGrid[index.x][index.y] - 15;
            invalidate();
          }
        }
        mPuzzle.ChangePuzzle(index.x, index.y);
        mBrickGrid = mPuzzle.GetPuzzle();
        invalidate();

        break;
      default:
        break;
    }

    return true;
  }
示例#26
0
  public static Puzzle parsePuzzle(File file) throws Exception {
    Puzzle puzzle = new Puzzle();

    String[] data = readData(file, "#");
    // remove empty space at the end of each line
    for (int j = 0; j < data.length; j++) {
      data[j] = data[j].trim();
    }
    // Set Puzzle Size
    String size = data[0];
    puzzle.setSize(Integer.valueOf(size));

    // Set Puzzle Category
    puzzle.setGameCategory(data[1]);

    // Set Puzzle Number
    puzzle.setPuzzleNumber(data[2]);

    // Parse QuestionAndAnswer Section
    QuestionAndAnswer across[] = new QuestionAndAnswer[puzzle.getSize() * puzzle.getSize() + 1];
    QuestionAndAnswer down[] = new QuestionAndAnswer[puzzle.getSize() * puzzle.getSize() + 1];
    int i = 3;
    while (i < data.length && data[i] != null) {
      parseQuestionAndAnswer(data[i], across, down);
      i++;
    }

    puzzle.setAcross(across);
    puzzle.setDown(down);
    puzzle.setPuzzleID();
    puzzle.setSolution();

    return puzzle;
  }
  // again, sets the gui
  void init(final int perspective, final Puzzle puzzle) {
    con.removeAll();
    setBounds(0, 0, 1400, 1030);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel header = new JLabel("Edit Puzzle");
    header.setFont(new Font("Serif", Font.BOLD, 40));
    header.setForeground(Color.BLACK);
    header.setBounds(600, 0, 290, 50);
    canvas = new MyCanvas(perspective);
    canvas.setBounds(30, 120, 800, 800);
    canvas.boxItem = puzzle.boxItems;
    canvas.isfromEditBoard = true;
    panel.setBackground(Color.orange);
    panel.setBounds(0, 0, 1300, 1000);
    JLabel[] alphabets = asigningalphabets(perspective);
    JLabel[] alphabets1 = asigningalphabets1(perspective);
    JLabel[] numbers = assigningnumbers(perspective);
    JLabel[] numbers1 = assigningnumbers1(perspective);
    JButton buttonNext = new JButton("Edit");
    buttonNext.setBounds(1150, 850, 120, 30);
    buttonNext.setFont(new Font("Serif", Font.BOLD, 20));
    buttonNext.setFocusable(false);
    JButton backButton = new JButton("Return");
    backButton.setBounds(930, 850, 120, 30);
    backButton.setFont(new Font("Serif", Font.BOLD, 20));
    backButton.setFocusable(false);
    listmodel = new DefaultListModel();
    enterPuzzle(puzzle.getcategoryName());
    final JList listofMoves = new JList(listmodel);
    JScrollPane list = new JScrollPane();
    list.setViewportView(listofMoves);
    list.setBounds(870, 350, 500, 300);
    listofMoves.setFont(new Font("Serif", Font.PLAIN, 20));
    for (int i = 0; i < listmodel.getSize(); i++) {
      CategoryNode tmp = ChessApplication.l.head;
      while (tmp != null) {
        if (tmp.categoryName.equalsIgnoreCase(puzzle.getcategoryName())) {
          Puzzle temp = tmp.h;
          int counter = 0;
          while (temp != null) {
            if (temp.getFenString().equalsIgnoreCase(puzzle.getFenString())) {
              listofMoves.setSelectedIndex(counter);
            }
            temp = temp.next;
            counter++;
          }
        }
        tmp = tmp.next;
      }
    }
    JLabel categoryLabel = new JLabel("Select Category");
    categoryLabel.setFont(new Font("Serif", Font.BOLD, 20));
    categoryLabel.setBounds(1020, 160, 290, 30);
    JLabel movesLabel = new JLabel("Select Puzzle");
    movesLabel.setFont(new Font("Serif", Font.BOLD, 20));
    movesLabel.setBounds(1030, 310, 290, 30);
    DefaultComboBoxModel catagorylist = new DefaultComboBoxModel();
    for (int i = 1; i < BoardtoAdd.listofCategory.getSize(); i++) {
      catagorylist.addElement(BoardtoAdd.listofCategory.getElementAt(i));
    }
    final JComboBox categoryBox = new JComboBox(catagorylist);
    categoryBox.setBounds(1000, 200, 200, 30);
    categoryBox.setFont(new Font("Serif", Font.BOLD, 20));
    categoryBox.setSelectedItem(puzzle.getcategoryName());
    backButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent arg0) {
            setRunningFalse();
            ChessApplication.editboard.setVisible(false);
            ChessApplication.startform.setVisible(true);
          }
        });
    buttonNext.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent arg0) {
            setRunningFalse();
            ChessApplication.editboard.setVisible(false);
            ChessApplication.boardtoedit.init("Edit Moves", perspective, false, puzzle);
          }
        });
    listofMoves.addMouseListener(
        new MouseListener() {

          @Override
          public void mouseClicked(MouseEvent e) {
            setRunningFalse();
            ChessApplication.editboard.setVisible(false);
            puzzle.setBoxItems();
            ChessApplication.editboard.init(
                getPuzzle(categoryBox.getSelectedItem().toString(), listofMoves.getSelectedIndex())
                    .position
                    .getToPlay(),
                getPuzzle(
                    categoryBox.getSelectedItem().toString(), listofMoves.getSelectedIndex()));
          }

          @Override
          public void mousePressed(MouseEvent e) {}

          @Override
          public void mouseReleased(MouseEvent e) {}

          @Override
          public void mouseEntered(MouseEvent e) {}

          @Override
          public void mouseExited(MouseEvent e) {}
        });
    categoryBox.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            setRunningFalse();
            ChessApplication.editboard.setVisible(false);
            puzzle.setBoxItems();
            ChessApplication.editboard.init(
                getPuzzle(categoryBox.getSelectedItem().toString()).position.getToPlay(),
                getPuzzle(categoryBox.getSelectedItem().toString()));
          }
        });
    for (int i = 0; i < 8; i++) {
      con.add(alphabets[i]);
      con.add(numbers[i]);
      con.add(alphabets1[i]);
      con.add(numbers1[i]);
    }
    con.add(categoryLabel);
    con.add(movesLabel);
    con.add(categoryBox);
    con.add(list);
    con.add(backButton);
    con.add(buttonNext);
    con.add(header);
    con.add(canvas);
    con.setBackground(Color.orange);
    con.add(panel);
    setVisible(true);
    canvas.start();
  }
示例#28
0
  public void settingBoarders(Pair pair, int countryID) {
    OwnList activeFields = new OwnList();
    OwnList aboutToAdd = new OwnList();
    OwnList countryPairs = new OwnList();
    double probability = this.countrySize;
    Random rand = new Random();

    activeFields.add(pair);
    countryPairs.add(pair);

    while (!activeFields.isEmpty()) {
      ListIterator<Pair> activeFieldIterator = activeFields.listIterator();
      Pair nextPair;
      while (activeFieldIterator.hasNext()) {
        nextPair = activeFieldIterator.next();
        activeFieldIterator.remove();
        // checking up, down, left, right for possible neighbours
        // up
        int x = nextPair.getElement0();
        int y = nextPair.getElement1() - 1;
        if (x >= 0 && y >= 0 && x < this.width && y < this.height && puzzle.getCountry(x, y) < 0) {
          if (rand.nextDouble() <= probability) {
            aboutToAdd.add(new Pair(x, y));
            if (!countryPairs.contains(new Pair(x, y))) {
              countryPairs.add(new Pair(x, y));
            }
          }
        }
        // down
        x = nextPair.getElement0();
        y = nextPair.getElement1() + 1;
        if (x >= 0 && y >= 0 && x < this.width && y < this.height && puzzle.getCountry(x, y) < 0) {
          if (rand.nextDouble() <= probability) {
            aboutToAdd.add(new Pair(x, y));
            if (!countryPairs.contains(new Pair(x, y))) {
              countryPairs.add(new Pair(x, y));
            }
          }
        }
        // left
        x = nextPair.getElement0() - 1;
        y = nextPair.getElement1();
        if (x >= 0 && y >= 0 && x < this.width && y < this.height && puzzle.getCountry(x, y) < 0) {
          if (rand.nextDouble() <= probability) {
            aboutToAdd.add(new Pair(x, y));
            if (!countryPairs.contains(new Pair(x, y))) {
              countryPairs.add(new Pair(x, y));
            }
          }
        }
        // right
        x = nextPair.getElement0() + 1;
        y = nextPair.getElement1();
        if (x >= 0 && y >= 0 && x < this.width && y < this.height && puzzle.getCountry(x, y) < 0) {
          if (rand.nextDouble() <= probability) {
            aboutToAdd.add(new Pair(x, y));
            if (!countryPairs.contains(new Pair(x, y))) {
              countryPairs.add(new Pair(x, y));
            }
          }
        }
        activeFields.remove(nextPair);
      }
      // reducing the probability of adding a field for the next iteration
      probability = probability * probability;

      ListIterator<Pair> addIterator = aboutToAdd.listIterator();
      while (addIterator.hasNext()) {
        activeFields.add(addIterator.next());
        addIterator.remove();
      }
      aboutToAdd.clear();
    }

    // Adding the new country with its ID to the Puzzle
    Pair[] countryPairsArray = countryPairs.toArray();
    puzzle.setCountry(countryPairsArray, countryID);
    // Randomly pick a Field in the country to define the circle there. The CircleID equals the
    // CountryID. Value is not set yet.
    puzzle.setCircle(countryPairsArray[rand.nextInt(countryPairsArray.length)], -1, countryID);
  }