使用java简单实现俄罗斯方块小游戏
时间: 2024-01-01 17:06:27 浏览: 27
很高兴回答你的问题!以下是一个简单的使用Java实现俄罗斯方块小游戏的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TetrisGame extends JFrame {
private final int WIDTH = 10;
private final int HEIGHT = 20;
private final int SQUARE_SIZE = 30;
private final int BOARD_X = 10;
private final int BOARD_Y = 30;
private final int FPS = 60;
private Timer gameTimer;
private Tetromino currentPiece;
private Board board;
public TetrisGame() {
setTitle("Tetris");
setSize(WIDTH * SQUARE_SIZE + 2 * BOARD_X, HEIGHT * SQUARE_SIZE + 2 * BOARD_Y);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
board = new Board(WIDTH, HEIGHT);
currentPiece = new Tetromino();
gameTimer = new Timer(1000 / FPS, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
handleKeyPress(e.getKeyCode());
}
});
setVisible(true);
gameTimer.start();
}
private void update() {
if (!board.isGameOver()) {
currentPiece.update();
if (board.isCollision(currentPiece)) {
currentPiece.undo();
board.addPiece(currentPiece);
currentPiece = new Tetromino();
if (board.isCollision(currentPiece)) {
board.setGameOver(true);
gameTimer.stop();
}
}
}
}
private void handleKeyPress(int keyCode) {
if (!board.isGameOver()) {
switch (keyCode) {
case KeyEvent.VK_LEFT:
currentPiece.moveLeft();
if (board.isCollision(currentPiece)) {
currentPiece.moveRight();
}
break;
case KeyEvent.VK_RIGHT:
currentPiece.moveRight();
if (board.isCollision(currentPiece)) {
currentPiece.moveLeft();
}
break;
case KeyEvent.VK_DOWN:
currentPiece.moveDown();
if (board.isCollision(currentPiece)) {
currentPiece.moveUp();
board.addPiece(currentPiece);
currentPiece = new Tetromino();
if (board.isCollision(currentPiece)) {
board.setGameOver(true);
gameTimer.stop();
}
}
break;
case KeyEvent.VK_SPACE:
currentPiece.rotate();
if (board.isCollision(currentPiece)) {
currentPiece.rotateBack();
}
break;
}
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.translate(BOARD_X, BOARD_Y);
board.draw(g);
currentPiece.draw(g);
}
public static void main(String[] args) {
new TetrisGame();
}
}
```
这是一个简单的俄罗斯方块游戏,使用了Java的Swing库进行界面的绘制和事件的处理。游戏中,使用方向键控制方块的移动,空格键控制方块的旋转。
希望这个示例代码对你有所帮助!如果有任何疑问,请随时提问。