俄罗斯方块
相信大家从小就玩过俄罗斯方块的,多余的话就不多说了,代码是有生命的,就让代码来说话好了
- package cn.hncu.games;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.HeadlessException;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import javax.swing.JFrame;
- import javax.swing.JMenu;
- import javax.swing.JMenuBar;
- import javax.swing.JMenuItem;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.Timer;
- public class Tetris extends JFrame {
- private TetrisPanel a;
- private JMenuItem j1,j2,j3;
- public Tetris() {
- // 添加菜单,此处仅示意技术,不写完善
- JMenuBar menubar = new JMenuBar();
- setJMenuBar(menubar);
- // 菜单
- JMenu menuGame = new JMenu("游戏");
- menubar.add(menuGame);
- // 菜单项
- j1 = new JMenuItem("新游戏");
- j1.setActionCommand("newGame");
- menuGame.add(j1);
- j2 = new JMenuItem("暂停");
- j2.setActionCommand("pause");
- menuGame.add(j2);
- j3 = new JMenuItem("继续");
- j3.setActionCommand("resume");
- menuGame.add(j3);
- // 菜单项监听
- MenuListener ml = new MenuListener();
- j1.addActionListener(ml);
- j2.addActionListener(ml);
- j3.addActionListener(ml);
- //另一种添加方式
- menuGame.add("其它").addActionListener(ml);
- // 为了在菜单监听器类中访问a对象,提升作用域
- // TetrisPanel a = new TetrisPanel();
- a = new TetrisPanel();
- this.addKeyListener(a.listener);
- // this.add(a);正式开发不用this,运行效率更高
- add(a);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setSize(220, 275);
- setLocation(400, 100);
- setTitle("俄罗斯方块精简版");
- setResizable(false);
- }
- public static void main(String[] args) {
- Tetris te = new Tetris();
- te.setVisible(true);
- }
- /*
- * 用面板当画布,界面刷新效果更好
- */
- class TetrisPanel extends JPanel {
- private int blockType; // 0-6 3
- private int turnState; // 0-3 2
- private int x;
- private int y;
- private int score;
- private int delay;
- private TimerListener listener = new TimerListener();
- private Timer timer;
- // 定义地图,用来存放整个游戏方块区的状态(显示方格或不显示)
- // 存放块的位置:x=0~11 y=0~21
- // ----22行12列(其中一行两列是外框),行列的序号位置跟我们平时写的是相反的map[列号][行号]
- int[][] map = new int[13][23];// 为解决越界,在边上预留了1列
- // 方块的形状:
- // 第一维代表方块类型(包括7种:S、Z、L、J、I、O、T)
- // 第二维代表旋转次数
- // 第三四维代表方块矩阵
- int shapes[][][] = new int[][][] {
- /*
- * 模板 { {0,0,0,0,0,0,0,0, 0,0,0,0, 0,0,0,0}, {0,0,0,0,0,0,0,0, 0,0,0,0,
- * 0,0,0,0}, {0,0,0,0,0,0,0,0, 0,0,0,0, 0,0,0,0}, {0,0,0,0,0,0,0,0,
- * 0,0,0,0, 0,0,0,0} }
- */