Java制作俄罗斯方块

Java俄罗斯方块小游戏

在这里插入图片描述

import javax.swing.*;
import java.awt.*;
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.List;
import java.util.Random;public class TetrisGame extends JFrame implements ActionListener, KeyListener {private final int BOARD_WIDTH = 10;private final int BOARD_HEIGHT = 20;private final int CELL_SIZE = 30;private Timer timer;private Board board;private Shape currentShape;public TetrisGame() {initUI();}private void initUI() {board = new Board();add(board);timer = new Timer(500, this);timer.start();setTitle("俄罗斯方块游戏");setSize(BOARD_WIDTH * CELL_SIZE, BOARD_HEIGHT * CELL_SIZE);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);addKeyListener(this);setFocusable(true);}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {TetrisGame tetrisGame = new TetrisGame();tetrisGame.setVisible(true);});}@Overridepublic void actionPerformed(ActionEvent e) {// 定时器触发,尝试向下移动当前方块if (board.canMoveDown(currentShape)) {currentShape.moveDown();} else {// 如果无法继续下移,将当前方块加入游戏板并生成新的方块board.addShape(currentShape);currentShape = new Shape();if (!board.canMoveDown(currentShape)) {// 如果新生成的方块无法下移,游戏结束timer.stop();JOptionPane.showMessageDialog(this, "游戏结束!");System.exit(0);}}repaint();}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyPressed(KeyEvent e) {// 根据按键事件执行相应操作if (e.getKeyCode() == KeyEvent.VK_LEFT && board.canMoveLeft(currentShape)) {// 左移currentShape.moveLeft();} else if (e.getKeyCode() == KeyEvent.VK_RIGHT && board.canMoveRight(currentShape)) {// 右移currentShape.moveRight();} else if (e.getKeyCode() == KeyEvent.VK_DOWN && board.canMoveDown(currentShape)) {// 下移currentShape.moveDown();} else if (e.getKeyCode() == KeyEvent.VK_SPACE && board.canRotate(currentShape)) {// 旋转currentShape.rotate();}repaint();}@Overridepublic void keyReleased(KeyEvent e) {}// 游戏板class Board extends JPanel {private boolean[][] filledCells;public Board() {filledCells = new boolean[BOARD_HEIGHT][BOARD_WIDTH];currentShape = new Shape();}// 判断是否可以左移public boolean canMoveLeft(Shape shape) {for (Cell cell : shape.getCells()) {if (cell.getX() <= 0 || filledCells[cell.getY()][cell.getX() - 1]) {return false;}}return true;}// 判断是否可以右移public boolean canMoveRight(Shape shape) {for (Cell cell : shape.getCells()) {if (cell.getX() >= BOARD_WIDTH - 1 || filledCells[cell.getY()][cell.getX() + 1]) {return false;}}return true;}// 判断是否可以下移public boolean canMoveDown(Shape shape) {for (Cell cell : shape.getCells()) {if (cell.getY() >= BOARD_HEIGHT - 1 || filledCells[cell.getY() + 1][cell.getX()]) {return false;}}return true;}// 判断是否可以旋转public boolean canRotate(Shape shape) {Shape rotatedShape = shape.getRotatedShape();for (Cell cell : rotatedShape.getCells()) {if (cell.getX() < 0 || cell.getX() >= BOARD_WIDTH || cell.getY() >= BOARD_HEIGHT || filledCells[cell.getY()][cell.getX()]) {return false;}}return true;}// 将方块加入已填充单元格public void addShape(Shape shape) {for (Cell cell : shape.getCells()) {filledCells[cell.getY()][cell.getX()] = true;}clearLines();}// 消除满行private void clearLines() {for (int i = BOARD_HEIGHT - 1; i >= 0; i--) {boolean isFullLine = true;for (int j = 0; j < BOARD_WIDTH; j++) {if (!filledCells[i][j]) {isFullLine = false;break;}}if (isFullLine) {moveLinesDown(i);}}}// 将上方所有行向下移动private void moveLinesDown(int row) {for (int i = row; i > 0; i--) {for (int j = 0; j < BOARD_WIDTH; j++) {filledCells[i][j] = filledCells[i - 1][j];}}}@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g);drawBoard(g);drawShape(g, currentShape);}// 绘制游戏板private void drawBoard(Graphics g) {for (int i = 0; i < BOARD_HEIGHT; i++) {for (int j = 0; j < BOARD_WIDTH; j++) {if (filledCells[i][j]) {g.setColor(Color.BLUE);g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);g.setColor(Color.BLACK);g.drawRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);}}}}// 绘制方块private void drawShape(Graphics g, Shape shape) {for (Cell cell : shape.getCells()) {g.setColor(Color.RED);g.fillRect(cell.getX() * CELL_SIZE, cell.getY() * CELL_SIZE, CELL_SIZE, CELL_SIZE);g.setColor(Color.BLACK);g.drawRect(cell.getX() * CELL_SIZE, cell.getY() * CELL_SIZE, CELL_SIZE, CELL_SIZE);}}}// 单元格class Cell {private int x;private int y;public Cell(int x, int y) {this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}}// 方块class Shape {private List<Cell> cells;public Shape() {cells = new ArrayList<>();// 初始化形状Random random = new Random();int shapeType = random.nextInt(7); // 0 到 6switch (shapeType) {case 0: // Icells.add(new Cell(3, 0));cells.add(new Cell(3, 1));cells.add(new Cell(3, 2));cells.add(new Cell(3, 3));break;case 1: // Jcells.add(new Cell(4, 0));cells.add(new Cell(4, 1));cells.add(new Cell(4, 2));cells.add(new Cell(3, 2));break;case 2: // Lcells.add(new Cell(3, 0));cells.add(new Cell(3, 1));cells.add(new Cell(3, 2));cells.add(new Cell(4, 2));break;case 3: // Ocells.add(new Cell(4, 0));cells.add(new Cell(4, 1));cells.add(new Cell(3, 0));cells.add(new Cell(3, 1));break;case 4: // Scells.add(new Cell(4, 1));cells.add(new Cell(3, 1));cells.add(new Cell(3, 0));cells.add(new Cell(2, 0));break;case 5: // Tcells.add(new Cell(3, 0));cells.add(new Cell(3, 1));cells.add(new Cell(3, 2));cells.add(new Cell(4, 1));break;case 6: // Zcells.add(new Cell(2, 1));cells.add(new Cell(3, 1));cells.add(new Cell(3, 0));cells.add(new Cell(4, 0));break;}}public List<Cell> getCells() {return cells;}// 左移public void moveLeft() {for (Cell cell : cells) {cell.x--;}}// 右移public void moveRight() {for (Cell cell : cells) {cell.x++;}}// 下移public void moveDown() {for (Cell cell : cells) {cell.y++;}}// 旋转public void rotate() {int centerX = cells.get(1).getX();int centerY = cells.get(1).getY();for (Cell cell : cells) {int x = cell.getX() - centerX;int y = cell.getY() - centerY;cell.x = centerX - y;cell.y = centerY + x;}}// 获取旋转后的形状public Shape getRotatedShape() {Shape rotatedShape = new Shape();rotatedShape.cells.clear();rotatedShape.cells.addAll(this.cells);rotatedShape.rotate();return rotatedShape;}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/150978.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Java并发编程八】synchronized原理

synchronized的基本使用 可以在代码中加入synchronized代码块&#xff0c;也可以在方法的返回值前面加上synchronized声明。一把锁只能同时被一个线程获取&#xff0c;没有获得锁的线程只能等待。每个实例都对应有自己的一把锁&#xff0c;不同实例之间互不影响。synchronized修…

C#,怎么修改(VS)Visual Studio 2022支持的C#版本

一些文字来自于 Microsoft . &#xff08;只需要读下面的红色文字即可&#xff01;&#xff09; 1 C# 语言版本控制 最新的 C# 编译器根据项目的一个或多个目标框架确定默认语言版本。 Visual Studio 不提供用于更改值的 UI&#xff0c;但可以通过编辑 .csproj 文件来更改值。…

1688阿里巴巴官方开放平台API接口获取商品详情、商品规格信息列表、价格、宝贝详情数据调用示例说明

商品详情API接口在电商平台和购物应用中的作用非常重要。它提供了获取商品详细信息的能力&#xff0c;帮助用户了解和选择合适的商品&#xff0c;同时也支持开发者进行竞品分析、市场研究和推广营销等工作&#xff0c;以提高用户体验和促进销售增长。 1688.item_get-获得1688商…

SpringBoot 注解开发

利用自定义注解&#xff0c;解决问题 例1 自定义注解限制请求 场景&#xff1a;前端发起的频繁的请求&#xff0c;导致服务器压力过大。需要对后端接口进行限流处理&#xff0c;每个接口都需要做限流处理的话就会导致代码冗余&#xff0c;此时就可以利用注解进行解决 非注解形…

单链表的实现(Single Linked List)---直接拿下!

单链表的实现&#xff08;Single Linked List&#xff09;—直接拿下&#xff01; 文章目录 单链表的实现&#xff08;Single Linked List&#xff09;---直接拿下&#xff01;一、单链表的模型二、代码实现&#xff0c;接口函数实现①初始化②打印链表③创建一个结点④尾插⑤尾…

2023年网络安全竞赛—内存取证解析

内存取证 目录 内存取证 解析如下: 任务:内存取证 *任务说明:仅能获取win20230306的IP地址 FTP用户名:user,密码:123456 在服务器中下载内存片段,在内存片段中获取主机信息&

Unity 场景烘培 ——unity Post-Processing后处理1(四)

提示&#xff1a;文章有错误的地方&#xff0c;还望诸位大神不吝指教&#xff01; 文章目录 前言一、Post-Processing是什么&#xff1f;二、安装使用Post-Processing1.安装Post-Processing2.使用Post-Processing&#xff08;1&#xff09;.添加Post-process Volume&#xff08…

malloc 和 new的区别

在 C 中&#xff0c;malloc 和 new 都是用于动态分配内存的方法&#xff0c;但它们有一些重要的区别。以下是关于 malloc 和 new 的常见面试内容及答案的总结&#xff1a; 1. 区别&#xff1a; malloc 是 C 语言的函数&#xff0c;而 new 是 C 中的运算符。malloc 只分配内存…

Flutter 3.16 中带来的更新

Flutter 3.16 中带来的更新 目 录 1. 概述2. 框架更新2.1 Material 3 成为新默认2.2 支持 Material 3 动画2.3 TextScaler2.4 SelectionArea 更新2.5 MatrixTransition 动画2.6 滚动更新2.7 在编辑菜单中添加附加选项2.8 PaintPattern 添加到 flutter_test 3. 引擎更新&#xf…

文件隐藏 [极客大挑战 2019]Secret File1

打开题目 查看源代码发现有一个可疑的php 访问一下看看 点一下secret 得到如下页面 响应时间太短我们根本看不清什么东西&#xff0c;那我们尝试bp抓包一下看看 提示有个secr3t.php 访问一下 得到 我们看见了flag.php 访问一下可是什么都没有 那我们就进行代码审计 $file$_…

Servlet---上传文件

文章目录 上传文件的方法上传文件的示例前端代码示例后端代码示例 上传文件的方法 上传文件的示例 前端代码示例 <body><form action"upload" method"post" enctype"multipart/form-data"><input type"file" name&qu…

2023年中国地产SaaS分类、产业链及市场规模分析[图]

SaaS是一种基于云计算技术&#xff0c;通过订阅的方式向互联网向客户提供访问权限以获取计算资源的一项软件即服务。地产SaaS则是SaaS的具体应用&#xff0c;提供了一个线上平台&#xff0c;用于协助房地产供应商与购房者、建筑承建商、材料供应商及房地产资产管理公司之间的协…

【Linux网络】详解使用http和ftp搭建yum仓库,以及yum网络源优化

目录 一、回顾yum的原理 1.1yum简介 yum安装的底层原理&#xff1a; yum的好处&#xff1a; 二、学习yum的配置文件及命令 1、yum的配置文件 2、yum的相关命令详解 3、yum的命令相关案例 三、搭建yum仓库的方式 1、本地yum仓库建立 2、通过http搭建内网的yum仓库 3、…

Sentinel 热点规则 (ParamFlowRule)

Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件&#xff0c;主要以流量为切入点&#xff0c;从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。 SpringbootDubboNacos 集成 Sentinel&…

Navicat for mysql 无法连接到虚拟机的linux系统下的mysql

原创/朱季谦 最近在linux Centos7版本的虚拟机上安装了一个MySql数据库&#xff0c;发现本地可以正常ping通虚拟机&#xff0c;但Navicat则无法正常连接到虚拟机里的MySql数据库&#xff0c;经过一番琢磨&#xff0c;发现解决这个问题的方式&#xff0c;很简单&#xff0c;总共…

ffmpeg知识点整理

使用FFmepg进行视频转码、视频格式转换、图片提取等&#xff01;_ffmepg -c:v-CSDN博客 中文文档&#xff1a; ffmpeg 中文手册 (beandrewang.github.io) 笔记&#xff1a; 通用规则是&#xff0c;所有选项作用于其后边的第一个文件。因此&#xff0c;顺序是非常重要的&…

Appium移动自动化测试--安装Appium

Appium 自动化测试是很早之前就想学习和研究的技术了&#xff0c;可是一直抽不出一块完整的时间来做这件事儿。现在终于有了。 反观各种互联网的招聘移动测试成了主流&#xff0c;如果再不去学习移动自动化测试技术将会被淘汰。 web自动化测试的路线是这样的&#xff1a;编程语…

springboot--单元测试

单元测试 前言1、写测试要用的类2、写测试要用的类3、运行测试类4、spring-boot-starter-test默认提供了以下库4.1 junit54.1.1 DisplayName:为测试类或者测试方法设置展示名称4.1.2 BeforeAll&#xff1a;所有测试方法运行之前先运行这个4.1.3 BeforeEach&#xff1a;每个测试…

python:list和dict的基本操作实例

python&#xff1a;list和dict的基本操作实例 今天我们来谈谈Python中list和dict的使用方法。这两种数据结构在Python中非常常见&#xff0c;掌握它们的使用方法对于编写高效的代码非常重要。 首先我们来看看list的使用。在下面的例子中&#xff0c;我们有一个名为ori_list的…

2023.11.17-hive调优的常见方式

目录 0.设置hive参数 1.数据压缩 2.hive数据存储格式 3.fetch抓取策略 4.本地模式 5.join优化操作 6.SQL优化(列裁剪,分区裁剪,map端聚合,count(distinct),笛卡尔积) 6.1 列裁剪: 6.2 分区裁剪: 6.3 map端聚合(group by): 6.4 count(distinct): 6.5 笛卡尔积: 7…