Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.mynumberspuzzle;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- import androidx.appcompat.app.AppCompatActivity;
- public class MainActivity extends AppCompatActivity {
- Puzzle myPuzzle;
- TextView tvMovesCount;
- Button[][] btnsBoard;
- int rows;
- int cols;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Intent intent = getIntent();
- rows = intent.getIntExtra("ROWS_COUNT", 4);
- cols = intent.getIntExtra("COLS_COUNT", 4);
- // Todo make code for general size
- myPuzzle = new Puzzle(rows, cols);
- btnsBoard = new Button[myPuzzle.getRows()][myPuzzle.getCols()];
- tvMovesCount = findViewById(R.id.tvMovesCount);
- for (int r = 0; r < myPuzzle.getRows(); r++) {
- for (int c = 0; c < myPuzzle.getCols(); c++) {
- int id = getResources().getIdentifier("button" + r + c, "id", getPackageName());
- Log.d("debug-id", id + "");
- btnsBoard[r][c] = findViewById(id);
- }
- }
- restart();
- }
- private void restart() {
- myPuzzle.restart();
- // display puzzle on screen
- tvMovesCount.setText(myPuzzle.getMovesCount() + "");
- for (int r = 0; r < myPuzzle.getRows(); r++) {
- for (int c = 0; c < myPuzzle.getCols(); c++) {
- btnsBoard[r][c].setText("" + myPuzzle.getBoard()[r][c]);
- btnsBoard[r][c].setVisibility(View.VISIBLE);
- }
- }
- btnsBoard[myPuzzle.getBlankRow()][myPuzzle.getBlankCol()].setVisibility(View.INVISIBLE);
- }
- public void handleClick(View view) {
- int clickedId = view.getId();
- int clickedRow = 0, clickedCol = 0;
- for (int r = 0; r < myPuzzle.getRows(); r++) {
- for (int c = 0; c < myPuzzle.getCols(); c++) {
- if (clickedId == btnsBoard[r][c].getId()) {
- clickedRow = r;
- clickedCol = c;
- }
- }
- }
- if (myPuzzle.move(clickedRow, clickedCol)) {
- for (int r = 0; r < myPuzzle.getRows(); r++) {
- for (int c = 0; c < myPuzzle.getCols(); c++) {
- btnsBoard[r][c].setText("" + myPuzzle.getBoard()[r][c]);
- btnsBoard[r][c].setVisibility(View.VISIBLE);
- }
- }
- btnsBoard[myPuzzle.getBlankRow()][myPuzzle.getBlankCol()].setVisibility(View.INVISIBLE);
- btnsBoard[myPuzzle.getBlankRow()][myPuzzle.getBlankCol()].setVisibility(View.INVISIBLE);
- tvMovesCount.setText(myPuzzle.getMovesCount() + "");
- }
- if (myPuzzle.isGameOver()) {
- Toast.makeText(this, "You win", Toast.LENGTH_LONG).show();
- }
- if (myPuzzle.getMovesCount() == 0) {
- restart();
- }
- }
- }
Add Comment
Please, Sign In to add comment