N
N
Nikolay Razumovsky2020-11-27 15:01:46
Java
Nikolay Razumovsky, 2020-11-27 15:01:46

How to make the code better?

In order to study programming, I am making a game 2048 in java. The game has a class in which there are many repeating fragments - field iteration cycles. The question is, is it possible to create such a method that will take the values ​​​​of the enumeration boundaries and the executable code?

Something like this:

public void fun(int borderX, int borderY, ??? code){
  for (int x = 0; x < borderX; x++)
    for (int y = 0; y < borderY; y++)
      do code
}


If not, can you recommend how to make the code better? Thank you for your attention.

Actually, the code
public class Field {
  private int[][] field; // игровое поле
  private int width, heigth; // размеры поля

  public Field(int sizeX, int sizeY) { // инициализатор
    this.width = sizeX;
    this.heigth = sizeY;
    this.field = new int[sizeX][sizeY];
  }

  public int getCell(int x, int y) { // показать значение ячейки
    return this.field[x][y];
  }

  public void setCell(int val, int x, int y) { // присвоить ячейке значение
    this.field[x][y] = val;
  }

  public void reset() { // сбросить поле (новая игра, рестарт)
    for (int x = 0; x < width; x++)
      for (int y = 0; y < heigth; y++)
        this.field[x][y] = 0;
  }

  public void copyOf(Field f) { // копировать значения клеток поля (для функции отмена хода)
    for (int x = 0; x < width; x++)
      for (int y = 0; y < heigth; y++)
        this.field[x][y] = f.getCell(x, y);
  }

  public boolean isEqualTo(Field f) { // для проверки: привело ли нажатие на клавишу к смещению плиток?
    for (int x = 0; x < width; x++)
      for (int y = 0; y < heigth; y++)
        if (field[x][y] != f.getCell(x, y))
          return false;
    return true;
  }

  private boolean canMergeY() { // можно ли сдвинуть плитки по вертикали?
    for (int x = 0; x < width; x++)
      for (int y = 0; y < heigth - 1; y++)
        if (field[x][y] == field[x][y + 1])
          return true;
    return false;
  }

  private boolean canMergeX() { // можно ли сдвинуть плитки по горизонтали?
    for (int x = 0; x < width - 1; x++)
      for (int y = 0; y < heigth; y++)
        if (field[x][y] == field[x + 1][y])
          return true;
    return false;
  }

  public boolean canMerge() { // проверка на возможность продолжения игры
    return canMergeX() && canMergeY();
  }

  public boolean contains(int i) { // для поиска плиток 0 и 2048 для разных задач
    for (int x = 0; x < width; x++)
      for (int y = 0; y < heigth; y++)
        if (field[x][y] == i)
          return true;
    return false;
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-11-27
@frenneruruu

Yes, you can, using lambda functions. These are anonymous functions. In your case, you need an interface like this:

@FunctionalInterface
interface BiIntFunction {
    void apply(x: int, y: int);
}

и применять примерно так:
void doSomething(int borderX, int borderY, body: BiIntFunction) {
    for (int x = 0; x < borderX; x++) {
        for (int y = 0; y < borderY; y++) {
           body.apply(x, y);
        }
    }
}
//....
doSomething(sizeX, sizeY, (x, y) -> { ... your code here ... });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question