我的八卦拼图游戏中的瓷砖无法交换

x33g5p2x  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(212)

我目前正在开发一个由9个按钮组成的游戏。它们可以相互交换,以形成一幅图画。
可悲的是,我的瓷砖不能互换。
有人知道为什么吗?
这是我的xml文件:

<ImageView
    android:id="@+id/image_4"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_7"
    app:layout_constraintEnd_toStartOf="@+id/image_5"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_3"
    app:layout_constraintTop_toBottomOf="@+id/image_1" />

<ImageView
    android:id="@+id/image_3"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_6"
    app:layout_constraintEnd_toStartOf="@+id/image_4"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/image_0"
    tools:srcCompat="@drawable/rect" />

<ImageView
    android:id="@+id/image_1"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_4"
    app:layout_constraintEnd_toStartOf="@+id/image_2"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_0"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_chainStyle="packed"
    tools:srcCompat="@drawable/rect" />

<ImageView
    android:id="@+id/image_2"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_5"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_1"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_chainStyle="packed"
    tools:srcCompat="@drawable/rect" />

<ImageView
    android:id="@+id/image_5"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_8"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_4"
    app:layout_constraintTop_toBottomOf="@+id/image_2" />

<ImageView
    android:id="@+id/image_8"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:layout_marginBottom="289dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_7"
    app:layout_constraintTop_toBottomOf="@+id/image_5" />

<ImageView
    android:id="@+id/image_0"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:layout_constraintBottom_toTopOf="@+id/image_3"
    app:layout_constraintEnd_toStartOf="@+id/image_1"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_chainStyle="packed"
    tools:srcCompat="@drawable/rect" />

<ImageView
    android:id="@+id/image_6"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:layout_marginBottom="289dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/image_7"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/image_3"
    tools:srcCompat="@drawable/rect" />

<ImageView
    android:id="@+id/image_7"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:layout_marginBottom="289dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/image_8"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/image_6"
    app:layout_constraintTop_toBottomOf="@+id/image_4" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/floatingActionButton"
    android:layout_width="56dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:clickable="true"
    android:onClick="openCamera"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:srcCompat="@drawable/photo_camera_white_18dp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginBottom="32dp"
    android:onClick="initialize"
    android:text="New Game"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

这是我的mainactivity:公共类mainactivity扩展了appcompatactivity实现view.ontouchlistener{

protected static final String TAG = "MainActivity";
protected ImageView[] buttons = new ImageView[9];
protected Bitmap[] grid = new Bitmap[9];
protected List<Bitmap> shuffled;
protected int emptyButton;
float deltaX, deltaY, initialX, initialY;
boolean actionUp;
int[][] startOrder = new int[3][3];
int activeField;
int emptyField;

@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttons[0] = findViewById(R.id.image_0);
    buttons[1] = findViewById(R.id.image_1);
    buttons[2] = findViewById(R.id.image_2);
    buttons[3] = findViewById(R.id.image_3);
    buttons[4] = findViewById(R.id.image_4);
    buttons[5] = findViewById(R.id.image_5);
    buttons[6] = findViewById(R.id.image_6);
    buttons[7] = findViewById(R.id.image_7);
    buttons[8] = findViewById(R.id.image_8);

    for (ImageView b : buttons) {
        b.setOnTouchListener(this);
    }

    prepareGrid();

    findViewById(R.id.shuffle).setOnClickListener((View view) -> {
        if (view.getId() == R.id.shuffle) shuffle();
    });
}

public void openCamera(View view) {
    Intent intent = new Intent(this, CameraActivity.class);
    startActivity(intent);
}

public void prepareGrid() {
    File picture = new File(getFilesDir(), "my_picture.jpg");
    if (picture.isFile()) {
        try {
            Bitmap source = BitmapFactory.decodeStream(new FileInputStream(picture));
            grid = cut(crop(source));
            shuffle();
            emptyButton = 8;
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}

public void shuffle() {
    shuffled = new ArrayList<>(Arrays.asList(grid));
    int position = 8, counter = 0;
    do {
        int nextToPos = new Random().nextInt(4);
        if (nextToPos == 0 && position-3 >= 0) {
            Collections.swap(shuffled, position, position-3);
            position -= 3;
        } else if (nextToPos == 1 && position+1 <= 8 && position != 2 && position != 5) {
            Collections.swap(shuffled, position, position+1);
            position++;
        } else if (nextToPos == 2 && position+3 <= 8) {
            Collections.swap(shuffled, position, position+3);
            position += 3;
        } else if (nextToPos == 3 && position-1 >= 0 && position != 3 && position != 6) {
            Collections.swap(shuffled, position, position-1);
            position--;
        }
        counter++;

        if (counter > 600) {
            while (position < 8) {
                if (position + 3 <= 8) {
                    Collections.swap(shuffled, position, position + 3);
                    position += 3;
                }
                if (position + 1 <= 8 && position != 2 && position != 5) {
                    Collections.swap(shuffled, position, position + 1);
                    position++;
                }
            }
            break;
        }
    } while (position != 8 || counter < 200);

    for (int i = 0; i < 8; i++) {   //befüllt die ib mit den kleinen teilbildern
        buttons[i].setImageBitmap(shuffled.get(i));
    }

    buttons[8].setImageBitmap(null);        //macht den 9ten button empty
    for (ImageView imageButton: buttons) imageButton.setEnabled(true);
    emptyButton = 8;
}

public Bitmap[] cut(Bitmap source) {
    Bitmap[] grid = new Bitmap[9];
    int size = source.getHeight() / 3;

    int i = 0;
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) { //schneidet des bild zurecht
            grid[i] = Bitmap.createBitmap(source, col * size, row * size, size, size);
            i++;
        }
    }

    return grid;
}

public Bitmap crop(Bitmap source) {
    int x = 0, y = 0, size;

    Matrix matrix = new Matrix();
    matrix.postRotate(90);  //weils sonst schief is

    if (source.getHeight() > source.getWidth()) { //portrait
        size = source.getWidth();
        y = (source.getHeight() - size) / 2;
    } else { //landscape
        size = source.getHeight();
        x = (source.getWidth() - size) / 2;
    }
    return Bitmap.createBitmap(source, x, y, size, size, matrix, true);
}

@RequiresApi(api = Build.VERSION_CODES.N)
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent event) {
    int action = event.getAction();

    if (view instanceof ImageButton) {
        ImageButton clickedButton = (ImageButton) view;
        final double BUTTON_WIDTH = buttons[emptyButton].getWidth() / 2.0;
        if ((emptyButton-1 >= 0 && buttons[emptyButton-1] == clickedButton) ||
                (emptyButton-3 >= 0 && buttons[emptyButton-3] == clickedButton) ||
                (emptyButton+1 < buttons.length && buttons[emptyButton+1] == clickedButton)||
                (emptyButton+3 < buttons.length && buttons[emptyButton+3] == clickedButton)) {

            switch (action) {
                case MotionEvent.ACTION_DOWN:

                    /*deltaX = view.getX() - event.getRawX();
                    deltaY = view.getY() - event.getRawY();
                    initialX = view.getX();
                    initialY = view.getY();
                    return true;*/
                    initialX = event.getX();
                    initialY = event.getY();
                    deltaX = view.getX() - event.getRawX();
                    deltaY = view.getY() - event.getRawY();
                    activeField = Integer.parseInt(view.getTag().toString());
                    break;

                case MotionEvent.ACTION_UP:
                    deltaX = event.getX() - initialX;
                    deltaY = event.getY() - initialY;

                    if (Math.abs(deltaX) > Math.abs(deltaY)) {
                        if (deltaX > 0) {
                            //rechts
                            if (checkRightBorder() && checkEmptyFeld(1)) {
                                updateOrder();
                                view.animate()
                                        .x(view.getX() + view.getWidth())
                                        .start();
                            } else {
                                check();
                                break;
                            }check();
                        } else {
                            //links
                            if (checkLeftBorder() && checkEmptyFeld(-1)) {
                                updateOrder();
                                view.animate()
                                        .x(view.getX() - view.getWidth())
                                        .start();
                            } else {
                                check();
                                break;
                            }
                        }check();
                    } else {
                        if (deltaY > 0)
                            //runter
                            if (checkVerticalBorder(2) && checkEmptyFeldVertical(1)) {
                                updateOrderVertical(1);
                                view.animate()
                                        .y(view.getY() + view.getWidth())
                                        .start();
                                check();
                            } else {
                                check();
                                break;
                            }
                        else
                            //rauf
                            if (checkVerticalBorder(0) && checkEmptyFeldVertical(-1)) {
                                updateOrderVertical(-1);
                                view.animate()
                                        .y(view.getY() - view.getWidth())
                                        .start();
                                check();
                            } else {
                                check();
                                break;
                            }
                    }
                    /*if (isIncreasingSequence()) {
                        Toast.makeText(this, "gewonen", Toast.LENGTH_LONG).show();
                        buttons[8].setImageBitmap(grid[emptyButton]);
                    }*/
                    check();
                    break;
                    default:
                    return false;
            }
        }
    }
    return true;
}
//------------------------------------------------check-methods--------------------------------------
@RequiresApi(api = Build.VERSION_CODES.N)
public Boolean checkLeftBorder() {
    for (int[] ints : startOrder) {
        if (Arrays.stream(ints).anyMatch(x -> x == activeField)) {
            int index = findIndex(ints, activeField);
            return (index > 0);
        }
    }
    return true;
}@RequiresApi(api = Build.VERSION_CODES.N)
public Boolean checkRightBorder() {
    for (int[] ints : startOrder) {
        if (Arrays.stream(ints).anyMatch(x -> x == activeField)) {
            int index = findIndex(ints, activeField);
            return (index < 2);
        }
    }
    return true;
}
@RequiresApi(api = Build.VERSION_CODES.N)
public Boolean checkVerticalBorder(int row) {
    return Arrays.stream(startOrder[row]).noneMatch(x -> x == activeField);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public Boolean checkEmptyFeld(int col) {
    for (int[] ints : startOrder) {
        if (Arrays.stream(ints).anyMatch(x -> x == activeField)) {
            int index = findIndex(ints, activeField);
            return (ints[index + col] == emptyField);
        }
    }
    return false;
}
@RequiresApi(api = Build.VERSION_CODES.N)
private boolean checkEmptyFeldVertical(int i) {
    int row = 0;
    for (int[] ints : startOrder) {
        if (Arrays.stream(ints).anyMatch(x -> x == activeField)) {
            int activeIndex = findIndex(startOrder[row], activeField);
            int emptyIndex = findIndex(startOrder[row + i], emptyField);
            return (activeIndex == emptyIndex);
        }
        row++;
    }
    return false;
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void updateOrder() {
    int col = 0;
    for (int[] ints : startOrder) {
        if (Arrays.stream(ints).anyMatch(x -> x == activeField)) {
            int index = findIndex(ints, activeField);
            int indexEmpty = findIndex(ints, emptyField);
            int temp = startOrder[col][index];
            startOrder[col][index] = startOrder[col][indexEmpty];
            startOrder[col][indexEmpty] = temp;
        }
        col++;
    }
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void updateOrderVertical(int j) {
    for (int i = 0; i < 3; i++) {
        if (Arrays.stream(startOrder[i]).anyMatch(x -> x == activeField)) {
            int index = findIndex(startOrder[i], activeField);
            int temp = startOrder[i][index];
            startOrder[i][index] = startOrder[i + j][index];
            startOrder[i + j][index] = temp;
            break;
        }
    }
}
public static int findIndex(int[] arr, int t) {
    if (arr == null) {
        return -1;
    }
    int len = arr.length;
    int i = 0;

    while (i < len) {
        if (arr[i] == t) {
            return i;
        } else {
            i = i + 1;
        }
    }
    return -1;
}

public void animateY(View view, float y, int duration) {
    view.animate()
            .y(y)
            .setDuration(duration)
            .start();
}

public void animateX(View view, float x, int duration) {
    view.animate()
            .x(x)
            .setDuration(duration)
            .start();
}

public void swap(int imageButtonPosition, int emptyButtonPosition) {
    ImageView emptyButton = buttons[emptyButtonPosition];
    buttons[emptyButtonPosition] = buttons[imageButtonPosition];
    buttons[imageButtonPosition] = emptyButton;
}

public void check() {
    boolean end = true;
    for (int i = 0; i<buttons.length-1; i++) {
        Drawable drawable = buttons[i].getDrawable();
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        if (bitmap != grid[i]) {
            end = false;
        }
    }
    if (end) {
        buttons[8].setImageBitmap(grid[8]);
        for (ImageView imageButton : buttons) imageButton.setEnabled(false);
    }
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题