How to check whether the jigsaw puzzle is completed or not?

后端 未结 4 1647
面向向阳花
面向向阳花 2021-01-26 00:40

i am preparing one small game like jigsaw , for that i am using 9 imageview\'s with 9 different images in the layout. set the images to imageview at the time of starting those a

4条回答
  •  猫巷女王i
    2021-01-26 01:20

    I have a simple solution. Set serial number Integer tags to ImageViews using View.setTag(index) before jumbling(before preparing the puzzle.) Then everytime the user makes a move, loop through all the imageviews and check if they are in order. If out of order then puzzle is not completed yet.

    class PuzzleItem {
       Drawable puzzlepartImage;
       int correctPosition;
    
       public PuzzleItem(Drawable d, int index) {
          puzzlepartImage = d;
          correctPosition = index;
       }
    }
    
    ArrayList list = new ArrayList();
    for (int i = 0; i < 9; i++) {
        list.add(new PuzzleItem(drawables[i], i)); 
    }
    Collections.shuffle(list);
    
    //Create the views from this list and add to the layout serially.
    // set the last view as emptyview.
    

    On every move:

    void onClick(View v) {
        /* swap drawables */
        Drawable clickedDrawable = v.getDrawable();
        v.setDrawable(null);
        mEmptyView.setDrawable(clickedDrawable);
        mEmptyView = v;
    
        /* swap tag integers */
        Integer temp = (Integer)mEmptyView.getTag();
        mEmptyView.setTag(v.getTag());
        v.setTag(temp);
    
    }
    

    After every move check for completion:

    for (int i = 0; i < 9; i++) {
        if (imgView[i].getTag() != i) break;
    }
    if (i == 9)// puzzle completed.
    

提交回复
热议问题