用Java写一个俄罗斯方块小程序

时间: 2023-12-05 12:05:20 浏览: 44
好的,我可以为您提供一个简单的 Java 俄罗斯方块小程序的示例代码。这个程序基于 Java Swing 库,使用了 JFrame、JPanel、JLabel、JButton 等组件,实现了一个简单的俄罗斯方块游戏。 以下是示例代码,您可以将其保存为 Tetris.java 并运行: ```java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Tetris extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; private static final int WIDTH = 300; private static final int HEIGHT = 600; private static final int BLOCK_SIZE = 30; private static final int BOARD_WIDTH = 10; private static final int BOARD_HEIGHT = 20; private static final int DELAY = 500; private static final Color[] COLORS = { Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.PINK, Color.ORANGE, Color.CYAN }; private JFrame frame; private JPanel board; private JLabel scoreLabel; private JButton startButton; private int[][] blocks; private Point[] currentBlock; private Color currentColor; private int currentX; private int currentY; private boolean isRunning; private int score; public Tetris() { frame = new JFrame("Tetris"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); board = new JPanel() { private static final long serialVersionUID = 1L; @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < BOARD_HEIGHT; i++) { for (int j = 0; j < BOARD_WIDTH; j++) { if (blocks[i][j] != 0) { g.setColor(COLORS[blocks[i][j] - 1]); g.fillRect(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); } } } for (Point p : currentBlock) { g.setColor(currentColor); g.fillRect((currentX + p.x) * BLOCK_SIZE, (currentY + p.y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); } } }; board.setPreferredSize(new Dimension(BLOCK_SIZE * BOARD_WIDTH, BLOCK_SIZE * BOARD_HEIGHT)); frame.add(board, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(); scoreLabel = new JLabel("Score: 0"); bottomPanel.add(scoreLabel); startButton = new JButton("Start"); startButton.addActionListener(this); bottomPanel.add(startButton); frame.add(bottomPanel, BorderLayout.SOUTH); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } private void init() { blocks = new int[BOARD_HEIGHT][BOARD_WIDTH]; currentBlock = new Point[4]; generateBlock(); currentX = BOARD_WIDTH / 2 - 1; currentY = 0; isRunning = true; score = 0; scoreLabel.setText("Score: " + score); } private void generateBlock() { Random rand = new Random(); int type = rand.nextInt(7) + 1; switch (type) { case 1: // I currentBlock[0] = new Point(0, 0); currentBlock[1] = new Point(0, 1); currentBlock[2] = new Point(0, 2); currentBlock[3] = new Point(0, 3); break; case 2: // J currentBlock[0] = new Point(0, 0); currentBlock[1] = new Point(1, 0); currentBlock[2] = new Point(1, 1); currentBlock[3] = new Point(1, 2); break; case 3: // L currentBlock[0] = new Point(0, 2); currentBlock[1] = new Point(1, 0); currentBlock[2] = new Point(1, 1); currentBlock[3] = new Point(1, 2); break; case 4: // O currentBlock[0] = new Point(0, 0); currentBlock[1] = new Point(0, 1); currentBlock[2] = new Point(1, 0); currentBlock[3] = new Point(1, 1); break; case 5: // S currentBlock[0] = new Point(0, 1); currentBlock[1] = new Point(0, 2); currentBlock[2] = new Point(1, 0); currentBlock[3] = new Point(1, 1); break; case 6: // T currentBlock[0] = new Point(0, 1); currentBlock[1] = new Point(1, 0); currentBlock[2] = new Point(1, 1); currentBlock[3] = new Point(1, 2); break; case 7: // Z currentBlock[0] = new Point(0, 0); currentBlock[1] = new Point(0, 1); currentBlock[2] = new Point(1, 1); currentBlock[3] = new Point(1, 2); break; } currentColor = COLORS[rand.nextInt(COLORS.length)]; } private void moveDown() { if (canMove(currentX, currentY + 1, currentBlock)) { currentY++; } else { addBlock(currentX, currentY, currentBlock, currentColor); checkRows(); generateBlock(); currentX = BOARD_WIDTH / 2 - 1; currentY = 0; if (!canMove(currentX, currentY, currentBlock)) { isRunning = false; } } } private void moveLeft() { if (canMove(currentX - 1, currentY, currentBlock)) { currentX--; } } private void moveRight() { if (canMove(currentX + 1, currentY, currentBlock)) { currentX++; } } private void rotate() { Point[] newBlock = new Point[4]; for (int i = 0; i < 4; i++) { newBlock[i] = new Point(currentBlock[i].y, -currentBlock[i].x); } if (canMove(currentX, currentY, newBlock)) { currentBlock = newBlock; } } private boolean canMove(int x, int y, Point[] block) { for (Point p : block) { int newX = x + p.x; int newY = y + p.y; if (newX < 0 || newX >= BOARD_WIDTH || newY < 0 || newY >= BOARD_HEIGHT || blocks[newY][newX] != 0) { return false; } } return true; } private void addBlock(int x, int y, Point[] block, Color color) { for (Point p : block) { blocks[y + p.y][x + p.x] = COLORS.length + 1; } for (Point p : block) { blocks[y + p.y][x + p.x] = COLORS.length + 1 - colorIndex(color); } } private int colorIndex(Color color) { for (int i = 0; i < COLORS.length; i++) { if (color.equals(COLORS[i])) { return i; } } return -1; } private void checkRows() { ArrayList<Integer> fullRows = new ArrayList<Integer>(); for (int i = 0; i < BOARD_HEIGHT; i++) { boolean full = true; for (int j = 0; j < BOARD_WIDTH; j++) { if (blocks[i][j] == 0) { full = false; break; } } if (full) { fullRows.add(i); } } if (fullRows.size() > 0) { for (int i : fullRows) { for (int j = i; j > 0; j--) { for (int k = 0; k < BOARD_WIDTH; k++) { blocks[j][k] = blocks[j - 1][k]; } } } score += fullRows.size() * 100; scoreLabel.setText("Score: " + score); } } private void gameLoop() { while (isRunning) { moveDown(); board.repaint(); try { Thread.sleep(DELAY); } catch (InterruptedException e) { e.printStackTrace(); } } } public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { init(); gameLoop(); } } public static void main(String[] args) { new Tetris(); } } ``` 该程序使用一个二维数组来表示游戏区域,每个格子可以被染上不同的颜色。在游戏中,程序会随机生成一个俄罗斯方块,玩家需要使用键盘控制方块的移动和旋转,让方块落到最底部或者尽可能占据更多的空间。当一行满了格子时,该行会被消除,并且玩家可以获得一定的分数。当方块无法继续下落时,游戏结束。

相关推荐

最新推荐

recommend-type

Python小游戏之300行代码实现俄罗斯方块

主要给大家介绍了关于Python小游戏之300行代码实现俄罗斯方块的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧
recommend-type

node-v4.1.2-linux-armv7l.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

2_职业强国2.psd

2_职业强国2.psd
recommend-type

com.tencent.ig.zip

com.tencent.ig.zip
recommend-type

node-v4.3.2-darwin-x64.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

list根据id查询pid 然后依次获取到所有的子节点数据

可以使用递归的方式来实现根据id查询pid并获取所有子节点数据。具体实现可以参考以下代码: ``` def get_children_nodes(nodes, parent_id): children = [] for node in nodes: if node['pid'] == parent_id: node['children'] = get_children_nodes(nodes, node['id']) children.append(node) return children # 测试数
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。