-2

Good day, so I intend for my code to loop through my array and increment the row index of object by 1 position. I used timer task because I want the object to move forward after certain amount of time. This is the code I have tried. I have looked but I have struggled to find solution relevant to my problem. Would appreciate the help.

class cat_function extends TimerTask {
    public void run() {
        synchronized (game.board) {
            for (int i = 0; i < game.board.length; i++) {
                for (int k = 0; k < game.board[0].length; k++) {
                    if (game.board[i][k] instanceof cat) {
                        cat garfield = new cat(0, 0);
                        game.board[i][k] = garfield;
                        game.board[i][k + 1] = garfield;
                    }
                }
            }
        }
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    Please clarify what you mean by _"increment the row index of object"_. Currently, on every iteration you are adding a new `cat` instance to the board. – Jim Garrison Jan 12 '21 at 22:19
  • I want to use the timertask class to move "cat" up one row every 1 second – king123456 Jan 12 '21 at 22:40

1 Answers1

-1

Assuming:

  • game.board is defined as a Cat[][]
  • an empty cell's value is null

Then all you have to do is

                if (game.board[i][k] instanceof cat) {
                    game.board[i][k + 1] = game.board[i][k];  // Put cat in new location
                    game.board[i][k] = null;                  // Remove cat from previous location
                }

However, this code still has two problems

  1. What do you do when you reach the edge of the board. You'll have to add logic to make it do something different so you don't fall of the edge.
  2. There's no need to scan the entire game board every time just to find the Cat. Keep the cat's location (indexes) separately so you always know where it is and don't have to look for it.
  3. If there can be more than one cat on the board you will also need logic to decide what happens if two cats "collide" when moving (i.e. you try to move a cat into a cell that already contains a cat).

Solving those problems is left as an exercise for you.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190