该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
public void paintNextOne(Graphics g) {//paint next square which will be created at the top right corner
if (nextsquare == null) {
return;
}
Cell[] cells = nextsquare.grids;
for (int i = 0; i < cells.length; i++) {
Cell cell = cells[i];
int x = (cell.getCol() + 10) * size;
int y = (cell.getRow() + 1) * size;
g.drawImage(cell.getImage(), x, y, null);
}
}
public static final int size= 26;//26x26pixel for 1 cell
private void paintWall(Graphics g) {
for (int row = 0; row < wall.length; row++) {
for (int col = 0; col < wall[row].length; col++) {
int x = col * size;
int y = row * size;
Cell cell = wall[row][col];
if (cell == null) {
} else {
g.drawImage(cell.getImage(), x, y, null);
}
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("bzhangk1405206’s Tetris");
Tetris tetris = new Tetris();
frame.add(tetris);
frame.setSize(525, 600);
frame.setAlwaysOnTop(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
tetris.action();
}
public void action() {
square = Squares.randomOne();
nextsquare = Squares.randomOne();
state = RUNNING;
this.repaint();
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {//use mouse event to control the movement of the square
int i = e.getButton();
if (i == MouseEvent.BUTTON1)
Tetris.this.moveLeft();
if (i == MouseEvent.BUTTON2)
Tetris.this.rotate();
if (i == MouseEvent.BUTTON3)
Tetris.this.moveRight();
repaint();
}
//If mouse exit from the frame, the game will pause, and start again when the mouse come back
public void mouseEntered(MouseEvent e) {
if (state == PAUSE) {
state = RUNNING;
}
}
@Override
public void mouseExited(MouseEvent e) {
if (state != GAME_OVER) {
state = PAUSE;
}
}
});
this.setFocusable(true);
this.requestFocus();
// control the drop of the square
//every 0.4 seconds, the square will drop down one row
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
speed =26;
if (state == RUNNING) {
DropAction();
}
repaint();
}
}, 400, 400);
}
public void rotate() {
square.rotate();
}
public void moveRight() {
square.moveRight();
if (outOfBounds() || coincide()) {
square.moveLeft();
}
}
public void moveLeft() {
square.moveLeft();
if (outOfBounds() || coincide()) {
square.moveRight();
}
}
// Check whether the cells already been used, so each squares will not cover each other
private boolean coincide() {
Cell[] cells = square.grids;
for (int i = 0; i < cells.length; i++) {
Cell cell = cells[i];
int row = cell.getRow();
int col = cell.getCol();
if (wall[row][col] != null) {
return true;
}
}
return false;
}
// Check whether the grids of the squares out the boundary , left or right or top
private boolean outOfBounds() {
Cell[] cells = square.grids;
for (int i = 0; i < cells.length; i++) {
Cell cell = cells[i];
int row = cell.getRow();
int col = cell.getCol();
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return true;
}
}
return false;
}