package sunshine.ikurs.kz.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
//Объявляем массив кнопок
Button [] B;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Создаем массив кнопок.
B=new Button[16];
//Записываем кнопки в массив.
B[0]=(Button)findViewById(R.id.button1);
B[1]=(Button)findViewById(R.id.button2);
B[2]=(Button)findViewById(R.id.button3);
B[3]=(Button)findViewById(R.id.button4);
B[4]=(Button)findViewById(R.id.button5);
B[5]=(Button)findViewById(R.id.button6);
B[6]=(Button)findViewById(R.id.button7);
B[7]=(Button)findViewById(R.id.button8);
B[8]=(Button)findViewById(R.id.button9);
B[9]=(Button)findViewById(R.id.button10);
B[10]=(Button)findViewById(R.id.button11);
B[11]=(Button)findViewById(R.id.button12);
B[12]=(Button)findViewById(R.id.button13);
B[13]=(Button)findViewById(R.id.button14);
B[14]=(Button)findViewById(R.id.button15);
B[15]=(Button)findViewById(R.id.button16);
}
//Функция смены кнопок Swap(B[2],B[3]);
public void Swap(Button B1, Button B2)
{
if (B2.getVisibility() == View.INVISIBLE)
{
B2.setVisibility(View.VISIBLE);
B1.setVisibility(View.INVISIBLE);
String Tmp = B1.getText().toString();
B1.setText(B2.getText());
B2.setText(Tmp);
}
}
public void buttonOnClick(View V) {
//Получаем текущую кнопку по которой кликнули
Button current = (Button)V;
//Получаем номер кнопки из тега кторый задали в XML файле в текстовом режиме редактирования
String N=current.getTag().toString();
//преобразуем тег из строки в целое число
int n = Integer.parseInt(N)-1;
//рассчитываем номер строки путем целочисленного деления
int y = n / 4;
//вычисляем столбец
int x = n;
if (n >= 12) x = n - 12;
else
if (n >= 8) x = n - 8;
else
if (n >= 4) x = n - 4;
//Рассчитываем номер кнопки сверху снизу слева справа и записываем в переменные
//NT NL NR NB NC (Top Left Right Bottom Current)
int nc = y * 4 + x;
int nt = (y - 1) * 4 + x;
int nb = (y + 1) * 4 + x;
int nl= y * 4 + x-1;
int nr = y * 4 + x + 1;
//Проверяем существование кнопки слева справа снизу сверху
//Если существует то пытаемся поменять кнопки местами
if (y - 1 >= 0)
Swap(B[nc], B[nt]);
if (y + 1 < 4)
Swap(B[nc], B[nb]);
if (x - 1 >= 0)
Swap(B[nc], B[nl]);
if (x + 1 < 4)
Swap(B[nc], B[nr]);
}
}