# Collision detection

## Recommended Posts

I am asked to do the following:

[B]Write a method in the Board class that takes a row and column index and a two-dimensional array as parameters, and checks to see that the non-zero entries of the given array correspond to empty positions on the grid, assuming that the given array's upper left were positioned at the given row and column. You'll use this to determine if a piece can move into a given position.[/B]

So I have a Piece object and two variable currentX and currentY. I am assuming those will be passed into the method described above. currentX and currentY represent the top corner of the shapes. Now, how do I implement collision detection? I think we need to have 2 for loops and find the indexes of the [B]shape array[/B] that contains 1. After that, I might have to create an array of the same size as [B]shape array[/B] and then do two for loops to see if there is a collision if the shape moves below.

So I need to have 3 methods implementing the same logic. One for move right, another for move left and another for move down, right? Isn't there a simpler method?

Code:

import java.awt.*;

public class Board extends Grid {
public static final int COLUMNS = 16;
public static final int ROWS = 32;
public static final Color BLUE = new Color(0,0,128,40);

public Board() {
super(new int[ROWS][COLUMNS]);
setSize(COLUMNS*Tetris.SQUARE_SIZE,
ROWS*Tetris.SQUARE_SIZE);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(BLUE);
paintStripes(g);
}

void paintStripes(Graphics g) {
for (int i = 0; i < COLUMNS; i += 4) {
g.fillRect(i*Tetris.SQUARE_SIZE,0,
Tetris.SQUARE_SIZE*2,Tetris.SQUARE_SIZE*ROWS);
}
}

}

Code:
public class PieceFactory {

public static final int[][] L1 =
{{1,1,0,0},
{0,1,0,0},
{0,1,0,0},
{0,0,0,0},
};

public static final int[][] L2 =
{{0,1,0,0},
{0,1,0,0},
{1,1,0,0},
{0,0,0,0},
};

public static final int[][] T =
{{0,1,0,0},
{1,1,0,0},
{0,1,0,0},
{0,0,0,0},
};

public static final int[][] BOX =
{{1,1,0,0},
{1,1,0,0},
{0,0,0,0},
{0,0,0,0},
};

public static final int[][] BAR =
{{1,1,1,1},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
};

public static final int[][] STEP1 =
{{1,0,0,0},
{1,1,0,0},
{0,1,0,0},
{0,0,0,0},
};

public static final int[][] STEP2 =
{{0,1,0,0},
{1,1,0,0},
{1,0,0,0},
{0,0,0,0},
};

public static final int[][][] SHAPES = {L1,L2,T,BOX,BAR,STEP1,STEP2};

public static Piece createPiece() {
int[][] s = SHAPES[(int) (Math.random()*SHAPES.length)];
switch ((int) (Math.random()*10)) {
case 0:
case 1:
case 2:
case 3:
default: return new Piece(s);
}

}

}

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Tetris extends JFrame implements KeyListener {
public static final int SQUARE_SIZE = 10; // 10 by 10 pixels

static Board board;
static Tetris game;

JPanel mainPanel;
public Piece currentPiece;
int score = 0;
JButton scoreButton;

public Tetris() {
super("Tetris");
game = this;
Container pane = getContentPane();
pane.setLayout(new BorderLayout());

scoreButton = new JButton("0");
scoreButton.setEnabled(false);

board = new Board();
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.setPreferredSize
(new Dimension(Board.COLUMNS*SQUARE_SIZE,
Board.ROWS*SQUARE_SIZE));

public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
pack();
show();
setResizable(false);
}

score += v;
scoreButton.setText(""+score);
}

public int getScore() {
return score;
}

static Board getBoard() {
return board;
}

static Tetris getGame() {
return game;
}

static void sleep(int milliseconds) {
try {
} catch (InterruptedException ie) {
}
}

public static void main(String[] args) {
Tetris game = new Tetris();
while (true) {
game.dropPiece();
}
}

void dropPiece() {
currentPiece = PieceFactory.createPiece();
currentPiece.repaint();
currentPiece.fall();
//mainPanel.remove(currentPiece);
board.repaint();
}

public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
switch (key) {
case KeyEvent.VK_UP:  // up arrow
case KeyEvent.VK_KP_UP:
currentPiece.rotateCounterclockwise();
break;
case KeyEvent.VK_DOWN:  // down arrow
case KeyEvent.VK_KP_DOWN:
currentPiece.rotateClockwise();
break;
case KeyEvent.VK_LEFT:  // left arrow
case KeyEvent.VK_KP_LEFT:
currentPiece.moveLeft();
break;
case KeyEvent.VK_RIGHT:  // right arrow
case KeyEvent.VK_KP_RIGHT:
currentPiece.moveRight();
break;
case KeyEvent.VK_SPACE:  //  space bar
currentPiece.drop();
}
}

public void keyReleased(KeyEvent arg0) {
}

public void keyTyped(KeyEvent arg0) {
}

}

Code:

public class Piece extends Grid {
int currentX;     // current X location on the board
double currentY;  // current Y location on the board

public Piece(int shape[][]) {
super(shape);
currentX = 7;
currentY = 2;
updateLocation();
}

public Piece(int shape[][], currentX, currentY) {
super(shape);
this.currentX = currentX;
this.currentY = currentY;
updateLocation()
}

setSize(Tetris.SQUARE_SIZE*getColumns(),
Tetris.SQUARE_SIZE*getRows());
}

void updateLocation() {
setLocation(Tetris.SQUARE_SIZE*currentX,
(int) (Tetris.SQUARE_SIZE*currentY));
}

synchronized void moveDown() {

}

synchronized void moveLeft() {
currentX--;
updateLocation();
}

synchronized void moveRight() {
currentX++;
updateLocation();
}

synchronized void rotateClockwise() {
int x = currentX;
int y = currentY;

currentPiece = new Piece(s, x, y);

updateLocation();
}

synchronized void rotateCounterclockwise() {
}

void fall() {
// replace the following by your code
Tetris.sleep(2000);
}

synchronized void drop() {
currentY++;
updateLocation();
}

public static int [][] multiplyMatrix(int [][] m1)
{
int [][] m2 =
{{0,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,0},
};

int[][] result = new int[4][4];

// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
if (m1[i][k] * m2[k][j] > 0)
{
result[i][j] = 1;
}
else
{
result[i][j] = 0;
}

return result;
}

}


##### Share on other sites
You can try checking for collision after the movement is done. If there is a collision, then undo the move. I think that will work for all three directions.

##### Share on other sites
Define current x by x argument. Define current y by y argument. Define j and k as zero. If piece [j,k] is occupied and board [x,y] is occupied then collision occurred. Otherwise increase x and j by one. If j is equal to four then subtract four from j and x and increase y and k by one. If k is equal to four then the process is complete and no collision occurred. Otherwise continue testing.

Your code uses this 'Grid' class for pieces and boards. If you can add grids or extract grid sections then you could copy the board data, add the piece values to it, then check for any value '2' indicating collision. Is this a Java class or one of your own? Edited by Khatharr

##### Share on other sites

You can try checking for collision after the movement is done. If there is a collision, then undo the move. I think that will work for all three directions.

Thanks for answering. Can you tell me how to undo a move? Because the previous move isn't stored in a variable, so I have a hard time figuring out how to implement that.

##### Share on other sites

Define current x by x argument. Define current y by y argument. Define j and k as zero. If piece [j,k] is occupied and board [x,y] is occupied then collision occurred. Otherwise increase x and j by one. If j is equal to four then subtract four from j and x and increase y and k by one. If k is equal to four then the process is complete and no collision occurred. Otherwise continue testing.

Your code uses this 'Grid' class for pieces and boards. If you can add grids or extract grid sections then you could copy the board data, add the piece values to it, then check for any value '2' indicating collision. Is this a Java class or one of your own?

It's a code from someone else. I am quite sure about what Board does. Does it contain all the previous pieces, while Grid contains the falling piece. because that seems to be the case. I can't quite parse the code.

##### Share on other sites
    public boolean legalDown(int currentX, double currentY, int[][] board)
{
int x = currentX;
int y = currentY-1;

for (int row = 0; row < 4; row++)
{
for(int col = 0; col < 4; col++)
{
if (shape[row][col] == 0 && board[x+col][y]row] == 1)
{
return true;
}
else
{
return false;
}
}
}

}


Ok, I came up with this, but I don't know if I can access shape directly like this. If I don't pass shape as a parameter to the method. What would happen? Do I need to call it like this: currentPiece.legalDown? I am not sure. Also, I don't know if it would work. Also, there is no method to save the 1 and 0 of the previous pieces right now, right? I have to write it in Board, right?

##### Share on other sites
public class collisiontest
{

public static boolean legalDown(int currentX, int currentY, int[][] board, int[][] shape)
{
int x = currentX;
int y = currentY-1;

for (int row = 0; row < 4; row++)
{
for(int col = 0; col < 4; col++)
{

if (shape[row][col] == 0 && (board[x+col][y+row] == 0 || board[x+col][y+row] == 1))
{
return true;
}
else
{
if (shape[row][col] == 1 && board[x+col][y+row] == 0)
{
return true;
}
else
{
return false;
}
}
}
}

return true;
}

public static void main(String[] args)
{
int [][] m1 =
{{1,1,0,0},
{1,1,0,0},
{0,0,0,0},
{0,0,0,0},
};

int[][] board =
{{0,0,0,0},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
};

int[][] board2 =
{{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{1,1,0,0},
};

int currentX = 0;
int currentY = 4;

System.out.println(legalDown(currentX, currentY, board, m1));

}
}


Ok, I am trying to test the method, but it doesn't work it always returns true. I am trying to figure out why.

Oh yeah, and I need to know what variable contains the "board", because I have no idea.

Edited by concepts

##### Share on other sites
public class collisiontest
{

public static boolean legalDown(int currentX, int currentY, int[][] board, int[][] shape)
{
int x = currentX+1;
int y = currentY;

for (int row = 0; row < 4; row++)
{
for(int col = 0; col < 4; col++)
{

if (shape[row][col] == 1 && board[x+row][y+col] == 0)
{

}
else
{
if (shape[row][col] == 0 && board[x+row][y+col] == 1)
{

}
else
{

if(shape[row][col] ==0 && board[x+row][y+row] == 0)
{

}

else
{

return false;
}
}
}
}
}

return true;
}

public static void main(String[] args)
{
int [][] m1 =
{{1,1,0,0},
{1,1,0,0},
{0,0,0,0},
{0,0,0,0},
};

int[][] board =
{{0,0,0,0},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
};

int[][] board3 =
{{0,0,0,0},
{0,0,1,1},
{0,0,1,1},
{1,0,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
};

int[][] board2 =
{{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{1,1,0,0},
};

int currentX = 1;
int currentY = 0;

System.out.println(legalDown(currentX, currentY, board, m1));

System.out.println(legalDown(currentX, currentY, board3, m1));

System.out.println(legalDown(currentX, currentY, board2, m1));

}
}


It's working now

##### Share on other sites

Glad it's working. A few issues, though.

Do not do this:

if(condition) {
//do nothing
}
else {
//do something
}

Do this:

if(condition == false) {
//do something
}

Also, why are you testing every which case except the one you're actually looking for?

    for(int row = 0; row < 4; row++) {
for(int col = 0; col < 4; col++) {
if((shape[row][col] == 1) && (board[x+row][y+col] == 1)) {
return false;
}
}
}
return true;



Also, the x axis travels left and right. The y axis travels up and down. In this function you've inverted them. This won't cause a bug since the inversion is universal in the scope of the variables, but it can confuse people coming into the function and may lead them to do something incorrect since the variable names are misleading.

Edited by Khatharr

why?

Which part?

##### Share on other sites

It's not working as expected. There are plenty of bug that are caused by the fact that the legalDown method may go out of bound by checking what's outside of bound

##### Share on other sites

It somewhat works, but I need the pieces to move all the way down...



##### Share on other sites
public class collisiontest
{

public static boolean legalDownSpec(int currentX, int currentY, int[][] board, int[][] shape, int index)
{
int x = currentX+1;
int y = currentY;

for (int row = 0; row < index; row++)
{
for (int col = 0; col < index; col++)
{

if (shape[row][col] == 1 && board[x+row][y+col] == 0)
{

}
else
{
if (shape[row][col] == 0 && board[x+row][y+col] == 1)
{

}
else
{

if(shape[row][col] ==0 && board[x+row][y+row] == 0)
{

}

else
{

return false;
}
}
}
}
}

return true;
}

public static boolean legalDown(int currentX, int currentY, int[][] board, int[][] shape)
{
int x = currentX+1;
int y = currentY;

if (x >= 3)
{
int index = x;
index = 6-index;

return legalDownSpec(currentX, currentY, board, shape, index);

//call special code here
}

for (int row = 0; row < 4; row++)
{
for(int col = 0; col < 4; col++)
{

if (shape[row][col] == 1 && board[x+row][y+col] == 0)
{

}
else
{
if (shape[row][col] == 0 && board[x+row][y+col] == 1)
{

}
else
{

if(shape[row][col] ==0 && board[x+row][y+row] == 0)
{

}

else
{

return false;
}
}
}
}
}

return true;
}

public static void main(String[] args)
{
int [][] m1 =
{{1,0,0,0},
{1,0,0,0},
{1,0,0,0},
{1,0,0,0},
};

int[][] board =
{{0,0,0,0},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{1,0,1,1},
};

int[][] board3 =
{{0,0,0,0},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{0,0,1,1},
{1,1,1,1},
};

int[][] board2 =
{{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
};

int currentX = 7; //3 causes exception
int currentY = 0;

System.out.println(legalDown(currentX, currentY, board, m1));

System.out.println(legalDown(currentX, currentY, board3, m1));

System.out.println(legalDown(currentX, currentY, board2, m1));

}
}


I added legalDownSpec to solve the problem, but I get another problem instead. Actually, I still get Array Out Of Bound, but it seems to stop earlier. I think I need another method to check if the piece is out of bound

##### Share on other sites

the problem has to do with the rotate method that doesn't update the shape...

do you know how i can fix this, because I don't know which method I have to change.

Edited by concepts

##### Share on other sites

Some information that might be helpful

[B]In the Piece class, you'll want methods for moving the piece down, moving it left and right by one column, and for rotating the piece clockwise and counterclockwise 90 degrees. (You want these methods to be synchronized so that two modifications of the piece aren't attempted concurrently.) When a piece is rotated, the array changes shape (somewhat similar, but not exactly like, the transpose algorithm we did in class). Note: Each time you move a piece, call its updateLocation method so that it gets painted properly on the board. Similarly, each time you change the shape of a piece, call its updateSize method. You should only move or rotate a piece if it would be legal to do so. (The methods of the Board will be helpful for determining legality of a board position.)[/B]

    public static void addArray(int currentX, int currentY, int[][] board, int[][] shape)
{
int x = currentY;
int y = currentX;

for (int row = 0; row < 4; row++)
{
for(int col = 0; col < 4; col++)
{

if (shape[row][col] == 1 )
{

board[x+row][y+col] = 1;
}

}
}
}

    void fall(Board board) {

int [][] a = getContents();
int [][] b = board.getContents();

while(Board.legalDown(currentX, currentY, b, a) && Board.isNotOutOfBoundDown(currentX, currentY, b, a))
{
currentY++;
updateLocation();
Tetris.sleep(2000);

}

//Tetris.sleep(2000);
}

    synchronized void rotateClockwise(Board board) {

int [][] a = getContents();
int [][] b = board.getContents();

if(Board.legalDown(currentX, currentY, b, a) && Board.isNotOutOfBoundDown(currentX, currentY, b, a))
{
int [][] transpose = new int[4][4];
transpose = transpose(contents);
contents = multiplyMatrix(transpose);

updateLocation();
}
}

synchronized void rotateCounterclockwise(Board board) {

int [][] a = getContents();
int [][] b = board.getContents();

if(Board.legalDown(currentX, currentY, b, a) && Board.isNotOutOfBoundDown(currentX, currentY, b, a))
{
int [][] transpose2 = new int[4][4];
transpose2 = multiplyMatrix(contents);
transpose2 = transpose(transpose2);
contents = transpose2;

updateLocation();
}
}

i don't see anything wrong with the rotate methods

how can i debug the rotate methods?

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628278
• Total Posts
2981789

• 10
• 11
• 17
• 14
• 9