import java.awt.*; public class TetrisBlock { // Class constants. private final int cols = 10; private final int rows = 20; private final int block_size = 25; private final int x_margin = 25; private final int y_margin = 25; // Block attributes. Color color; int pos_x; int pos_y; public TetrisBlock (int color, int x, int y) { pos_x = x; pos_y = y; // Set the color according to the official Tetris definitions. switch(color) { case 0: this.color = Color.GRAY; break; case 1: this.color = Color.CYAN; break; case 2: this.color = Color.YELLOW; break; case 3: this.color = Color.MAGENTA; break; case 4: this.color = Color.GREEN; break; case 5: this.color = Color.RED; break; case 6: this.color = Color.BLUE; break; case 7: this.color = Color.ORANGE; break; } } // Move the block down one row. public void moveDown() { pos_y++; } // Move the block left a column. public void moveLeft() { pos_x--; } // Move the block right a column. public void moveRight() { pos_x++; } // Change the block's position an arbitrary number of columns and rows. public void modifyPosition(int x, int y) { pos_x += x; pos_y += y; } // Return whether the block can move down within the matrix. public boolean checkDown(TetrisMatrix tm) { return (pos_y < rows - 1 && !(tm.positionEmpty(pos_x, pos_y+1))); } // Check whether the block is in a valid location within the matrix (for verifying game over). public boolean checkPosition(TetrisMatrix tm) { return (pos_y < rows && pos_x >= 0 && pos_x < cols && pos_y >= 0 && !(tm.positionEmpty(pos_x, pos_y))); } // Check to see if the block is in a valid rotation position (for rotating at the top of the screen). public boolean checkRotatePosition(TetrisMatrix tm) { return (pos_y < rows && pos_x >= 0 && pos_x < cols && !(tm.positionEmpty(pos_x, pos_y))); } // See if the block can move left. public boolean checkLeft(TetrisMatrix tm) { return (pos_x > 0 && !(tm.positionEmpty(pos_x-1, pos_y))); } // See if the block can move right. public boolean checkRight(TetrisMatrix tm) { return (pos_x < cols - 1 && !(tm.positionEmpty(pos_x+1, pos_y))); } // Get the current x position of the block. public int getX () { return pos_x; } // Get the current y position of the block. public int getY () { return pos_y; } // Draw the block. public void draw(Graphics g) { if (pos_y > -1) { // Outline g.setColor(Color.black); g.fillRect(pos_x*block_size + x_margin, pos_y * block_size + y_margin, block_size, block_size); // Inside g.setColor(color); g.fillRect(pos_x*block_size + x_margin + 1, pos_y * block_size + y_margin + 1, block_size - 2, block_size - 2); } } }