俄罗斯方块java
时间: 2023-09-28 17:03:45 浏览: 94
俄罗斯方块Java
俄罗斯方块是一款经典的游戏,Java也是一门适合游戏开发的语言。下面是一个简单的俄罗斯方块游戏的Java代码示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tetris extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private final int WIDTH = 10;
private final int HEIGHT = 22;
private final int BLOCK_SIZE = 30;
private int[][] board = new int[HEIGHT][WIDTH];
private Tetromino currentPiece;
private Tetromino[] pieces = {
new Tetromino(new int[][]{{1, 1, 1, 1}}, this, Color.cyan),
new Tetromino(new int[][]{{1, 1, 0}, {0, 1, 1}}, this, Color.orange),
new Tetromino(new int[][]{{0, 1, 1}, {1, 1, 0}}, this, Color.blue),
new Tetromino(new int[][]{{1, 1, 0}, {1, 1, 0}}, this, Color.yellow),
new Tetromino(new int[][]{{1, 0, 0}, {1, 1, 1}}, this, Color.green),
new Tetromino(new int[][]{{0, 0, 1}, {1, 1, 1}}, this, Color.pink),
new Tetromino(new int[][]{{1, 1}, {1, 1}}, this, Color.red)
};
public Tetris() {
setPreferredSize(new Dimension(WIDTH * BLOCK_SIZE, HEIGHT * BLOCK_SIZE));
setBackground(Color.black);
addKeyListener(this);
newPiece();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (board[i][j] != 0) {
g.setColor(Color.gray);
g.fillRect(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
g.setColor(Color.white);
g.drawRect(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}
}
}
currentPiece.draw(g);
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
currentPiece.move(-1, 0);
break;
case KeyEvent.VK_RIGHT:
currentPiece.move(1, 0);
break;
case KeyEvent.VK_DOWN:
currentPiece.move(0, 1);
break;
case KeyEvent.VK_UP:
currentPiece.rotate();
break;
case KeyEvent.VK_SPACE:
currentPiece.drop();
break;
}
repaint();
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public int getBlockSize() {
return BLOCK_SIZE;
}
public int[][] getBoard() {
return board;
}
public Tetromino[] getPieces() {
return pieces;
}
public void newPiece() {
Random r = new Random();
currentPiece = pieces[r.nextInt(pieces.length)];
currentPiece.setX(WIDTH / 2 - currentPiece.getPiece()[0].length / 2);
currentPiece.setY(0);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Tetris");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new Tetris(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这个代码示例中,我们使用了Java Swing库进行界面的开发,并且使用了一个Tetromino类来表示俄罗斯方块中的方块。在程序中,我们使用了一个二维数组来表示游戏区域中的方块,并且通过键盘事件来控制方块的移动和旋转。
阅读全文