Implemented an almost working game Fifteen.
On the move, a random arrangement of 4x4 buttons (0-15, where 0 is invisible, it is empty) appears, in which by pressing, the buttons are swapped (an empty button changes with another one having a number). More precisely, only the names of the buttons change. The problem is that you can change the empty button with any of the 15 remaining ones. How to realize that only neighboring buttons change ?
Please need a hint. The RandomNumbers method creates a random arrangement, CreateButtons creates them.

public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button [] [] buttons; LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout = findViewById(R.id.linearlayout); createButton(); } int empty_x,empty_y; private void createButton() { LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); button_params.weight=1; LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layout_params.weight=1; buttons= new Button[4][4]; int [] textNumber=randomNumbers(); int cnt=0; for (int i=0;i<buttons.length;i++) { LinearLayout linearLayout = new LinearLayout(this); for (int j=0;j<buttons[i].length;j++) { buttons[i][j] = new Button(this); buttons[i][j].setOnClickListener(this); if (textNumber[cnt]==0){ buttons[i][j].setEnabled(false); empty_x=i; empty_y=j; } else { buttons[i][j].setText(""+textNumber[cnt]); } cnt++; buttons[i][j].setTag(i+"#"+j); linearLayout.addView(buttons[i][j],button_params); } layout.addView(linearLayout,layout_params); } } // для получения случайных чисел на кнопках public int[] randomNumbers(){ int[] numbers = new int[16]; for (int i = 0; i <numbers.length ; i++) { numbers[i]=i; } for (int i = 0; i <numbers.length ; i++) { int idx=(int)Math.random()*15; //получаем случайное число (0-15) int temp = numbers[idx]; numbers[idx] = numbers[i]; numbers[i] = temp; } return numbers; } @Override public void onClick(View view) { String xy=view.getTag().toString(); int current_x = Integer.parseInt(xy.split("#")[0]); int current_y = Integer.parseInt(xy.split("#")[1]); String text= buttons[current_x][current_y].getText().toString(); buttons[current_x][current_y].setText(""); buttons[current_x][current_y].setEnabled(false); buttons[empty_x][empty_y].setEnabled(true); buttons[empty_x][empty_y].setText(text); empty_x=current_x; empty_y=current_y; }} 
  • five
    The buttons are adjacent if the sum of the modules of the deltas of their coordinates is 1. - Yaant

0