开发者代码

促销活动、技术干货、问题解答、技术讨论,学习,成长,分享,共建

俄罗斯方块java代码

2024-01-28 08:57:52 点击:160
俄罗斯方块java代码
俄罗斯方块是一款经典的游戏,也是很多程序员学习编程时的练手项目。下面是一个简单的用Java编写的俄罗斯方块游戏的代码示例,该示例基于Java Swing库实现游戏界面和游戏逻辑。


```java import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Random;


import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer;


public class TetrisBoard extends JPanel implements ActionListener, KeyListener {


private static final int BOARD_WIDTH = 10; private static final int BOARD_HEIGHT = 22; private static final int BLOCK_SIZE = 30; private static final int DELAY = 300;


private Timer timer; private boolean isFallingFinished = false; private boolean isStarted = false; private boolean isPaused = false; private int numLinesRemoved = 0; private int curX = 0; private int curY = 0; private ArrayList filledPositions = new ArrayList<>(); private Shape curPiece; private Shape.Tetrominoes[] board;


public TetrisBoard() { setFocusable(true); setPreferredSize(new Dimension(BOARD_WIDTH * BLOCK_SIZE, BOARD_HEIGHT * BLOCK_SIZE)); addKeyListener(this); board = new Shape.Tetrominoes[BOARD_WIDTH * BOARD_HEIGHT]; clearBoard(); timer = new Timer(DELAY, this); timer.start(); }


private void startGame() { if (isPaused) { return; } isStarted = true; isFallingFinished = false; numLinesRemoved = 0; clearBoard(); newPiece(); timer.start(); }


private void pause() { if (!isStarted) { return; } isPaused = !isPaused; if (isPaused) { timer.stop(); } else { timer.start(); } repaint(); }


private void clearBoard() { for (int i = 0; i < BOARD_HEIGHT * BOARD_WIDTH; i++) { board[i] = Shape.Tetrominoes.NoShape; } }


private void dropDown() { int newY = curY; while (newY > 0) { if (!tryMove(curPiece, curX, newY - 1)) { break; } newY--; } pieceDropped(); }


private void oneLineUp() { if (!tryMove(curPiece, curX, curY - 1)) { pieceDropped(); } }


private void clearLines() { int numFullLines = 0; for (int i = BOARD_HEIGHT - 1; i >= 0; i--) { boolean lineIsFull = true; for (int j = 0; j < BOARD_WIDTH; j++) { if (shapeAt(j, i) == Shape.Tetrominoes.NoShape) { lineIsFull = false; break; } } if (lineIsFull) { numFullLines++; for (int k = i; k < BOARD_HEIGHT - 1; k++) { for (int j = 0; j < BOARD_WIDTH; j++) { board[(k * BOARD_WIDTH) + j] = shapeAt(j, k + 1); } } } } if (numFullLines > 0) { numLinesRemoved += numFullLines; isFallingFinished = true; curPiece.setShape(Shape.Tetrominoes.NoShape); repaint(); } }


private void pieceDropped() { for (int i = 0; i < 4; i++) { int x = curX + curPiece.x(i); int y = curY - curPiece.y(i); board[(y * BOARD_WIDTH) + x] = curPiece.getShape(); } clearLines(); if (!isFallingFinished) { newPiece(); } }


private void newPiece() { curPiece = new Shape(); curPiece.setRandomShape(); curX = BOARD_WIDTH / 2 + 1; curY = BOARD_HEIGHT - 1 + curPiece.minY(); if (!tryMove(curPiece, curX, curY)) { curPiece.setShape(Shape.Tetrominoes.NoShape); timer.stop(); isStarted = false; } }


private boolean tryMove(Shape newPiece, int newX, int newY) { for (int i = 0; i < 4; i++) { int x = newX + newPiece.x(i); int y = newY - newPiece.y(i); if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT) { return false; } if (shapeAt(x, y) != Shape.Tetrominoes.NoShape) { return false; } } curPiece = newPiece; curX = newX; curY = newY; repaint(); return true; }


private void drawSquare(Graphics g, int x, int y, Shape.Tetrominoes shape) { Color colors[] = {new Color(0, 0, 0), new Color(204, 102, 102), new Color(102, 204, 102), new Color(102, 102, 204), new Color(204, 204, 102), new Color(204, 102, 204), new Color(102, 204, 204), new Color(218, 170, 0) };


Color color = colors[shape.ordinal()];


g.setColor(color); g.fillRect(x + 1, y + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2);


g.setColor(color.brighter()); g.drawLine(x, y + BLOCK_SIZE - 1, x, y); g.drawLine(x, y, x + BLOCK_SIZE - 1, y);


g.setColor(color.darker()); g.drawLine(x + 1, y + BLOCK_SIZE - 1, x + BLOCK_SIZE - 1, y + BLOCK_SIZE - 1); g.drawLine(x + BLOCK_SIZE - 1, y + BLOCK_SIZE - 1, x + BLOCK_SIZE - 1, y + 1);


}


@Override public void paint(Graphics g) { super.paint(g); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight());


for (int i = 0; i < BOARD_HEIGHT; i++) { for (int j = 0; j < BOARD_WIDTH; j++) { Shape.Tetrominoes shape = shapeAt(j, BOARD_HEIGHT - i - 1); if (shape != Shape.Tetrominoes.NoShape) { drawSquare(g, j * BLOCK_SIZE, i * BLOCK_SIZE, shape); } } }


if (curPiece.getShape() != Shape.Tetrominoes.NoShape) { for (int i = 0; i < 4; i++) { int x = curX + curPiece.x(i); int y = curY - curPiece.y(i); drawSquare(g, x * BLOCK_SIZE, (BOARD_HEIGHT - y - 1) * BLOCK_SIZE, curPiece.getShape()); } }


if (isStarted) { g.setColor(Color.BLACK); g.drawLine(0, getHeight() - 1, BOARD_WIDTH * BLOCK_SIZE, getHeight() - 1); String scoreString = "Score: " + numLinesRemoved; g.drawString(scoreString, 10, getHeight() - 10); } else { String message = "Press S to start."; g.setColor(Color.BLACK); g.setFont(new Font("Helvetica", Font.BOLD, 24)); FontMetrics fm = getFontMetrics(g.getFont()); g.drawString(message, (getWidth() - fm.stringWidth(message)) / 2, getHeight() / 2); }


if (isPaused) { String message = "Paused"; g.setColor(Color.BLACK); g.setFont(new Font("Helvetica", Font.BOLD, 18)); FontMetrics fm = getFontMetrics(g.getFont()); g.drawString(message, (getWidth() - fm.stringWidth(message)) / 2, getHeight() / 2); } }


private Shape.Tetrominoes shapeAt(int x, int y) { if (filledPositions.contains((y * BOARD_WIDTH) + x)) { return board[(y * BOARD_WIDTH) + x]; } else { return Shape.Tetrominoes.NoShape; } }


public void actionPerformed(ActionEvent e) { if (isFallingFinished) { isFallingFinished = false; newPiece(); } else { oneLineUp(); } }


public void keyPressed(KeyEvent e) { if (!isStarted || curPiece.getShape() == Shape.Tetrominoes.NoShape) { return; }


int keycode = e.getKeyCode();


if (keycode == 'p' || keycode == 'P') { pause(); return; }


if (isPaused) { return; }


switch (keycode) { case KeyEvent.VK_LEFT: tryMove(curPiece, curX - 1, curY); break; case KeyEvent.VK_RIGHT: tryMove(curPiece, curX + 1, curY); break; case KeyEvent.VK_DOWN: tryMove(curPiece.rotateRight(), curX, curY); break; case KeyEvent.VK_UP: tryMove(curPiece.rotateLeft(), curX, curY); break; case KeyEvent.VK_SPACE: dropDown(); break; case 'd': oneLineUp(); break; case 'D': oneLineUp(); break; } }


public void keyReleased(KeyEvent e) { }


public void keyTyped(KeyEvent e) { }


public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Tetris"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.add(new TetrisBoard(), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }); } } ```


以上是一个基于Java Swing库实现的简单俄罗斯方块游戏的代码示例。游戏中使用TetrisBoard类作为游戏面板,在面板上绘制游戏区域和方块,实现游戏逻辑。代码中包含了方块形状、方块下落、方块移动、方块旋转、消除行等功能。


该示例代码仅实现了基本的游戏功能,可以根据需要进行扩展和优化,如增加下一个方块显示、显示得分、增加游戏难度等。希望以上代码对你有所帮助!
声明:免责声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,也不承认相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,请发送邮件至:dm@cn86.cn进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。本站原创内容未经允许不得转载。
  • 7x24

    在线售后支持

  • 10

    +

    10年互联网服务经验

  • 300

    +

    全国300余家服务机构

  • 70000

    +

    与70000余家企业客户携手

logo
祥云平台主营业务:品牌型网站建设,高端型网站建设, 外贸型网站建设,营销型网站建设,网站优化, 开发类网站,企业网络营销,搜索引擎推广,微信小程序, 企业邮箱,短视频运营等。

服务热线

400-007-8608

公司:

苏州祥云平台信息技术有限公司
苏州华企立方信息技术有限公司

地址:江苏省昆山市昆太路530号祥和国际大厦15-16层

返回顶部