一个Java写的俄罗斯方块源码 算法简单
Java实现俄罗斯方块游戏简单版
Java实现俄罗斯⽅块游戏简单版本⽂实例为⼤家分享了Java实现俄罗斯⽅块游戏的具体代码,供⼤家参考,具体内容如下游戏页⾯效果如下:俄罗斯⽅块游戏本⾝的逻辑:俄罗斯⽅块游戏的逻辑是⽐较简单的。
它就类似于堆砌房⼦⼀样,各种各样的⽅地形状是不同的。
但是,俄罗斯⽅块游戏的界⾯被等均的分为若⼲⾏和若⼲列,因此⽅块的本质就是占⽤了多少个单元。
⾸先来考虑⼀下数据的问题。
对于界⾯来说,需要⼀个⼆维的 int 型数组,它保存着那些地⽅应该有着⾊,哪些没有;然后是⽅块本⾝,尽管它们的形状不统⼀,但是它们可以⽤⼀个4X4⽐例的⽅块所包围,因此⽤16个字节就可以把⼀个⽅块的信息保存者,注意:其实⽅块的数据也可以⽤int 数组表⽰,但是涉及到效率问题,⽤位操作⽐⽤普通的算术运算要快⼀点。
接下来思考⼀下动作具体有下⾯⼏点:(1)⽅块的诞⽣。
它的诞⽣是需要⽤随机原理的,另外,它如何初始化的被放置在游戏界⾯的顶部?(2)⽅块是需要⾃动的往下掉的,它在掉的过程中,还需要判断它是否与周围的环境是否发⽣了冲突,能不能继续往下。
(3)⽅块本⾝还可以变形,变形以后的⽅块具有不同的数据,判断的⽅式⼜会不⼀样。
(4)当⽤户⼀直按住s键的时候,⽅块还需要持续往下掉。
然后就是过程,玩家主要操作的地⽅有以下⼏个⽅⾯:(1)左右操作。
需要监听KeyEvent,让⽅块左右移动,直到碰到边界。
(2)变形操作。
也要监听KeyEvent,让⽅块⾃动的变形。
(3)下降操作。
也要监听KeyEvent,让⽅块快速的下降。
⾄于游戏的结束,只有⼀种情况,那就是诞⽣的⽅块出世就与其他⽅块冲突了。
源程序代码如下:注释详细package tetris;import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class Main extends JFrame implements KeyListener {private JTextArea[][] grids;// 把整个界⾯变为⼀个⽂本区域,整个游戏在⾥⾯进⾏private int data[][]; // 对于每个格⼦的数据,1代表有⽅块,0代表为空⽩区private int[] allRect; // 所有的⽅块类型,⽤16个字节来存储,俄罗斯⽅块图形都是在4*4格⼦⾥private int rect; // 当前游戏下落的⽅块类型;private int x, y; // 当前⽅块的坐标位置,x代表⾏,y代表列private int score = 0; // 记录当前游戏得分情况,每消⼀层得10分private JLabel label; // 显⽰分数的标签private JLabel label1;// 显⽰游戏是否结束private boolean running; // ⽤于判断游戏是否结束/*⽆参构造函数*/public Main() {grids = new JTextArea[26][12];//设置游戏区域⾏和列data = new int[26][12];//开辟data数组空间与游戏区域⾏和列⼀致allRect = new int[] { 0x00cc, 0x8888, 0x000f, 0x0c44, 0x002e, 0x088c, 0x00e8, 0x0c88, 0x00e2, 0x044c, 0x008e,0x08c4, 0x006c, 0x04c8, 0x00c6, 0x08c8, 0x004e, 0x04c4, 0x00e4 };//19种⽅块形状,如0x00cc就是 0000 表⽰⼀个2*2的正⽅形⽅块//0000//1100//1100label = new JLabel("score: 0"); //此标签存放得分情况,初始化为0分label1 = new JLabel("开始游戏"); //此标签为提⽰游戏状态:开始还是结束running = false; //为标志变量,false为游戏结束,true为游戏正在进⾏init(); // 游戏界⾯初始化}/*游戏界⾯初始化函数*/public void init() {JPanel center = new JPanel(); //此⾯板为游戏核⼼区域JPanel right = new JPanel(); //此⾯板为游戏说明区域center.setLayout(new GridLayout(26, 12, 1, 1)); //给游戏核⼼区域划分⾏、列共26⾏,12列for (int i = 0; i < grids.length; i++) {//初始化⾯板for (int j = 0; j < grids[i].length; j++) {grids[i][j] = new JTextArea(20, 20);grids[i][j].setBackground(Color.WHITE);grids[i][j].addKeyListener(this);// 添加键盘监听事件//初始化游戏边界if (j == 0 || j == grids[i].length - 1 || i == grids.length - 1) {grids[i][j].setBackground(Color.PINK);data[i][j] = 1;}grids[i][j].setEditable(false);// ⽂本区域不可编辑center.add(grids[i][j]); //把⽂本区域添加到主⾯板上}}//初始化游戏说明⾯板right.setLayout(new GridLayout(4, 1));right.add(new JLabel(" a : left d : right"));right.add(new JLabel(" s : down w : change"));right.add(label);label1.setForeground(Color.RED);// 设置标签内容为红⾊字体right.add(label1);//把主⾯板和说明⾯板添加到窗体中this.setLayout(new BorderLayout());this.add(center, BorderLayout.CENTER);this.add(right, BorderLayout.EAST);running = true; //初始化running状态为true,表⽰程序运⾏即游戏开始this.setSize(600, 850);// 设置窗体⼤⼩this.setVisible(true);// 窗体可见this.setLocationRelativeTo(null);// 设置窗体居中this.setResizable(false);// 窗体⼤⼩不可改变this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 释放窗体}/*主函数*/public static void main(String[] args) {Main m = new Main(); //创建Main对象,主要⽤于初始化数据m.go();// 开始游戏}/*开始游戏*/public void go() {// 开始游戏while (true) {//游戏开始直到游戏失败才结束,否则⼀直执⾏if (running == false) {//如果游戏失败break;}ranRect();// 绘制下落⽅格形状start();// 开始游戏}label1.setText("游戏结束!");//则游戏结束}/*绘制下落⽅格形状*/public void ranRect() {rect = allRect[(int) (Math.random() * 19)];// 随机⽣成⽅块类型(共7种,19个形状)}/*游戏开始函数*/public void start() {x = 0;y = 5; //初始化下落⽅块的位置for (int i = 0; i < 26; i++) {//共26层,⼀层⼀层下落try {Thread.sleep(1000);//每层延时1秒if (canFall(x, y) == false) {// 如果不可以掉落saveData(x, y);//把此⽅块区域data[][]标志为1,表⽰有数据for (int k = x; k < x + 4; k++) {//循环遍历4层,看是否有哪⼀层都有⽅块的情况,以便消除那⼀⾏⽅格和统计得分 int sum = 0;for (int j = 1; j <= 10; j++) {if (data[k][j] == 1) {sum++;}}if (sum == 10) {//如果k层都有⽅块,则消除k层⽅块removeRow(k);}}for (int j = 1; j <= 10; j++) {//游戏最上⾯的4层不能有⽅块,否则游戏失败 if (data[3][j] == 1) {running = false;break;}}break;}// 如果可以掉落x++;// 层加⼀fall(x, y);// 掉下来⼀层} catch (InterruptedException e) {e.printStackTrace();}}}/*判断正下落的⽅块是否可以下落*/public boolean canFall(int m, int n) {int temp = 0x8000;//表⽰1000 0000 0000 0000for (int i = 0; i < 4; i++) {//循环遍历16个⽅格(4*4)for (int j = 0; j < 4; j++) {if ((temp & rect) != 0) {// 此处有⽅块时if (data[m + 1][n] == 1)// 如果下⼀个地⽅有⽅块,则直接返回falsereturn false;}n++;//列加⼀temp >>= 1;}m++;// 下⼀⾏n = n - 4;// 回到⾸列}return true;//可以掉落返回true}/*把不可下降的⽅块的对应的data存储为1,表⽰此坐标有⽅块*/public void saveData(int m, int n) {int temp = 0x8000;//表⽰1000 0000 0000 0000for (int i = 0; i < 4; i++) {//循环遍历16个⽅格(4*4)for (int j = 0; j < 4; j++) {if ((temp & rect) != 0) {// 此处有⽅块时data[m][n] = 1;//data数组存放为1}n++;//下⼀列temp >>= 1;}m++;// 下⼀⾏n = n - 4;// 回到⾸列}}/*移除row⾏所有⽅块,以上的依次往下降*/public void removeRow(int row) {for (int i = row; i >= 1; i--) {for (int j = 1; j <= 10; j++) {data[i][j] = data[i - 1][j];//}}reflesh();// 刷新移除row⾏⽅块后的游戏主⾯板区域score += 10;// 分数加10;label.setText("score: " + score);//显⽰得分}/* 刷新移除row⾏⽅块后的游戏主⾯板区域*/public void reflesh() {for (int i = 1; i < 25; i++) {for (int j = 1; j < 11; j++) {if (data[i][j] == 1) {//有⽅块的地⽅把⽅块设置为绿⾊grids[i][j].setBackground(Color.GREEN);} else {//⽆⽅块的地⽅把⽅块设置为⽩⾊grids[i][j].setBackground(Color.WHITE);}}}}/*⽅块掉落⼀层*/public void fall(int m, int n) {if (m > 0)// ⽅块下落⼀层时clear(m - 1, n);// 清除上⼀层有颜⾊的⽅块draw(m, n);// 重新绘制⽅块图像}/*清除⽅块掉落之前有颜⾊的地⽅*/public void clear(int m, int n) {int temp = 0x8000;//表⽰1000 0000 0000 0000for (int i = 0; i < 4; i++) {//循环遍历16个⽅格(4*4)for (int j = 0; j < 4; j++) {if ((temp & rect) != 0) {// 此处有⽅块时grids[m][n].setBackground(Color.WHITE);//清除颜⾊,变为⽩⾊ }n++;//下⼀列temp >>= 1;}m++;//下⼀⾏n = n - 4;//回到⾸列}}/*绘制掉落后⽅块图像*/public void draw(int m, int n) {int temp = 0x8000;//表⽰1000 0000 0000 0000for (int i = 0; i < 4; i++) {//循环遍历16个⽅格(4*4)for (int j = 0; j < 4; j++) {if ((temp & rect) != 0) {// 此处有⽅块时grids[m][n].setBackground(Color.GREEN);//有⽅块的地⽅变为绿⾊ }n++;//下⼀列temp >>= 1;}m++;//下⼀⾏n = n - 4;//回到⾸列}}@Overridepublic void keyPressed(KeyEvent e) {}@Overridepublic void keyReleased(KeyEvent e) {}@Overridepublic void keyTyped(KeyEvent e) {if (e.getKeyChar() == 'a') {// ⽅格进⾏左移if (running == false) {return;}if (y <= 1)//碰到左边墙壁时return;int temp = 0x8000;//表⽰1000 0000 0000 0000for (int i = x; i < x + 4; i++) {//循环遍历16个⽅格(4*4)for (int j = y; j < y + 4; j++) {if ((rect & temp) != 0) {// 此处有⽅块时if (data[i][j - 1] == 1) {//如果左移⼀格有⽅块时return;}}temp >>= 1;}}clear(x, y);//可以进⾏左移操作时,清除左移前⽅块颜⾊y--;draw(x, y);//然后重新绘制左移后⽅块的图像}if (e.getKeyChar() == 'd') {//⽅块进⾏右移操作if (running == false) {return;}int temp = 0x8000;int m = x, n = y;int num = 7;for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {if ((temp & rect) != 0) {if (n > num) {num = n;}}temp >>= 1;n++;}m++;n = n - 4;}if (num >= 10) {return;}temp = 0x8000;for (int i = x; i < x + 4; i++) {for (int j = y; j < y + 4; j++) {if ((rect & temp) != 0) {if (data[i][j + 1] == 1) {return;}}temp >>= 1;}}clear(x, y);//可以进⾏右移操作时,清除右移前⽅块颜⾊y++;draw(x, y);//然后重新绘制右移后⽅块的图像}if (e.getKeyChar() == 's') {//⽅块进⾏下移操作if (running == false) {return;}if (canFall(x, y) == false) {saveData(x, y);return;}clear(x, y);//可以进⾏下移操作时,清除下移前⽅块颜⾊x++;draw(x, y);//然后重新绘制下移后⽅块的图像}if (e.getKeyChar() == 'w') {//改变⽅块形状if (running == false) {return;}int i = 0;for (i = 0; i < allRect.length; i++) {//循环遍历19个⽅块形状if (allRect[i] == rect)//找到下落的⽅块对应的形状,然后进⾏形状改变 break;}if (i == 0)//为正⽅形⽅块⽆需形状改变,为⽅块图形种类1return;clear(x, y);if (i == 1 || i == 2) {//为⽅块图形种类2rect = allRect[i == 1 ? 2 : 1];if (y > 7)y = 7;}if (i >= 3 && i <= 6) {//为⽅块图形种类3rect = allRect[i + 1 > 6 ? 3 : i + 1];}if (i >= 7 && i <= 10) {//为⽅块图形种类4rect = allRect[i + 1 > 10 ? 7 : i + 1];}if (i == 11 || i == 12) {//为⽅块图形种类5rect = allRect[i == 11 ? 12 : 11];}if (i == 13 || i == 14) {//为⽅块图形种类6rect = allRect[i == 13 ? 14 : 13];}if (i >= 15 && i <= 18) {//为⽅块图形种类7rect = allRect[i + 1 > 18 ? 15 : i + 1];}draw(x, y);}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
俄罗斯方块完整源代码
//不多说,直接可以拷贝下面的东西,就可以运行。
package day04;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class ERSBlock extends JPanel implements ActionListener,KeyListener//应该是继承JPanel{static Button but[] = new Button[6];static Button noStop = new Button("取消暂停"); static Label scoreLab = new Label("分数:");static Label infoLab = new Label("提示:");static Label speedLab = new Label("级数:");static Label scoreTex = new Label("0");static Label infoTex = new Label(" ");static Label speedTex = new Label("1");static JFrame jf = new JFrame();static MyTimer timer;static ImageIcon icon=new ImageIcon("resource/Block.jpg");static JMenuBar mb = new JMenuBar();static JMenu menu0 = new JMenu("游戏 ");static JMenu menu1 = new JMenu("帮助 ");static JMenuItem mi0 = new JMenuItem("新游戏"); static JMenuItem mi1 = new JMenuItem("退出");static JMenuItem mi1_0 = new JMenuItem("关于"); static JDialog dlg_1;static JTextArea dlg_1_text = new JTextArea(); static int startSign= 0;//游戏开始标志 0 未开始 1 开始 2 暂停static String butLab[] = {"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};static int game_body[][] = new int[19][10];static int game_sign_x[] = new int[4];//用于记录4个方格的水平位置static int game_sign_y[] = new int[4];//用于记录4个方格的垂直位置static boolean downSign = false;//是否落下static int blockNumber = 1;//砖块的编号static int gameScore = 0;//游戏分数static int speedMark = 1;public static void main(String args[]) {ERSBlock myBlock = new ERSBlock();mb.add(menu0);mb.add(menu1);menu0.add(mi0);menu0.add(mi1);menu1.add(mi1_0);jf.setJMenuBar(mb);myBlock.init();jf.add(myBlock);jf.setSize(565,501);jf.setResizable(false);jf.setTitle("俄罗斯方块");jf.setIconImage(icon.getImage());jf.setLocation(200,100);jf.show();timer = new MyTimer(myBlock); //启动线程timer.setDaemon(true);timer.start();timer.suspend();}public void init(){setLayout(null);for(int i = 0;i < 6;i++){but[i] = new Button(butLab[i]);add(but[i]);but[i].addActionListener(this);but[i].addKeyListener(this);but[i].setBounds(360,(240 + 30 * i),160,25); }add(scoreLab);add(scoreTex);add(speedLab);add(speedTex);add(infoLab);add(infoTex);add(scoreLab);scoreLab.setBounds(320,15,30,20); scoreTex.setBounds(360,15,160,20); scoreTex.setBackground(Color.white); speedLab.setBounds(320,45,30,20); speedTex.setBounds(360,45,160,20); speedTex.setBackground(Color.white);but[1].setEnabled(false);but[4].setEnabled(false);infoLab.setBounds(320,75,30,20); infoTex.setBounds(360,75,160,20); infoTex.setBackground(Color.white); noStop.setBounds(360,360,160,25); noStop.addActionListener(this); noStop.addKeyListener(this);mi0.addActionListener(this);mi1.addActionListener(this);mi1_0.addActionListener(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if(e.getSource() == but[0])//开始游戏{startSign = 1;infoTex.setText("游戏已经开始!");but[0].setEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);timer.resume();}if(e.getSource() == but[1]||e.getSource() == mi0)//重新开始游戏{startSign = 0;gameScore = 0;timer.suspend();num_csh_restart();repaint();rand_block();scoreTex.setText("0");infoTex.setText("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource() == but[2])//降低级数 {infoTex.setText("降低级数!"); speedMark--;if(speedMark <= 1){speedMark = 1;infoTex.setText("已经是最低级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[3])//提高级数 {infoTex.setText("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;infoTex.setText("已经是最高级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[4])//游戏暂停 {this.add(noStop);this.remove(but[4]);infoTex.setText("游戏暂停!"); timer.suspend();}if(e.getSource() == noStop)//取消暂停 {this.remove(noStop);this.add(but[4]);infoTex.setText("继续游戏!"); timer.resume();}if(e.getSource() == but[5]||e.getSource() == mi1)//退出游戏{jf.dispose();}if(e.getSource() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/guanyu.txt");//得到路径byte a[] = new byte[io.available()];io.read(a);io.close();String str = new String(a);dlg_1_text.setText(str);}catch(Exception g){}dlg_1_text.setEditable(false);dlg_1.add(dlg_1_text);dlg_1.pack();dlg_1.setResizable(false);dlg_1.setSize(200, 120);dlg_1.setLocation(400, 240);dlg_1.show();}}public void rand_block()//随机产生砖块{int num;num = (int)(Math.random() * 6) + 1;//产生0~6之间的随机数blockNumber = num;switch(blockNumber){case 1: block1(); blockNumber = 1; break;case 2: block2(); blockNumber = 2; break;case 3: block3(); blockNumber = 3; break;case 4: block4(); blockNumber = 4; break;case 5: block5(); blockNumber = 5; break;case 6: block6(); blockNumber = 6; break;case 7: block7(); blockNumber = 7; break;}}public void change_body(int blockNumber)//改变砖块状态{dingwei();if(blockNumber == 1&&downSign == false)//变换长条2种情况{if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 16)//说明长条是横着的{if(game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] != 2){num_csh_game();game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] >= 1&&game_sign_x[3] <= 7)//说明长条是竖着的{if(game_body[game_sign_y[0] +1][game_sign_x[0]-1] != 2&&game_body[game_sign_y[3] -2][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]]=1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 3&&downSign == false)//变换转弯1有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] >= 1){if(game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;= 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[1] == game_sign_x[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[3] <= 8){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1]= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] == game_sign_x[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 4&&downSign == false)//变换转弯2有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[3] <= 7){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[1] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[2]) {if(game_body[game_sign_y[1]][game_sign_x[1] + 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0]] = 1;game_body[game_sign_y[1]][game_sign_x[1] + 2] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[0] == game_sign_y[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] - 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2] - 2] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 5&&downSign == false)//变换转弯3有4种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[2] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[1] >= 2){if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[1]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[2] == game_sign_y[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] +2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2]][game_sign_x[2] + 2] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[2] == game_sign_x[3]){if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 6&&downSign == false)//变换两层砖块1的2种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] -1 ] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 7&&downSign == false)//变换两层砖块2的2种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] <= 16){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[2] <= 17)if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}}public void num_csh_game()//数组清零for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){game_body[i][j] = 2;}else{game_body[i][j] = 0;}}}}public void num_csh_restart()//重新开始时数组清零 {for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++)game_body[i][j] = 0;}}}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(e.getKeyCode() == KeyEvent.VK_DOWN&&startSign == 1)//处理下键{this.down();}if(e.getKeyCode() == KeyEvent.VK_LEFT&&startSign == 1)//处理左键{this.left();}if(e.getKeyCode() == KeyEvent.VK_RIGHT&&startSign== 1)//处理右键{this.right();}if(e.getKeyCode() == KeyEvent.VK_UP&&startSign== 1)//处理上键转换{this.change_body(blockNumber);}if(startSign == 0){infoTex.setText("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){g.setColor(Color.black);g.fill3DRect(0,0,300,450,true);for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){g.setColor(Color.blue);g.fill3DRect(30*j,30*(i-4),30,30,true); }if(game_body[i][j] == 2){g.setColor(Color.magenta);g.fill3DRect(30*j,30*(i-4),30,30,true); }}}}public void left()//向左移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 0||game_body[game_sign_y[k]][game_sign_x[k] - 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] - 1] = 1; }infoTex.setText("向左移动!");repaint();}}public void right()//向右移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 9||game_body[game_sign_y[k]][game_sign_x[k] + 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] + 1] = 1; }infoTex.setText("向右移动!");repaint();}}public void down()//下落{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_y[k] == 18||game_body[game_sign_y[k] + 1][game_sign_x[k]] == 2){sign = 1;downSign = true;changeColor();cancelDW();getScore();if(game_over() == false){rand_block();repaint();}}}if(sign == 0){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k] + 1][game_sign_x[k]] = 1;}infoTex.setText("游戏进行中!");repaint();}}public boolean game_over()//判断游戏是否结束{int sign=0;for(int i = 0;i < 10;i++){if(game_body[4][i] == 2){sign = 1;}}if(sign == 1){infoTex.setText("游戏结束!");changeColor();repaint();startSign = 0;timer.suspend();return true;}elsereturn false;}public void getScore()//满行消除方法{for(int i = 0;i < 19;i++){int sign = 0;for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){sign++;}}if(sign == 10){gameScore += 100;scoreTex.setText(gameScore+"");infoTex.setText("恭喜得分!");for(int j = i;j >= 1;j--){for(int k = 0;k < 10;k++){game_body[j][k] = game_body[j - 1][k];}}}}}public void changeColor()//给已经落下的块换色{downSign = false;for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k]] = 2; }}public void dingwei()//确定其位置{int k = 0;cancelDW();for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){game_sign_x[k] = j;game_sign_y[k] = i;k++;}}}}public void cancelDW()//将定位数组初始化{for(int k = 0;k < 4;k++){game_sign_x[k] = 0;game_sign_y[k] = 0;}}public void block1()//长条{game_body[0][4] = 1;game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block2()//正方形{game_body[3][4] = 1;game_body[3][5] = 1;game_body[2][5] = 1;}public void block3()//3加1(下) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[3][5] = 1;}public void block4()//3加1(中) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[2][5] = 1;}public void block5()//3加1(上) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[1][5] = 1;}public void block6()//转折1 {game_body[1][5] = 1;game_body[2][5] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block7()//转折2 {game_body[1][4] = 1;game_body[2][4] = 1;game_body[2][5] = 1;game_body[3][5] = 1;}}//定时线程class MyTimer extends Thread {ERSBlock myBlock;public MyTimer(ERSBlock myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。
基于Java的俄罗斯方块的设计和实现(含源文件)
姓 名
学号
专 业
指导教师
摘 要
俄罗斯方块作为一款风靡全球的多样化终端游戏,经久不衰。俄罗斯方块简单的基本游戏规则是旋转、移动,游戏自动随机输出7种形状的方块,经旋转后可形成28种形状,方块堆叠在一起,排列成完整的一行或多行消除得分,积分达到一定程度会自动提升级别。该游戏上手简单、老少皆宜、家喻户晓。
2 系统的
对系统的需求分析就是用户和开发人员在“系统必须做什么”这个问题上实现相互理解,达到共识,从而形成双方认可的软件产品的需求规格。这样有利于提高软件开发过程中的能见度,便于对软件开发过程的控制与管理,便于采用工程化的模式开发软件,从而达到提高软件的质量,为开发人员、维护人员、管理人员之间的交流、协作提供便捷。作为工作成果的原始依据,系统的需求分析可以向潜在用户传递软件功能、性能的需求,使其能够判断该软件是否符合自己的需求。
游戏形状需求:用数组作为存储方块28种状态的数据结构,即长条形、Z字形、反Z形、田字形、7字形、反7形、T字型一共7种形状的向4个方向的旋转变形,各个方块要能实现它的任意变形,可设为顺时针变形或逆时针变形,一般为逆时针变形。方块的可否翻转需要加以判断,以防止其翻转越界。
键盘处理事件需求:方块下落时,可通过键盘方向键(上键、下键、左键、右键)或字母键I、K、J、L对下落方块进行向上(旋转变形)、向下(加速下落)、向左移动、向右移动。
鼠标处理事件需求:通过点击菜单栏中相应的菜单项或控制面板内的按钮,可以实现游戏的开始、结束、暂停、继续、提高等级、降低等级,预显方块形状的显示,分数、等级的显示,以及游戏帮助、颜色变换等功能。
显示需求:当方块填满一行时可以消行,剩余未填满的行逐次向下移动并统计分数。当达到一定分数的时候,会增加相应的等级。当方块充满主界面的每一行,方块不能再下落时,提示“Game Over”的字样。
Java项目--俄罗斯方块
Java项⽬--俄罗斯⽅块Java项⽬--俄罗斯⽅块百度盘链接⼀、⼼得⼆、游戏实例游戏截图⽬录结构三、代码1、主界⾯ Tetris.java1package com.hsj.tetris;23import java.awt.Color;4import java.awt.Font;5import java.awt.Graphics;6import java.awt.Image;7import java.awt.event.KeyAdapter;8import java.awt.event.KeyEvent;9import java.util.Arrays;10import java.util.Timer;11import java.util.TimerTask;1213import javax.imageio.ImageIO;14import javax.swing.JFrame;15import javax.swing.JPanel;16/**17 * 俄罗斯⽅块游戏⾯板18 *19*/20public class Tetris extends JPanel {21/** 正在下落⽅块 */22private Tetromino tetromino;23/** 下⼀个下落⽅块 */24private Tetromino nextOne;25/** ⾏数 */26public static final int ROWS = 20;27/** 列数 */28public static final int COLS = 10;29/** 墙 */30private Cell[][] wall = new Cell[ROWS][COLS];31/** 消掉的⾏数 */32private int lines;33/** 分数 */34private int score;3536public static final int CELL_SIZE = 26;3738private static Image background;//背景图⽚39public static Image I;40public static Image J;41public static Image L;42public static Image S;43public static Image Z;44public static Image O;45public static Image T;46static{//加载静态资源的,加载图⽚47//建议将图⽚放到 Tetris.java 同包中!48//从包中加载图⽚对象,使⽤Swing API实现51// Tetris.class.getResource("tetris.png"));52// T = toolkit.getImage(Tetris.class.getResource("T.png"));53// S = toolkit.getImage(Tetris.class.getResource("S.png")); 54// Z = toolkit.getImage(Tetris.class.getResource("Z.png"));55// L = toolkit.getImage(Tetris.class.getResource("L.png"));56// J = toolkit.getImage(Tetris.class.getResource("J.png"));57// I = toolkit.getImage(Tetris.class.getResource("I.png"));58// O = toolkit.getImage(Tetris.class.getResource("O.png")); 59//import javax.imageio.ImageIO;60try{61 background = ImageIO.read(62 Tetris.class.getResource("tetris.png"));63 T=ImageIO.read(Tetris.class.getResource("T.png"));64 I=ImageIO.read(Tetris.class.getResource("I.png"));65 S=ImageIO.read(Tetris.class.getResource("S.png"));66 Z=ImageIO.read(Tetris.class.getResource("Z.png"));67 L=ImageIO.read(Tetris.class.getResource("L.png"));68 J=ImageIO.read(Tetris.class.getResource("J.png"));69 O=ImageIO.read(Tetris.class.getResource("O.png"));70 }catch(Exception e){71 e.printStackTrace();72 }73 }7475public void action(){76//tetromino = Tetromino.randomTetromino();77//nextOne = Tetromino.randomTetromino();78//wall[19][2] = new Cell(19,2,Tetris.T);79 startAction();80 repaint();81 KeyAdapter l = new KeyAdapter() {82public void keyPressed(KeyEvent e) {83int key = e.getKeyCode();84if(key == KeyEvent.VK_Q){85 System.exit(0);//退出当前的Java进程86 }87if(gameOver){88if(key==KeyEvent.VK_S){89 startAction();90 }91return;92 }93//如果暂停并且按键是[C]就继续动作94if(pause){//pause = false95if(key==KeyEvent.VK_C){ continueAction(); }96return;97 }98//否则处理其它按键99switch(key){100case KeyEvent.VK_RIGHT: moveRightAction(); break; 101case KeyEvent.VK_LEFT: moveLeftAction(); break; 102case KeyEvent.VK_DOWN: softDropAction() ; break; 103case KeyEvent.VK_UP: rotateRightAction() ; break; 104case KeyEvent.VK_Z: rotateLeftAction() ; break;105case KeyEvent.VK_SPACE: hardDropAction() ; break; 106case KeyEvent.VK_P: pauseAction() ; break;107 }108 repaint();109 }110 };111this.requestFocus();112this.addKeyListener(l);113 }114115public void paint(Graphics g){116 g.drawImage(background, 0, 0, null);//使⽤this 作为观察者117 g.translate(15, 15);//平移绘图坐标系118 paintTetromino(g);//绘制正在下落的⽅块119 paintWall(g);//画墙120 paintNextOne(g);121 paintScore(g);122 }123public static final int FONT_COLOR = 0x667799;124public static final int FONT_SIZE = 0x20;125private void paintScore(Graphics g) {126 Font f = getFont();//获取当前的⾯板默认字体127 Font font = new Font(128 f.getName(), Font.BOLD, FONT_SIZE);129int x = 290;130int y = 162;131 g.setColor(new Color(FONT_COLOR));132 g.setFont(font);135 y+=56;136 str = "LINES:"+this.lines;137 g.drawString(str, x, y);138 y+=56;139 str = "[P]Pause";140if(pause){str = "[C]Continue";}141if(gameOver){ str = "[S]Start!";}142 g.drawString(str, x, y);143 }144145private void paintNextOne(Graphics g) {146 Cell[] cells = nextOne.getCells();147for(int i=0; i<cells.length; i++){148 Cell c = cells[i];149int x = (c.getCol()+10) * CELL_SIZE-1;150int y = (c.getRow()+1) * CELL_SIZE-1;151 g.drawImage(c.getImage(), x, y, null);152 }153 }154155private void paintTetromino(Graphics g) {156 Cell[] cells = tetromino.getCells();157for(int i=0; i<cells.length; i++){158 Cell c = cells[i];159int x = c.getCol() * CELL_SIZE-1;160int y = c.getRow() * CELL_SIZE-1;161//g.setColor(new Color(c.getColor()));162//g.fillRect(x, y, CELL_SIZE, CELL_SIZE);163 g.drawImage(c.getImage(), x, y, null);164 }165 }166167//在 Tetris 类中添加⽅法 paintWall168private void paintWall(Graphics g){169for(int row=0; row<wall.length; row++){170//迭代每⼀⾏, i = 0 1 2 (19)171 Cell[] line = wall[row];172//line.length = 10173for(int col=0; col<line.length; col++){174 Cell cell = line[col];175int x = col*CELL_SIZE;176int y = row*CELL_SIZE;177if(cell==null){178//g.setColor(new Color(0));179//画⽅形180//g.drawRect(x, y, CELL_SIZE, CELL_SIZE); 181 }else{182 g.drawImage(cell.getImage(), x-1, y-1, null); 183 }184 }185 }186 }187/**188 * 在 Tetris(俄罗斯⽅块) 类中增加⽅法189 * 这个⽅法的功能是:软下落的动作控制流程190 * 完成功能:如果能够下落就下落,否则就着陆到墙上,191 * ⽽新的⽅块出现并开始落下。
俄罗斯方块(Java实现)
俄罗斯⽅块(Java实现)程序效果:代码://Box.java1package tetris;2public class Box {3private final int M = 30, N = 12;4private int[][] ls = new int[M][N];5private int score=0;6int getM() {7return M;8 }9int getN() {10return N;11 }12int getScore() {13return score;14 }15boolean isOut(int x,int y){16return x<0|y<0|x>M-1|y>N-1?true:false;17 }18int getFlag(int x, int y) {19return isOut(x,y)?2:ls[x][y];20 }21int clearFlag(int x, int y) {22if(isOut(x,y))return -1;23 ls[x][y]=0;24return 0;25 }26int setFlag_1(int x, int y) {27if(isOut(x,y))return -1;28 ls[x][y]=1;29return 0;30 }31int setFlag_2(int x, int y) {32if(isOut(x,y))return -1;33 ls[x][y]=2;34return 0;35 }36/*boolean isFlag_2(int x, int y) {37 return isOut(x,y)?true:ls[x][y]== 2 ? true:false ;38 }*/39void clear(int x, int maxX) {40if(isOut(x,0)||isOut(maxX,0))return ;41for (int i = x; i <= maxX; i++) {42boolean isAllNotBlank = true;43for (int j = 0; j <= N - 1; j++) {44if (ls[i][j]== 0) {45 isAllNotBlank = false;46break;47 }48 }49if (isAllNotBlank) {50for (int k = i - 1; k >= 0; k--) {51for (int j = 0; j <= N - 1; j++) {52 ls[k + 1][j]=ls[k][j];53 }54 }55 score+=100;56 }57 }58 }59 }//Shape.java1package tetris;2import java.awt.Point;3import java.util.Random;4public class Shape {5private final Box box;6private Point[] ps = new Point[4];7private Point[] tps = new Point[5];8private final int[][][]shapes={9 {{-1,0,0,0,1,0,2,0},{0,0,0,-1,0,2,0,1}},10 {{- 1,0, 1, - 1,0,0,1,0},{0,- 1,1,-1,1,1,1,0},{-1,0,0,0,-1,1,1,0},{0,0,0,-1,0,1,1,1}},11 {{-1,0,0,0,1,1,1,0},{0,1,1,-1,1,1,1,0},{-1,0,-1,-1,0,0,1,0},{0,0,0,-1,0,1,1,-1}},12 {{0,0,1,-1,1,1,1,0},{0,0,1,-1,1,0,2,0},{0,0,0,-1,0,1,1,0},{0,0,1,0,1,1,2,0}},13 {{0,0,1,0,0,1,1,1}},14 {{-1,0,0,-1,-1,1,0,0},{-1,0,0,0,0,1,1,1}},15 {{- 1,0, - 1,- 1,0, 1,0,0},{- 1,1,0,0,0,1,1,0}}16 };17private int change = 0,shape,x,y;18int left,down;19private Random random;20boolean isPaused = false;21 Shape(Box b) {22 box = b;23for (int i = 0; i <= 3; i++) {24 ps[i] = new Point();25 }26for (int i = 0; i <= 4; i++) {27 tps[i] = new Point();28 }29 random = new Random();30 getNewShape();31 }32private void clearTpsFlag(){33for (int i = 0; i <= 3; i++) {34 box.clearFlag(tps[i].x, tps[i].y);35 }36 }37private int setPsFlag_1() {38for (int i = 0; i <= 3; i++) {39 box.setFlag_1(ps[i].x, ps[i].y);40 }41return 0;42 }43private int setPsFlag_2() {44for (int i = 0; i <= 3; i++) {45 box.setFlag_2(ps[i].x, ps[i].y);46 }47return 0;48 }49private synchronized int tps() {50for (int i = 0; i <= 3; i++) {51 tps[i].x = ps[i].x;52 tps[i].y = ps[i].y;53 }54 tps[4].x=x;55 tps[4].y=y;56return 0;57 }58private synchronized int backupChange() {59for (int i = 0; i <= 3; i++) {60 ps[i].x = tps[i].x;61 ps[i].y = tps[i].y;62 }63 x=tps[4].x;64 y=tps[4].y;65return 0;66 }67private synchronized int check() {68 System.out.println(ps[0]+","+ps[1]+","+ps[2]+","+ps[3]);69for (int i = 0; i <= 3;i++) {70if (!(box.getFlag(ps[i].x, ps[i].y)==0||box.getFlag(ps[i].x, ps[i].y)==1)){71 backupChange();72return 5;}73 }74return 0;75 }76private void getNewShape(){77 System.out.println("lll");78int i = Math.abs(random.nextInt()) % 7;79 shape=i;80 x=1;81 y=box.getN()/2;82for(int j=0;j<=3;j++){83 ps[j].setLocation(x+shapes[i][0][j*2], y+shapes[i][0][j*2+1]);84 }85 left=0;86 down=0;87 change=0;88 }89void changeShape(){90 tps();91 change++;92 change%=shapes[shape].length;93for(int j=0;j<=3;j++){94 ps[j].setLocation(x+shapes[shape][change][j*2], y+shapes[shape][change][j*2+1]);95 }96int g=check();97if(g==0){98 clearTpsFlag();99 setPsFlag_1();100 }101 }102synchronized int move(int dir) {103 tps();104switch(dir){105case 0:for (int i = 0; i <= 3; i++) {ps[i].y--;}y--;break;106case 1:for (int i = 0; i <= 3; i++) {ps[i].y++;}y++;break;107case 2:for (int i = 0; i <= 3; i++) {ps[i].x++;}x++;break;108default:109 }110int g = check();111if(g!=0&&dir==2){112int x = ps[0].x;113int maxX = ps[3].x;// x+4>M-1?M-1:x+4;114 setPsFlag_2();115 box.clear(x, maxX);116if(x==1){return -1;}117 getNewShape();118 }119if(g==0){120 clearTpsFlag();121 setPsFlag_1();122 }123return 0;124 }125 }//Tetris.java1package tetris;23import java.awt.BorderLayout;4import java.awt.Color;5import java.awt.Container;6import java.awt.Graphics;7import java.awt.GridLayout;8import java.awt.event.KeyAdapter;9import java.awt.event.KeyEvent;10import java.io.BufferedReader;11import java.io.BufferedWriter;12import java.io.FileNotFoundException;13import java.io.FileReader;14import java.io.FileWriter;15import java.io.IOException;16import javax.swing.JButton;17import javax.swing.JFrame;18import javax.swing.JOptionPane;19import javax.swing.JPanel;20import javax.swing.JTextField;2122public class Tetris extends JFrame implements Runnable{23private static final long serialVersionUID = 279494108361487144L; 24final Color BC = Color.GRAY;25final Color FC = Color.LIGHT_GRAY;26 Box box;27 Shape shape;28int a = 0, b = 0, c = 0;29 JPanel panel, scorePanel;30 JTextField scoreField, bestScoreField;31 JButton[][] bs;32 Tetris(Box b) {33super("Tetris");34 box = b;35 shape =new Shape(b);36 bs = new JButton[box.getM()][box.getN()];37for (int i = 0; i <= box.getM() - 1; i++) {38for (int j = 0; j <= box.getN() - 1; j++) {39 bs[i][j] = new JButton();40 bs[i][j].setBackground(BC);41 }42 }43 Container container = getContentPane();44 container.setLayout(new BorderLayout());45 scorePanel = new JPanel();46 scorePanel.setLayout(new BorderLayout());47 scoreField = new JTextField(10);48 bestScoreField = new JTextField(20);49 bestScoreField.setText(getBestScores());50 bestScoreField.setEditable(false);51 scoreField.setText("SCORE: " + new Integer(box.getScore()).toString());52 scoreField.setEditable(false);53 scorePanel.add(scoreField, BorderLayout.NORTH);54 scorePanel.add(bestScoreField, BorderLayout.SOUTH);55 container.add(scorePanel, BorderLayout.NORTH);56 panel = new JPanel();57 panel.setLayout(new GridLayout(box.getM(), box.getN()));58for (int i = 0; i <= box.getM() - 1; i++) {59for (int j = 0; j <= box.getN() - 1; j++) {60 panel.add(bs[i][j]);61 }62 }63 container.add(panel, BorderLayout.CENTER);64this.addKeyListener(new KeyAdapter() {65public void keyPressed(KeyEvent e) {66int c = e.getKeyCode();67// System.out.print(c);68switch (c) {69case KeyEvent.VK_LEFT :70//shape.left++;71 shape.move(0);72break;73case KeyEvent.VK_RIGHT :74//shape.left--;75 shape.move(1);76break;77case KeyEvent.VK_UP :78 shape.changeShape();79break;80case KeyEvent.VK_DOWN :81 shape.down++;82break;83case KeyEvent.VK_SPACE :84if (shape.isPaused == true) {85 shape.isPaused = false;86 } else {87 shape.isPaused = true;88 }89break;90default : }91 }92 });93this.setFocusable(true);94 setLocation(200, 10);95 setSize(20 * box.getN(), 20 * box.getM() + 20);96 setVisible(true);97 }98private int down() throws InterruptedException {99 System.out.println("ddd");100int dd=shape.move(2);101 scoreField.setText("Score: " + new Integer(box.getScore()).toString()); 102if(dd==-1){gameOver();}105public void run() {106while (true) {107try {108if (shape.isPaused == true) {109// System.out.println("PAUSED");110 Thread.sleep(500);111 } else {112//System.out.println("start1");113 down();114for (int i = 0; i <= box.getM() - 1; i++) {115for (int j = 0; j <= box.getN() - 1; j++) {116if(box.getFlag(i, j)==0)117 bs[i][j].setBackground(BC);118else bs[i][j].setBackground(FC);119 }120 }121if (shape.down >=1) {122 shape.down--;123 Thread.sleep(50);124continue;125 }126 Thread.sleep(250);127 }128 } catch (InterruptedException e) {129 e.printStackTrace();130 }131 }132 }133 String getBestScores() {134 BufferedReader reader = null;135try {136 reader = new BufferedReader(new FileReader("score.txt"));137 } catch (FileNotFoundException e) {138 e.printStackTrace();139 }140try {141 a = Integer.parseInt(reader.readLine());142 b = Integer.parseInt(reader.readLine());143 c = Integer.parseInt(reader.readLine());144 } catch (NumberFormatException e) {145 e.printStackTrace();146 } catch (IOException e) {147 e.printStackTrace();148 }149 String bestS = new String("Best Score: " + new Integer(a).toString() 150 + " " + new Integer(b).toString() + " "151 + new Integer(c).toString());152return bestS;153 }154int gameOver() {155 JOptionPane.showMessageDialog(null, "你死了~~~.", "GAME OVER", 156 JOptionPane.PLAIN_MESSAGE);157if (box.getScore() > a) {158 c = b;159 b = a;160 a = box.getScore();161 }162else if (box.getScore() > b) {163 c = b;164 b = box.getScore();165 }166else if (box.getScore()> c) {167 c = box.getScore();168 }169 save();170 System.exit(0);173int save() {174 BufferedWriter writer = null;175try {176 writer = new BufferedWriter(new FileWriter("score.txt"));177 } catch (IOException e) {178 e.printStackTrace();179 }180 String d = new Integer(a).toString(), e = new Integer(b).toString(),181 f = new Integer(c).toString();182try {183 writer.write(d);184 writer.newLine();185 writer.write(e);186 writer.newLine();187 writer.write(f);188 writer.flush();189 writer.close();190 } catch (NumberFormatException ev) {191 ev.printStackTrace();192 } catch (IOException ev) {193 ev.printStackTrace();194 }195return 0;196 }197public static void main(String[] args) {198 Box box = new Box();199 Tetris tetris = new Tetris(box);200 tetris.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);201 Thread thread1 = new Thread(tetris);202 thread1.start();203 }204205 }程序写于⼤三上学期。
JAVA俄罗斯方块程序代码
import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.*;import javax.swing.Timer;public class Tetris extends JFrame{public Tetris(){Tetrisblok a=new Tetrisblok();addKeyListener(a);add(a);}public static void main(String[]args){Tetris frame=new Tetris();JMenuBar menu=new JMenuBar();frame.setJMenuBar(menu);JMenu game=new JMenu("游戏");JMenuItem newgame=game.add("新游戏");JMenuItem pause=game.add("暂停");JMenuItem goon=game.add("继续");JMenuItem exit=game.add("退出");JMenu help=new JMenu("帮助");JMenuItem about=help.add("关于");menu.add(game);menu.add(help);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(220,275);frame.setTitle("Tetris内测版");//frame.setUndecorated(true);frame.setVisible(true);frame.setResizable(false);}}//创建一个俄罗斯方块类class Tetrisblok extends JPanel implements KeyListener{//blockType代表方块类型//turnState代表方块状态private int blockType;private int score=0;private int turnState;private int x;private int y;private int i=0;int j=0;int flag=0;//定义已经放下的方块x=0-11,y=0-21;int[][]map=new int[13][23];//方块的形状第一组代表方块类型有S、Z、L、J、I、O、T7种第二组代表旋转几次第三四组为方块矩阵private final int shapes[][][]=new int[][][]{//i{{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0}},//s{{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},//z{{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}},//j{{0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0}},//o{{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0}},//l{{1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}}, //t{{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0}}}; //生成新方块的方法public void newblock(){blockType=(int)(Math.random()*1000)%7;turnState=(int)(Math.random()*1000)%4;x=4;y=0;if(gameover(x,y)==1){newmap();drawwall();score=0;JOptionPane.showMessageDialog(null,"GAME OVER");}}//画围墙public void drawwall(){for(i=0;i<12;i++){map[i][21]=2;}for(j=0;j<22;j++){map[11][j]=2;map[0][j]=2;}}//初始化地图public void newmap(){for(i=0;i<12;i++){for(j=0;j<22;j++){map[i][j]=0;}}}//初始化构造方法Tetrisblok(){newblock();newmap();drawwall();Timer timer=new Timer(1000,new TimerListener());timer.start();}//旋转的方法public void turn(){int tempturnState=turnState;turnState=(turnState+1)%4;if(blow(x,y,blockType,turnState)==1){}if(blow(x,y,blockType,turnState)==0){turnState=tempturnState;}repaint();}//左移的方法public void left(){if(blow(x-1,y,blockType,turnState)==1){x=x-1;};repaint();}//右移的方法public void right(){if(blow(x+1,y,blockType,turnState)==1){x=x+1;};repaint();}//下落的方法public void down(){if(blow(x,y+1,blockType,turnState)==1){y=y+1;delline();};if(blow(x,y+1,blockType,turnState)==0){add(x,y,blockType,turnState);newblock();delline();};repaint();}//是否合法的方法public int blow(int x,int y,int blockType,int turnState){for(int a=0;a<4;a++){for(int b=0;b<4;b++){if(((shapes[blockType][turnState][a*4+b]==1)&&(map[x+b+1][y+a]==1))||((shapes[blockType][turnState][a*4+b]==1)&&(map[x+b+1][y+a]==2))){return0;}}}return1;}//消行的方法public void delline(){int c=0;for(int b=0;b<22;b++){for(int a=0;a<12;a++){if(map[a][b]==1){c=c+1;if(c==10){score+=10;for(int d=b;d>0;d--){for(int e=0;e<11;e++){map[e][d]=map[e][d-1];}}}}}c=0;}}//判断你挂的方法public int gameover(int x,int y){if(blow(x,y,blockType,turnState)==0){return1;}return0;}//把当前添加mappublic void add(int x,int y,int blockType,int turnState){int j=0;for(int a=0;a<4;a++){for(int b=0;b<4;b++){if(map[x+b+1][y+a]==0){map[x+b+1][y+a]=shapes[blockType][turnState][j];};j++;}}}//画方块的的方法public void paintComponent(Graphics g){super.paintComponent(g);//画当前方块for(j=0;j<16;j++){if(shapes[blockType][turnState][j]==1){g.fillRect((j%4+x+1)*10,(j/4+y)*10,10,10);}}//画已经固定的方块for(j=0;j<22;j++){for(i=0;i<12;i++){if(map[i][j]==1){g.fillRect(i*10,j*10,10,10);}if(map[i][j]==2){g.drawRect(i*10,j*10,10,10);}}}g.drawString("score="+score,125,10);g.drawString("抵制不良游戏,",125,50);g.drawString("拒绝盗版游戏。
Java编写的俄罗斯方块(小游戏)
for (i=0; i<xblocks; i++)
{
for (j=0; j<yblocks; j++)
{
screendata[i][j]=0;
}
ห้องสมุดไป่ตู้ }
score=0;
emptyline=-1;
int objectdx;
short objecttype;
short objectcolor;
int objectrotation;
int objectrotationd=0;
short objectptr;
short checkptr;
final short itemcount=7;
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
gameInit();
}
//初始化游戏
public void gameInit()
{
0,0, 1,0, 0,1, -1,1, // 被旋转180度
0,0, 0,-1, 1,0, 1,1, // 被旋转270度
0,0, 1,0, -1,0, 0,-1, // L形1,正常状态
0,0, 0,1, 0,-1, -1,0, // 被旋转90度
short screencount=40;
boolean showtitle=true;
int items[]={
0,0, -1,0, 0,-1, -1,-1, // 四方形, 正常状态
俄罗斯方块java代码
俄罗斯方块java代码俄罗斯方块是最经典的休闲益智游戏之一,现在很多人都不玩了,这里就来写一篇俄罗斯方块的Java代码。
首先,需要说明的是,Java代码中有两个类,一个是主类(Tetris.java),一个是方块类(Block.java)。
主类包含的功能是:显示游戏画面、游戏的主逻辑、处理键盘事件、以及控制游戏暂停、游戏结束等;方块类包含的功能是:初始化方块颜色、坐标、方向等,旋转方块。
那么我们来分析一下主类(Tetris.java)的代码。
首先是一些变量的定义:游戏区域的宽度和高度static final int Width = 10;static final int Height = 22;方块的颜色static Color blocksColor[] = {new Color(255, 255, 255), 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) };游戏区域static int[][] wall = new int[Width][Height];当前方块static Block curBlock;下一个方块static Block nextBlock;游戏是否结束static boolean isOver;线程static MyThread t;接下来是一些初始化操作:初始化主窗体public Tetris() {initFrame();initUI();initGame();}初始化游戏界面private void initUI() {设置游戏面板和游戏区域pnlGame = new JPanel();pnlGame.setPreferredSize(new Dimension(blockSize * Width, blockSize * Height));pnlGame.setBorder(BorderFactory.createLineBorder(Color.gray));gameArea = new GameArea();pnlGame.add(gameArea);设置下一个方块显示面板和下一个方块区域pnlNextBlock = new JPanel();pnlNextBlock.setPreferredSize(new Dimension(blockSize * 4, blockSize * 4));pnlNextBlock.setBorder(BorderFactory.createTitledBorder("Next Block"));nextBlockArea = new BlockArea();pnlNextBlock.add(nextBlockArea);将游戏界面和下一个方块界面加入主窗体frmMain.getContentPane().add(pnlGame, BorderLayout.WEST);frmMain.getContentPane().add(pnlNextBlock, BorderLayout.EAST);显示窗体frmMain.pack();frmMain.setVisible(true);}初始化游戏private void initGame() {初始化积分、速度score = 0;speed = 1;初始化游戏区域for (int i = 0; i < Width; i++) {for (int j = 0; j < Height; j++) {wall[i][j] = 0;}}旋转T型方块,初始朝向为横向curBlock = new Block(1, 0);生成下一块方块nextBlock = new Block(0, 0);}我们可以看到,主类(Tetris.java)包含以下方法:1. initFrame()方法,用来初始化主窗体。
java实现俄罗斯方块小游戏
java实现俄罗斯⽅块⼩游戏本⽂实例为⼤家分享了java实现俄罗斯⽅块的具体代码,供⼤家参考,具体内容如下使⽤⼀个⼆维数组保存游戏的地图:// 游戏地图格⼦,每个格⼦保存⼀个⽅块,数组纪录⽅块的状态private State map[][] = new State[rows][columns];游戏前先将所有地图中的格⼦初始化为空:/* 初始化所有的⽅块为空 */for (int i = 0; i < map.length; i++) {for (int j = 0; j < map[i].length; j++) {map[i][j] = State.EMPTY;}}玩游戏过程中,我们能够看到界⾯上的⽅块,那么就得将地图中所有的⽅块绘制出来,当然,除了需要绘制⽅块外,游戏积分和游戏结束的字符串在必要的时候也需要绘制:/*** 绘制窗体内容,包括游戏⽅块,游戏积分或结束字符串*/@Overridepublic void paint(Graphics g) {super.paint(g);for (int i = 0; i < rows; i++) {for (int j = 0; j < columns; j++) {if (map[i][j] == State.ACTIVE) { // 绘制活动块g.setColor(activeColor);g.fillRoundRect(j * BLOCK_SIZE, i * BLOCK_SIZE + 25,BLOCK_SIZE - 1, BLOCK_SIZE - 1, BLOCK_SIZE / 5,BLOCK_SIZE / 5);} else if (map[i][j] == State.STOPED) { // 绘制静⽌块g.setColor(stopedColor);g.fillRoundRect(j * BLOCK_SIZE, i * BLOCK_SIZE + 25,BLOCK_SIZE - 1, BLOCK_SIZE - 1, BLOCK_SIZE / 5,BLOCK_SIZE / 5);}}}/* 打印得分 */g.setColor(scoreColor);g.setFont(new Font("Times New Roman", Font.BOLD, 30));g.drawString("SCORE : " + totalScore, 5, 70);// 游戏结束,打印结束字符串if (!isGoingOn) {g.setColor(Color.RED);g.setFont(new Font("Times New Roman", Font.BOLD, 40));g.drawString("GAME OVER !", this.getWidth() / 2 - 140,this.getHeight() / 2);}}通过随机数的⽅式产⽣⽅块所组成的⼏种图形,⼀般七种图形:条形、⽥形、正7形、反7形、T形、Z形和反Z形,如⽣成条形:map[0][randPos] = map[0][randPos - 1] = map[0][randPos + 1]= map[0][randPos + 2] = State.ACTIVE;⽣成图形后,实现下落的操作。
JAVA课程设计俄罗斯方块(含代码)
Java程序课程设计任务书俄罗斯方块游戏的开发1、主要内容:俄罗斯方块游戏具有广泛的游戏人群,因为它比较简单有趣,无论老少都比较适合。
俄罗斯方块游戏的设计对于每一个Java语言设计者进行语言提高和进阶都是一个很好的锻炼机会。
俄罗斯方块游戏的设计工作是非常复杂和重要的,它涉及面逛,牵涉面多,如果不好好考虑和设计,将难以成功开发出这个游戏。
在这个游戏的设计中,将牵涉到图形界面的显示与更新,数据的收集与更新并且在这个游戏的开发中还会应用类的继承机制以及一些设计模式。
因此,如何设计和开发好这个俄罗斯方块游戏,对于提高Java开发水平和系统的设计能力有极大的帮助。
在设计开发过程中,开发者需要处理好各个类之间的集成关系,还要处理各个类的相应的封装,并且还要协调好各个模块之间的逻辑依赖关系和数据通信关系。
2、具体要求(包括技术要求等):系统的功能设计要求:本课程设计将实现以下几种功能。
1.游戏界面主框架游戏界面主框架主要包括游戏图形区域界面,游戏速度的选择更新界面,,游戏分数的显示更新界面,下一个图形方块的显示更新区域,开始游戏按钮,重新开始游戏按钮以及退出游戏按钮游戏界面主框架的主要结构如下图所示。
2.游戏图形区域界面的显示更新功能游戏图形区域界面主要是一个图形显示更新区域,主要包括游戏方块显示更新,整行方块的删除和更新,进行中和游戏结束时的分数更新和游戏图形区域界面的清除。
在这个游戏图形区域界面中,主要是一个表格,根据相应格子的设置标志来显示相应的图形图片,这样就实现了俄罗斯方块的实时显示。
3.游戏方块的设计在俄罗斯方块游戏中,具体的游戏方块图形的设计是比较重要的一个方面。
因为俄罗斯方块游戏中主要的动作就是控制游戏方块的移动和翻转,以便于组成一行行连续的方块从而增加游的分数。
由于主要的游戏动作都集中在这个游戏方块上,因此游戏方块的设计就显得格外重要了。
为了增加程序的可扩展性,这里设计一个游戏方块的基类,各个具体的游戏方块都从这个基类开始继承。
java俄罗斯方块代码
俄罗斯方块代码JDK1.6调试通过调试结果如下:本程序建两个文件,分别命名为RussionBlockGame和Win;其中Win代码如下:import java.awt.*;import java.awt.event.*;import java.awt.geom.*;import javax.swing.*;public class Win{public static void main(String[] args){GameWin frame=new GameWin();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}public static boolean isplaying=true;}class GameWin extends JFrame{public GameWin(){this.setFocusable(true);getContentPane().requestFocus();this.setAlwaysOnTop(true);setTitle("super russionBlock");setBounds(350,90,Default_X,Default_Y);setResizable(false);add(jpy1);jpy1.setDividerLocation(304);jpy1.setDividerSize(4);addKeyListener(jpy2);Thread t=new Thread(jpy2);t.start();}public static final int Default_X=500;public static final int Default_Y=630;private left jpy2=new left();private right jpy3=new right();private JSplitPane jpy1=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jpy2,jpy3); }class right extends JPanel implements ActionListener{public right(){initialframe();initialListener();}public void initialframe(){setLayout(null);add(jlArray[0]);jlArray[0].setBounds(30,60,70,30);jlArray[0].setFocusable(false);add(jlArray[1]);jlArray[1].setBounds(30,140,70,30);jlArray[1].setFocusable(false);add(jcArray[0]);jcArray[0].setBounds(100,60,70,30);jcArray[0].setFocusable(false);add(jcArray[1]);jcArray[1].setBounds(100,140,70,30);jcArray[1].setFocusable(false);add(jbArray[0]);jbArray[0].setBounds(50,240,100,35);jbArray[0].setFocusable(false);add(jbArray[1]);jbArray[1].setBounds(50,310,100,35);jbArray[1].setFocusable(false);add(jbArray[2]);jbArray[2].setBounds(50,380,100,35);jbArray[2].setFocusable(false);add(jbArray[3]);jbArray[3].setBounds(50,450,100,35);jbArray[3].setFocusable(false);}public void initialListener(){for(int i=0;i<4;i++)jbArray[i].addActionListener(this);}public void actionPerformed(ActionEvent e){if(e.getSource()==jbArray[0]){Win.isplaying=true;}else if(e.getSource()==jbArray[1]){Win.isplaying=false;}else if(e.getSource()==jbArray[2]){Win.isplaying=false;}else if(e.getSource()==jbArray[3]){System.exit(0);}}private String[] level={"1","2","3","4","5"};private String[] color={"浅绿","浅黄","黑色"};private JComboBox[] jcArray={new JComboBox(level),new JComboBox(color)};private JLabel[] jlArray={new JLabel("游戏等级"),new JLabel("空间背景")};private JButton[] jbArray={new JButton("开始游戏"),new JButton("暂停游戏"),new JButton("结束游戏"),new JButton("退出游戏")}; }class left extends JComponent implements KeyListener,Runnable{public left(){game=new RussionBlockGame();}public void paintComponent(Graphics g){Graphics2D g2=(Graphics2D)g;super.paintComponent(g);double width=300,height=600;Rectangle2D rect=new Rectangle2D.Double(0,0,width,height);g2.setColor(Color.black);g2.draw(rect);g2.setColor(Color.yellow);g2.fill(rect);g2.setColor(Color.black);g2.draw(rect);for(int i=0;i<20;i++)for(int j=0;j<10;j++){if(game.judge(i,j)==true){Rectangle2D rect3=new Rectangle2D.Double(j*boxSize,i*boxSize,boxSize,boxSize);g2.setColor(Color.black);g2.draw(rect3);g2.setColor(Color.red);g2.fill(rect3);g2.setColor(Color.black);g2.draw(rect3);}}game.notsure();}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(Win.isplaying==false)return;switch(e.getKeyCode()){case KeyEvent.VK_LEFT: //LEFTgame.moveleft();movejudge();break;case KeyEvent.VK_UP: //UPgame.turnright();movejudge();break;case KeyEvent.VK_RIGHT: //RIGHTgame.moveright();movejudge();break;case KeyEvent.VK_DOWN: //DOWNgame.movedown();movejudge();break;}}public void keyReleased(KeyEvent e) {}public void movejudge(){if(game.Iscanmoveto()==true){game.sure();repaint();}else if(game.Ishitbottom()==true) {game.CheckAndCutLine();game.makenewblock();repaint();if(game.IsGameOver()==true)Win.isplaying=false; }}public void run(){try{while(Win.isplaying){Thread.sleep(500);game.movedown();movejudge();}}catch(Exception e){e.printStackTrace();}}private RussionBlockGame game;public static final int boxSize=30;}其次RussionBlockGame代码如下:import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.math.*;public class RussionBlockGame{private int aa=0;private int ic=0;private final int sp_width=10; //游戏界面宽格private final int sp_height=20; //游戏界面高格private final int types[][][]={ //游戏方块{{-1,0},{0,0},{1,0},{2,0}}, //长条{{0,-1},{0,0},{0,1},{0,2}},{{-1,0},{0,0},{1,0},{1,1}}, //直角(右){{0,1},{0,0},{0,-1},{1,-1}},{{1,0},{0,0},{-1,0},{-1,-1}},{{0,-1},{0,0},{0,1},{-1,1}},{{-1,0},{0,0},{0,1},{1,0}}, //直角(中){{0,1},{0,0},{1,0},{0,-1}},{{1,0},{0,0},{0,-1},{-1,0}},{{0,-1},{0,0},{-1,0},{0,1}},{{-1,1},{-1,0},{0,0},{1,0}}, //直接(左){{1,1},{0,1},{0,0},{0,-1}},{{1,-1},{1,0},{0,0},{-1,0}},{{-1,-1},{0,-1},{0,0},{0,1}},{{0,-1},{0,0},{1,0},{1,1}},{{-1,0},{0,0},{0,-1},{1,-1}},{{0,1},{0,0},{1,0},{1,-1}},{{1,0},{0,0},{0,-1},{-1,-1}},{{0,0},{0,1},{1,0},{1,1}} //正方形};private int[][] block_box=new int[4][2]; //四个方块坐标private int[][] block_box_tt=new int[4][2];private int block_x=0,block_y=0; //游戏方块在游戏界面中的坐标private int block_type=0; //方块类别private int[][] game_space=new int[20][10]; //空间数据private int movetype=0;private int scroe=0;private int speed=5;public RussionBlockGame(){clearspace();makenewblock();}public void clearspace() //初始化空间数据{for(int i=0;i<sp_height;i++)for(int j=0;j<sp_width;j++)game_space[i][j]=0;}public void makenewblock() //随机出现方块{aa=(int)(Math.random()*100%7+1);ic=aa*10+1;switch(aa){case 1:block_type=0;break;case 2:block_type=2;break;case 3:block_type=6;break;case 4:block_type=10;break;case 5:block_type=14;break;case 6:block_type=16;break;case 7:block_type=18;}block_x=1;block_y=sp_width/2;for(int i=0;i<4;i++){block_box[i][0]=block_x-types[block_type][i][1];block_box[i][1]=block_y+types[block_type][i][0]; }}public void movedown(){block_x++;for(int i=0;i<4;i++){block_box[i][0]=block_x-types[block_type][i][1]; }movetype=1;}public void moveleft(){block_y--;for(int i=0;i<4;i++){block_box[i][1]=block_y+types[block_type][i][0]; }movetype=2;}public void moveright(){block_y++;for(int i=0;i<4;i++){block_box[i][1]=block_y+types[block_type][i][0]; }movetype=3;}public void turnright(){int[][] block_box_temp=new int[4][2];int block_type_temp=block_type;int id=ic%10;for(int i=0;i<4;i++){block_box_temp[i][0]=block_box[i][0];block_box_temp[i][1]=block_box[i][1];}if(aa==7)return;else if(aa==1||aa==5||aa==6){if(id==2){block_type--;ic--;}else{block_type++;ic++;}}else{if(id==4){block_type=block_type-3;ic=ic-3;}else{block_type++;ic++;}}for(int i=0;i<4;i++){block_box[i][0]=block_x-types[block_type][i][1];block_box[i][1]=block_y+types[block_type][i][0]; }if(Iscanmoveto()==false){ic=ic_temp;block_type=block_type_temp;for(int i=0;i<4;i++){block_box[i][0]=block_box_temp[i][0];block_box[i][1]=block_box_temp[i][1];}}}public void moveback(){if(movetype==1){block_x--;for(int i=0;i<4;i++){block_box[i][0]=block_x-types[block_type][i][1];}}else if(movetype==2){block_y++;for(int m=0;m<4;m++){block_box[m][1]=block_y+types[block_type][m][0];}}else if(movetype==3){block_y--;for(int n=0;n<4;n++){block_box[n][1]=block_y+types[block_type][n][0];}}}public boolean Iscanmoveto(){for(int i=0;i<4;i++){if(block_box[i][0]<0||block_box[i][0]>19){moveback();return false;}else if(block_box[i][1]<0||block_box[i][1]>9){moveback();return false;}else if(game_space[block_box[i][0]][block_box[i][1]]==1){moveback();return false;}}return true;}public boolean Ishitbottom(){for(int i=0;i<4;i++){if(block_box[i][0]+1>19){for(int m=0;m<4;m++){game_space[block_box[m][0]][block_box[m][1]]=1;block_box_tt[m][0]=block_box[m][0];block_box_tt[m][1]=block_box[m][1];block_box[m][0]=0;block_box[m][1]=0;}return true;}}for(int i=0;i<4;i++){if(game_space[block_box[i][0]+1][block_box[i][1]]==1){for(int m=0;m<4;m++){game_space[block_box[m][0]][block_box[m][1]]=1;block_box_tt[m][0]=block_box[m][0];block_box_tt[m][1]=block_box[m][1];block_box[m][0]=0;block_box[m][1]=0;}return true;}}return false;}public void CheckAndCutLine(){int a[]={block_box_tt[0][0],block_box_tt[1][0],block_box_tt[2][0],block_box_tt[3][0]}; int b[]={30,30,30,30};int temp=0;int temp1=0;int count=0;int ss=0;for(int i=0;i<4;i++){for(int j=0;j<10;j++){if(game_space[a[i]][j]==1)temp++;}if(temp==10){for(int m=0;m<4;m++)if(b[m]==a[i]){break;}elsess++;if(ss==4){b[count]=a[i];count++;}}temp=0;ss=0;}for(int i=0;i<3;i++)for(int j=i+1;j<4;j++){if(b[i]>b[j]){temp1=b[i];b[i]=b[j];b[j]=temp1;}}for(int n=0;n<4;n++){if(b[n]==30)break;else{for(int aa=b[n]-1;aa>=0;aa--){for(int bb=0;bb<10;bb++){game_space[aa+1][bb]=game_space[aa][bb];}}for(int cc=0;cc<10;cc++)game_space[0][cc]=0;}}}public boolean IsGameOver(){boolean flag=false;for(int i=0;i<sp_width;i++){if(game_space[0][i]==1){flag=true;break;}}return flag;}public void sure(){for(int i=0;i<4;i++)game_space[block_box[i][0]][block_box[i][1]]=1;}public void notsure(){for(int i=0;i<4;i++)game_space[block_box[i][0]][block_box[i][1]]=0;}public boolean judge(int i,int j){if(game_space[i][j]==1)return true;elsereturn false;}}written by sick_dog邱瑜丹2012.3.27。
俄罗斯方块java代码
g2.drawString("NEXT", 196, 45);
g2.drawString("SCORE",193, 110);
g2.drawString(""+SCORE,205, 130);
g2.drawString("Xiong", 205, 160);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Els extends JFrame implements KeyListener,Runnable
{
public Els()
{
g2.drawLine(0, m, 180, m);
}
//将值不非0的格子涂黑
for(int i=1;i<13;i++)
{
for(int j=0;j<20;j++)
{
g2.setColor(Color.DARK_GRAY);
if (o[i][j]!=0) g2.fillRect(15*i-13, 15*j+2, 13, 13);
}
for(int m=52;m<=92;m+=10)
{
g2.drawLine(192, m, 232, m);
}
//绘制大框格
for(int m=0;m<=180;m+=15)
{
Java编写俄罗斯方块方案和源码
Java编程俄罗斯方块方案和源码开发过程:1)软件的功能描述俄罗斯方块的基本规则:1、一个用于摆放小型正方形的平面虚拟场地,其标准大小:行宽为10,列高为20,以每个小正方形为单位。
2、一组由4个小型正方形组成的规则图形,英文称为Tetromino,中文通称为方块共有7种,分别以S、Z、L、J、I、O、T这7个字母的形状来命名。
I:一次最多消除四层J(左右):最多消除三层,或消除二层L:最多消除三层,或消除二层O:消除一至二层S(左右):最多二层,容易造成孔洞Z (左右):最多二层,容易造成孔洞T:最多二层(1)玩家操作有:旋转方块,以格子为单位左右移动方块,让方块加速落下。
(2)方块移到区域最下方或是着地到其他方块上无法移动时,就会固定在该处,而新的方块出现在区域上方开始落下。
(3)当区域中某一列横向格子全部由方块填满,则该列会消失并成为玩家的得分。
同时删除的列数越多,得分指数上升。
(4)当固定的方块堆到区域最上方而无法消除层数时,则游戏结束。
(6)一般来说,游戏还会提示下一个要落下的方块,熟练的玩家会计算到下一个方块,评估要如何进行。
由于游戏能不断进行下去对商业用游戏不太理想,所以一般还会随着游戏的进行而加速提高难度。
(7)预先设置的随机发生器不断地输出单个方块到场地顶部2)需求分析2.1 找对象,找东西对象关系模型tetris (俄罗斯方块)|-- tetromino 一个正在下落的方块| |-- cells 4个格子|-- nextOne 下一个准备下落的方块| |-- cells 4个格子|-- wall 墙, 是方块下落到底部打散着陆到墙上|-- rows 20行|-- cols 10列个格子2.2 数学模型设计2.3 类的设计: 是根据数学模型设计的属性Tetris (俄罗斯方块)类继承JPanel|-- Tetromino tetromino 正在下落的方块|-- Tetromino nextOne 下一个准备下落的方块|-- Cell[][] wall 是2维数组Tetromino 类|-- Cell[] cells 4个格子T 型方块继承Tetromino 类I 型方块继承Tetromino 类...Cell 类|-- int row 行号|-- int col 列号3)功能分析算法实现功能分析映射到数学模型的数据计算数学模型的数据计算:算法分析策略:功能就是方法,功能的描述中的动词也是方法3.1 下落功能:(softDropAction())如果(检查)能够下落就下落,否则就着陆到墙上,而新的方块出现在区域上方开始落下。
俄罗斯方块java代码
import javax.swing.*;import javax.swing.Timer;import java.awt.*;import java.awt.event.*;import java.util.*;/**Title: 俄罗斯方块*Description: 俄罗斯方块*Copyright: 俄罗斯方块*Company:俄罗斯方块**@author Zhu Yong*@version 1.0*/public class SquaresGame{public static void main(String[]args){ new SquaresFrame().play();}}class SquaresFrame extends JFrame { public final static int WIDTH= 500;public final static int HEIGHT= 600;/***游戏区*/private BoxPanel boxPanel;/***暂停标记*/private boolean isPause= true;/***默认构造函数*/public SquaresFrame(){/***记分面板boxPanel =new BoxPanel(infoPanel);JMenuBar bar = new JMenuBar();JMenu menu = new JMenu("菜单");JMenuItem begin = new JMenuItem("新游戏");final JMenuItem pause = new JMenuItem("暂停"); JMenuItem stop = new JMenuItem("结束");setJMenuBar(bar);bar.add(menu);menu.add(begin);menu.add(pause);menu.add(stop);stop.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){System.exit(0);}});pause.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){if (isPause){boxPanel.supend(false);isPause = ! isPause;pause.setText("恢复");}else {boxPanel.supend(true);isPause = ! isPause;pause.setText("暂停");}}});boxPanel.newGame(); }});boxPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cre ateEtchedBorder(),"Box"));infoPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cr eateEtchedBorder(),"Info"));add(boxPanel,BorderLayout.CENTER);add(infoPanel,BorderLayout.EAST);setTitle("Squares Game");setSize(WIDTH,HEIGHT);//不可改变框架大小setResizable(false);//定位显示到屏幕中间setLocation(((int)Toolkit.getDefaultToolkit().getScreenSize().getWidt h()-WIDTH)/2,((int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()-HEIGHT) /2);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);}public void play() {boxPanel.newGame();}}/****@author Zhu Yong*游戏区面板*/class BoxPanel extends JPanel {/***定义行*/public final static int ROWS= 20;/**public final static int COLS= 10;public final static Color DISPLAY= new Color(128,128,255);/***没有方块时显示的颜色*/public final static Color HIDE= new Color(238,238,238);/***记分面板上显示的下一个方块的颜色*/public final static Color NEXTDISPLAY= Color.ORANGE;/***是否显示网络*/public final static boolean PAINTGRID= false;/***用4个按钮表示一个方块*/private JButton[][]squares= new JButton[ROWS][COLS];/***定义对前位置是否有方块.用颜色区别.*/private int[][]stateTable= new int[ROWS][COLS];private InfoPanel scorePanel;private ABox currentBox;private ABox nextBox;/***各方块颜色数组.其中0号颜色为无方块时颜色.共7种方块 .最后一个消行时颜色 */private static Color[]boxColor= new Color[]{newColor(238,238,238),new Color(128,128,255),new Color(189,73,23), new Color(154,105,22),new Color(101,124,52),newColor(49,100,128),new Color(84,57,119),new Color(111,54,102), new Color(126,50,57),Color.RED};/***定时器,负责方块自动下移*/private Timer timer;/**private int level;/***初时化时的延时*/private final static int INITDELAY= 940;/***每一级别延时减少的步进值*/private final static int INC= 90;public BoxPanel(InfoPanel panel){setLayout(new GridLayout(ROWS,COLS,1,1));//可能获取焦点,才能接受键盘事件setFocusable(true);//setCursor(new Cursor(1));/***初时化,生成JButton,设置颜色.JButton数组按照先第一行再第二行的顺序添加.下标为[行][列]和[x][y]正好相反.*/for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++) {JButton square= new JButton("");square.setEnabled(false);square.setBorderPainted(PAINTGRID);squares[i][j] = square;stateTable[i][j] = 0;add(square);}scorePanel = panel;timer =new Timer(INITDELAY,new autoDownHandler());//注册键盘事件addKeyListener(new KeyAdapter(){ publicvoid keyPressed(KeyEvent e) {int key = e.getKeyCode();//System.out.println(bt.getX()+":"+bt.getY());if (key == KeyEvent.VK_DOWN) dropdown();else if (key == KeyEvent.VK_UP) rotate();else if (key == KeyEvent.VK_RIGHT) right();else if (key == KeyEvent.VK_LEFT) left();/***重新所有方块. 即重新改变所有JButton背景色*/private void showBox(){for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)squares[i][j].setBackground(boxColor[stateTable[i][j]]);}/***只重新显示当前方块*/private void showCurrentBox(){point[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col =location[i].getX();squares[row][col].setBackground(boxColor[stateTable[row][col]]);}}/***消行记分*/private void clearBox(){int clearLines=0;for(int i=ROWS-1;i>=0;i--)for(int j=0;j<COLS;j++) {if (stateTable[i][j]==0) break;if (j==(COLS-1)) {removeLine(i);clearLines++;i++; }}if (clearLines>0) {scorePanel.winScore(clearLines);upgrade();}}/***消行,重置属性表.下移*@param line*/for(int j=0;j<COLS;j++){stateTable[line][j] = 8;//System.out.println(squares[line][j].getBackground());squares[line][j].setBackground(Color.RED);//System.out.println(squares[line][j].getBackground());//validate();}showBox();for (int i=line;i>=0;i--)for(int j=0;j<COLS;j++)if (i!=0)stateTable[i][j] = stateTable[i-1][j];elsestateTable[i][j] = 0;showBox();timer.start();}/***检查把方块移动到(x,y)时是否合法 .*@param x*@param y*@return*/public boolean checkAction(int x,int y) {//先移除当前方块,再判断.当前方块和下一位置的方块有共用的位置.removeCurrentBox();boolean ret = true;point[] list = currentBox.getShape().getList();int xx = 0;int yy = 0;for (int i=0;i<4;i++) {if (i!=0) {xx = list[i].getX()+x;yy = list[i].getY()+y; }else {xx = x; yy = y; }//System.out.println("check"+i+"->"+xx+":"+yy);if ( xx>=COLS|| xx<0) {ret = false;break; } if ( yy>=ROWS|| yy<0 ) {ret = false; break;}//System.out.println("after break check"+i+"->"+xx+":"+yy); if (stateTable[yy][xx]!=0){ret = false; break;}}addCurrentBox();return ret;}*左移*/public void left(){if(checkAction(currentBox.getHead().getX()-1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()-1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***右移*/public void right(){if(checkAction(currentBox.getHead().getX()+1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()+1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***下移*@return*/public boolean down(){int choose=0;if(checkAction(currentBox.getHead().getX(),currentBox.getHead().getY()+1)) {removeCurrentBox();showCurrentBox();etY()+1);addCurrentBox();showCurrentBox();//showBox();return true;}else {clearBox();currentBox = nextBox.setDefault();nextBox = BoxFactory.getBox().setDefault();scorePanel.setNext(nextBox);//showBox();//检查是否游戏结束if (checkGameOver()){supend(false);choose = JOptionPane.showConfirmDialog(this, "游戏结束\n你的积分为"+scorePanel.getScore()+"\n要开始新游戏吗?","GameOver",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);if (choose == JOptionPane.YES_OPTION) newGame();}addCurrentBox();showCurrentBox();//showBox();return false;}}/***丢下.*/public void dropdown() {while (down()) {};}/***判断是否结束*@returnpoint[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col = location[i].getX();if (stateTable[row][col]!=0) return true;}return false;}/***变形*/public void rotate(){if (checkRotate()){removeCurrentBox();showCurrentBox();currentBox.rotate();addCurrentBox();showCurrentBox();//showBox();}}/***检查变形是否合法*@return*/private boolean checkRotate(){removeCurrentBox();int oldheadx =currentBox.getHead().getX(); intoldheady =currentBox.getHead().getY();//System.out.println("oldhead:"+oldheadx+","+oldheady);boolean ret = true;point[] shape = currentBox.getNextShape().getList();int x=0,y=0,newheadx = 0,newheady=0; for(inti=0;i<4;i++) {if (i!=0){x = newheadx + shape[i].getX();y = newheady + shape[i].getY();}else {newheadx = oldheadx + shape[i].getX();newheady = oldheady + shape[i].getY();x = newheadx;y = newheady;//System.out.println("newhead:"+newheadx+":"+newheady);if ( x>=COLS|| x<0) {ret = false;break; } if ( y>=ROWS|| y<0 ){ret = false;break;}//System.out.println("after break checkrotate "+i+"->"+x+":"+y); if (stateTable[y][x]!=0) {ret = false;break;}}addCurrentBox();return ret;}/***移除当前方块.设置颜色为无色.主要用于移动,变形时.清除当前位置方块.显示下一位置方块.*/private void removeCurrentBox(){//System.out.println("removeCurrentBox:"+Thread.currentThread().getNa me());for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = 0;}}/***添加当前方块到属性表.*/private void addCurrentBox(){for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = currentBox.getId();}}/***暂停游戏*false时暂停*@param resume*/public void supend(boolean resume){if (! resume) {timer.stop();else {timer.start();setFocusable(true);this.requestFocus();}}/***设置游戏级别.即改变定时器延时.*@param level*/public void setLevel(int level) {this.level= level;scorePanel.setLevel(level);timer.setDelay(INITDELAY-INC*level);}/***自动下移监听器*@author Administrator**/private class autoDownHandler implements ActionListener { public void actionPerformed(ActionEvent e){ down();}}/***根据积分自动设置级别*/public void upgrade(){int score =scorePanel.getScore();if (score > 3000 &&level<2) setLevel(2); else if (score > 6000 &&level<3) setLevel(3); else if(score > 10000 &&level<4) setLevel(4); else if(score > 15000 &&level<5) setLevel(5); else if(score > 21000 &&level<6) setLevel(6); else if(score > 28000 &&level<7) setLevel(7); else if(score > 35000 &&level<8) setLevel(8); else if(score > 43000 &&level<9) setLevel(9); else if(score > 51000 &&level<10) setLevel(10);}/***重置,开始新游戏.for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)stateTable[i][j] = 0;showBox();setLevel(1);scorePanel.clean();currentBox = BoxFactory.getBox();nextBox = BoxFactory.getBox();scorePanel.setNext(nextBox);setFocusable(true);requestFocus();addCurrentBox();showBox();timer.start();}}/***记分面板*@author Administrator**/class InfoPanel extends JPanel{private JLabel scoreLabel;private JLabel lineLabel;private JLabel levelLabel;private JPanel nextPanel;/***下一个方块*/private JButton[][]nextBox;public InfoPanel(){setLayout(new BorderLayout());Box vbox = Box.createVerticalBox();add(vbox,BorderLayout.CENTER);vbox.add(Box.createRigidArea(new Dimension(12,50)));Box vbox1 = Box.createVerticalBox();vbox.add(vbox1);scoreLabel =new JLabel("0");lineLabel =new JLabel("0");levelLabel =new JLabel("0");nextPanel.setLayout(new GridLayout(4,4,1,1));for(int i=0;i<4;i++)for(int j=0;j<4;j++){JButton bt = new JButton("");bt.setEnabled(false);bt.setBorderPainted(BoxPanel.PAINTGRID);nextPanel.add(bt);nextBox[j][i] = bt;}vbox1.add(new JLabel("Next :"));vbox1.add(nextPanel);vbox1.add(Box.createVerticalStrut(90));vbox1.add(new JLabel("得分:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(scoreLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel("行数:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(lineLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel(" Level :"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(levelLabel);vbox1.add(Box.createVerticalStrut(80));}/***记分.显示在面板上*@param lines*/public void winScore(int lines){int score = 0;lineLabel.setText(""+(Integer.parseInt(lineLabel.getText())+lines));if (lines==1) score = 100;else if (lines ==2) score = 300;else if (lines ==3) score = 500;else if (lines ==4) score = 1000;scoreLabel.setText(""+(Integer.parseInt(scoreLabel.getText())+score)) ;}/***@param next*/public void setNext(ABox next) {for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);int headx = 2; int heady = 0;//设置方块位置if (next.getId() == 1) {headx = 2;heady=0;}else if (next.getId() == 2) {headx = 1;heady = 1;}else if (next.getId() == 3) {headx = 2;heady = 1;}else if (next.getId() == 4) {headx = 1;heady = 1;}else if (next.getId() == 5) {headx = 2;heady = 1;}else if (next.getId() == 6) {headx = 1;heady = 1;}else if (next.getId() == 7) {headx = 1;heady = 1;}point[] shape = next.getShape(0).getList();nextBox[headx][heady].setBackground(BoxPanel.NEXTDISPLAY);nextBox[headx+shape[1].getX()][heady+shape[1].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[2].getX()][heady+shape[2].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[3].getX()][heady+shape[3].getY()].setBackground(B oxPanel.NEXTDISPLAY);}/***设置显示级别*@param level*/public void setLevel(int level) {levelLabel.setText(""+level);}/***获取当前积分*@return*/public int getScore(){return Integer.parseInt(scoreLabel.getText());}*重置*/public void clean(){scoreLabel.setText(""+0);setLevel(1);for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);}}/***方块类*@author Administrator**/class ABox {public final static int ROWS= 20;public final static int COLS= 10;private int id;/***用于存放方块所有样子坐标.*/private ArrayList<BoxShape>shapeTable;private String name;private int currentShapeId;/***当前方块位置.注意这里是坐标(x,y)和squares,stateTable数组的行列顺序正好相反.**/private point[]location;/***方块起始位置.*/private point head= new point(0,COLS/2);public ABox(String name,int id) {= name;this.id= id;shapeTable =new ArrayList<BoxShape>();location =new point[4];}/**public void rotate(){currentShapeId=(currentShapeId+1)>=shapeTable.size()?0:(currentShapeI d+1);point shapehead = shapeTable.get(currentShapeId).getList()[0];setHead(getHead().getX()+shapehead.getX(),getHead().getY()+shapehead. getY());}/***添加方块坐标集*@param shape*/public void addShape(BoxShape shape){shapeTable.add(shape);}/***重设方块位置.定义新的头结点.根据坐标集计算下其它子方块位置.*@param x新位置头结点坐标x*@param y*/public void setHead(int x,int y) {head.setxy(x, y);point[] shapePoint = getShape().getList();location[0] = head;location[1] = head.add(shapePoint[1]);location[2] = head.add(shapePoint[2]);location[3] = head.add(shapePoint[3]);}/***获取位置数组*@return*/public point[] getLocation(){return location;}/***获取头结点*@return*/public point getHead(){/***获取当前坐标集*@return*/public BoxShape getShape(){// get current shapereturn shapeTable.get(currentShapeId);}/***获取下一个坐标集*/public BoxShape getNextShape() {//int index = currentShapeId+1;//if (index>=shapeTable.size()) index = 0;returnshapeTable.get(currentShapeId+1>=shapeTable.size()?0:currentShapeId+1);}/***重置当前方块 .因为游戏中一直在重用方块对象.*@return*/public ABox setDefault(){setHead(4,0);currentShapeId = 0;return this;}/***获取对应坐标集*@param index*@return*/public BoxShape getShape(int index){ return shapeTable.get(index);}/***用于调试*/public String toString(){return ""+name+" "+getHead();}public int getId(){}/***产生方块*@author Administrator**/class BoxFactory {/***ArrayLIst中存放每个方块的一个对象.随机获取.*/private static ArrayList<ABox>aboxes= new ArrayList<ABox>();/***产生方块对象.*/static {/**其中包含4个点.都是相对坐标.第一个坐标是相对变形前根结点坐标的变化量,其它3坐标是相对当前根结点的变化量.对任一方块,可让其处一个3*3或4*4的方阵中,变化时不应脱离此方块,然后以此来计算根结点相对变化值.*****/ABox abox = new ABox("changtiao",1);abox.addShape(new BoxShape(2,-2,0,1,0,2,0,3));abox.addShape(new BoxShape(-2,2,1,0,2,0,3,0));aboxes.add(abox);/** ** **/abox = new ABox("fangkuai",2);abox.addShape(new BoxShape(0,0,1,0,0,1,1,1));aboxes.add(abox);** ***/abox = new ABox("3A",3);abox.addShape(new BoxShape(1,-1,-1,1,0,1,-1,2)); abox.addShape(new BoxShape(-1,1,1,0,1,1,2,1)); aboxes.add(abox);/*** ***/abox = new ABox("3B",4);abox.addShape(new BoxShape(0,0,0,1,1,1,1,2)); abox.addShape(new BoxShape(0,0,1,0,-1,1,0,1)); aboxes.add(abox);/**** **/abox = new ABox("4A",5);abox.addShape(new BoxShape(1,-1,0,1,-1,2,0,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,2,1)); abox.addShape(new BoxShape(1,-1,1,0,0,1,0,2)); abox.addShape(new BoxShape(-1,1,0,1,1,1,2,1)); aboxes.add(abox);/******/abox = new ABox("4b",6);abox.addShape(new BoxShape(1,-1,0,1,0,2,1,2)); abox.addShape(new BoxShape(1,1,-2,1,-1,1,0,1)); abox.addShape(new BoxShape(-1,-1,1,0,1,1,1,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,0,1)); aboxes.add(abox);/**/abox = new ABox("5",7);abox.addShape(new BoxShape(0,0,-1,1,0,1,1,1));abox.addShape(new BoxShape(0,0,-1,1,0,1,0,2));abox.addShape(new BoxShape(-1,1,1,0,2,0,1,1));abox.addShape(new BoxShape(1,-1,0,1,1,1,0,2));aboxes.add(abox);}/***随机获取方块*@return*/public static ABox getBox() {//return aboxes.get(new Random().nextInt(aboxes.size()));return aboxes.get(newRandom().nextInt(aboxes.size())).setDefault();}}/***方块坐标集的一个类,用于简化初始化方块时输入坐标*@author Administrator**/class BoxShape{public int dx1,dx2,dx3,dx4;public int dy1,dy2,dy3,dy4;public BoxShape(int dx1,int dy1,int dx2,int dy2,int dx3,int dy3,int dx4,int dy4){this.dx1= dx1; this.dy2= dy2;this.dx3= dx3; this.dy4= dy4;}/** this.dy1= dy1;this.dy3= dy3;this.dx2= dx2;this.dx4= dx4;*返回坐标点数组*@return*/public point[] getList(){return new point[]{new point(dx1,dy1),new point(dx2,dy2),new point(dx3,dy3),new point(dx4,dy4)};}*一个坐标的类 .可用Point,Dimension代替*@author Administrator**/class point {private int x;private int y;public point (int x,int y) {this.x= x;this.y= y;}public int getX(){return x;}public int getY(){return y;}public point add(point other){return new point(x+other.getX(),y+other.getY());}public void setxy(int x,int y){this.x= x;this.y= y;}public String toString() {return ""+x+":"+y;}}THE UNIVERSITY OF AUCKLANDFIRST SEMESTER, 2011Campus: CityCOMPUTER SCIENCEPrinciples of Programming(Time Allowed: TWO hours)Note:*The use of calculators is NOT permitted.*You should separate the Section A Question Booklet from the Section B Question/Answer Booklet. You may keep the Section A Question Booklet. You must hand in the Section BQuestion/Answer booklet and the Teleform sheet.*Compare the exam version number on the Teleform sheet supplied with the version number above. If they do not match, ask the supervisor for a new sheet.*Enter your name and student ID on the Teleform sheet. Your name should be entered left aligned. If your name is longer than the number of boxes provided, truncate it.*Answer Section A on the Teleform answer sheet provided. Each question in this section is worth 2 marks.*For Section A, use a dark pencil to mark your answers in the answer boxes on the Teleform sheet.Check that the question number on the sheet corresponds to the question number in thisquestion/answer book. Do not cross out answers on the Teleform sheet if you change your mind.You must completely erase one answer before you choose another one. If you spoil your sheet,ask the supervisor for a replacement. There is one correct answer per question.*Answer Section B in the space provided in the Section B Question/Answer Booklet.*Attempt all questions. Write as clearly as possible. The space provided will generally be sufficient but is not necessarily an indication of the expected length. Extra space is providedat the end of this exam book.CONTINUEDVERSION 00000001- 2 -COMPSCI 101PLEASE CHECK BEFORE YOU START:Have you entered your name and student ID on the Teleform sheet (letters written in the boxesand corresponding circles filled in) and on the front of the Section B question/answer booklet?*What output is produced when the following code is executed?System.out.println("[" + 4 + 4 + 3 * 5 / 2 + "," + 2 + 2 + "]");[447.5,22][15.5,22][447,22][15.5,4][15,22]*Which of the following outputs could NOT have been produced by the following code?int a = (int) (Math.random() * (4 - 1));int b = (int) (Math.random() * 4) - 1;System.out.println("a: " + a + " b: " + b);*a: 0 b: 2*a: 2 b: -1*a: 0 b: 0*a: -1 b: 2*None of the above3) What output is produced when the following code is executed?int a = 9;int b = 1;int c = a % (a - 1);int d = b % (b + 1);int sum = c + d;System.out.println("sum: " + sum);*sum: 10*sum: 2*sum: 9*sum: 1*None of the above*What output is produced when the following code is executed?String word = "SPLENDID";int pos1 = word.indexOf("S");int pos2 = word.indexOf("word");int sum = pos1 + pos2;System.out.println(sum);*-2*1*0*-1*None of the above*What output is produced when the following is executed?String word = "JOYFUL";char c = word.charAt(word.length() - 2);word = word.substring(0, 1) + word.substring(3) + c;System.out.println(word);JOFULFJFULUJOFULUJFULFNone of the above*Consider the following variable declarations:Point p1, p2;Rectangle r1, r2;p1 = new Point(10, 20);p2 = new Point(30, 40);r1 = new Rectangle(10, 20, 30, 40);r2 = new Rectangle(50, 60, 70, 80);Given these variable declarations, only ONE of the following statements will COMPILE. Which one?*boolean result = p1.intersects(p2);*boolean result = p1.contains(r1);*boolean result = p2.contains(p2);*boolean result = r2.contains(p1);*boolean result = r1.intersects(p2);7) What is the output of the following code?boolean a = true;boolean b = true;boolean c = false;if (c) {System.out.println("first");} else if (a && c){ if (a || b) {System.out.println("second"); } else {System.out.println("third");}} else if (a || c){ System.out.println("fourth");} else {System.out.println("fifth");}*fifth*third*second*first*fourth*Given the isPerfect() method defined below, which of the following sections of code prints “yes”?private boolean isPerfect(int n1, int n2, int n3) {int sum = n1 + n2 + n3;int product = n1 * n2 * n3;if (sum == product) {return true;}return false;}*if (isPerfect(0, 3, 3)){ System.out.println("yes");}*if (isPerfect(-1, 6, 1)) {System.out.println("yes");}*if (isPerfect(1, 2, 3)){ System.out.println("yes");}*if (isPerfect(2, 2, 2)){ System.out.println("yes");}(e) None of the above*What is the output of the following code?public void start(){ int a, b;a = 1;b = 2;exam(a, b);System.out.print("a: " + a + ", ");System.out.print("b: " + b);}private void exam(int a, int other) {a = a + 1;other = other + 1;}*a: 1, b: 2*a: 2, b: 3*a: 2, b: 2*a: 1, b: 3*The code would not compile because the names of the parameters in the method definition do not match the names of the variables in the statement that calls the method.10) What output is produced by the following code segment?int counter = 1;int sum = 0;while (counter <= 3) {sum += counter;}System.out.println(sum);//6//2//Nothing, because the loop never stops.//Nothing, because the variable sum is out of scope.//311) What output is produced by the following code segment?int i = 7;int counter = 0;while (i >= 0) {counter++;i = i - 3;}System.out.println(counter);*3*4*2*Nothing, because the variable counter is out of scope.*Nothing, because the loop never stops.12) A for loop has the following basic structure:for (initialisation; condition; increment) {...}Which of the following is the correct order in which the three component parts of the loop would be encountered if the loop executed exactly twice?(a) initialisation condition condition increment increment increment(c) initialisation increment increment condition condition condition(d) initialisation condition increment condition increment(e) initialisation increment condition increment condition increment13) What output is produced by the following code?String[] words = {"one", "two", "buckle", "my", "shoe"};for (int i = 0; i < words.length; i++) {if (words[i].length() <= 3){ System.out.print(words[i].charAt(0));}}*tbms*otm*bms*otbms*Nothing would be printed*What output is produced by the following code segment?int sum = 0;for (int i = 1; i < 5; i++) {sum += i;}System.out.println(sum);*15*4*6*10*Nothing, because the variable sum is out of scope.15) Consider the following while loop:int i = 10;while (i > 0) {System.out.println(i * i);i -= 2;}Which of the following for loops is equivalent to this while loop?*for (int i = 0; i < 10; i++) {System.out.println(i * i);}*for (int i = 10; i > 0; i--){ System.out.println(i * i);}*for (int i = 0; i <= 10; i=i+2) {System.out.println(i * i);}*for (int i = 10; i >= 0; i=i-2){ System.out.println(i * i);}*for (int i = 10; i > 0; i=i-2) {System.out.println(i * i);}。
俄罗斯方块java代码1
/*** File: ErsBlocksGame.java* User: Administrator* Date: Dec 15, 2003* Describe: 俄罗斯方块的Java 实现*/import javax.swing.*;import java.awt.*;import java.awt.event.*;/*** 游戏主类,继承JFrame类,负责游戏的全局控制。
* 内含* 1, 一个GameCanvas画布类的实例引用,* 2, 一个保存当前活动块(ErsBlock)实例的引用,* 3, 一个保存当前控制面板(ControlPanel)实例的引用;*/public class ErsBlocksGame extends JFrame {/*** 每填满一行计多少分*/public final static int PER_LINE_SCORE = 100;/*** 积多少分以后能升级*/public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20;/*** 最大级数是10级*/public final static int MAX_LEVEL = 10;/*** 默认级数是5*/public final static int DEFAULT_LEVEL = 5;//一个GameCanvas画布类的实例引用,private GameCanvas canvas;// 一个保存当前活动块(ErsBlock)实例的引用,private ErsBlock block;// 一个保存当前控制面板(ControlPanel)实例的引用; private ControlPanel ctrlPanel;private boolean playing = false;private JMenuBar bar = new JMenuBar();//菜单条包含4个菜单private JMenumGame = new JMenu("游戏"),mControl = new JMenu("控制"),mWindowStyle = new JMenu("窗口风格"),mInfo = new JMenu("帮助");//4个菜单中分别包含的菜单项private JMenuItemmiNewGame = new JMenuItem("新游戏"),miSetBlockColor = new JMenuItem("设置方块颜色"),miSetBackColor = new JMenuItem("设置背景颜色"),miTurnHarder = new JMenuItem("增加难度"),miTurnEasier = new JMenuItem("降低难度"),miExit = new JMenuItem("退出"),miPlay = new JMenuItem("开始"),miPause = new JMenuItem("暂停"),miResume = new JMenuItem("继续"),miStop = new JMenuItem("停止"),miAuthor = new JMenuItem("作者: Java游戏设计组"),miSourceInfo = new JMenuItem("版本:1.0");//设置窗口风格的菜单private JCheckBoxMenuItemmiAsWindows = new JCheckBoxMenuItem("Windows"),miAsMotif = new JCheckBoxMenuItem("Motif"),miAsMetal = new JCheckBoxMenuItem("Metal", true);/*** 主游戏类的构造函数* @param title String,窗口标题*/public ErsBlocksGame(String title) {super(title);//初始窗口的大小,用户可调控setSize(315, 392);Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();//将游戏窗口置于屏幕中央setLocation((scrSize.width - getSize().width) / 2,(scrSize.height - getSize().height) / 2);//创建菜单createMenu();Container container = getContentPane();// 布局的水平构件之间有6个象素的距离container.setLayout(new BorderLayout(6, 0));// 建立20个方块高,12个方块宽的游戏画布canvas = new GameCanvas(20, 12);//建立一个控制面板ctrlPanel = new ControlPanel(this);//游戏画布和控制面板之间左右摆放container.add(canvas, BorderLayout.CENTER);container.add(ctrlPanel, BorderLayout.EAST);//增加窗口监听器addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {stopGame();System.exit(0);}});//增加构件的适配器,一旦构件改变大小,就调用//fanning()方法,自动调整方格的尺寸addComponentListener(new ComponentAdapter() {public void componentResized(ComponentEvent ce) {canvas.fanning();}});show(); //setVisiable// 根据窗口的大小,自动调整方格的尺寸canvas.fanning();}/*** 让游戏“复位”*/public void reset() {ctrlPanel.reset(); //控制窗口复位canvas.reset(); //游戏画板复位}/*** 判断游戏是否还在进行* @return boolean, true-还在运行,false-已经停止*/public boolean isPlaying() {return playing;}/*** 得到当前活动的块* @return ErsBlock, 当前活动块的引用*/public ErsBlock getCurBlock() {return block;}/*** 得到当前画布* @return GameCanvas, 当前画布的引用*/public GameCanvas getCanvas() {return canvas;}/*** 开始游戏*/public void playGame() {play();ctrlPanel.setPlayButtonEnable(false);miPlay.setEnabled(false);ctrlPanel.requestFocus();}/*** 游戏暂停*/public void pauseGame() {if (block != null) block.pauseMove();ctrlPanel.setPauseButtonLabel(false);miPause.setEnabled(false);miResume.setEnabled(true);}/*** 让暂停中的游戏继续*/public void resumeGame() {if (block != null) block.resumeMove();ctrlPanel.setPauseButtonLabel(true);miPause.setEnabled(true);miResume.setEnabled(false);ctrlPanel.requestFocus();}/*** 用户停止游戏*/public void stopGame() {playing = false;if (block != null) block.stopMove();miPlay.setEnabled(true);miPause.setEnabled(true);miResume.setEnabled(false);ctrlPanel.setPlayButtonEnable(true);ctrlPanel.setPauseButtonLabel(true);}/*** 得到当前游戏者设置的游戏难度* @return int, 游戏难度1-MAX_LEVEL=10 */public int getLevel() {return ctrlPanel.getLevel();}/*** 让用户设置游戏难度系数* @param level int, 游戏难度系数为1-MAX_LEVEL=10 */public void setLevel(int level) {if (level < 11 && level > 0) ctrlPanel.setLevel(level);}/*** 得到游戏积分* @return int, 积分。
java俄罗斯方块完整代码
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_Q) {//如果按Q
System.exit(0);//结束Java进程
}
if(gameOver) {//如果游戏结束
T = ImageIO.read(Tetris.class.getResource("tT.png"));
I = ImageIO.read(Tetris.class.getResource("II.png"));
S = ImageIO.read(Tetris.class.getResource("SS.png"));
}else {
g.drawImage(cell.getImage(),x-1,y-1,null);//有格子贴图
}
}
}
}
//添加启动方法
public void action() {
wall = new Cell[ROWS][COLS];
//启动
startAction();
//处理键盘按下事件
KeyAdapter l = new KeyAdapter(){
if(gameOver) {
g.drawImage(overImage,0,0,null);
}
}
//画分数
private void paintScore(Graphics g) {
int x = 390;//基线位置
int y = 190;//基线位置
g.setColor(new Color(FONT_COLOR));//颜色
俄罗斯方块java代码5
* File: GameCanvas.java* User: Administrator* Date: Dec 15, 2003* Describe: 俄罗斯方块的每一个方块的绘制*/import javax.swing.*;import javax.swing.border.EtchedBorder;//EtchedBorder为swing包中的突出或凹进的边框import java.awt.*;/*** 画布类,内有<行数> * <列数>个方格类的实例。
* 继承JPanel类。
* ErsBlock线程类动态改变画布类的方格颜色,画布类通过* 检查方格颜色来体现ErsBlock块的移动情况。
*/class GameCanvas extends JPanel {//默认的方块的颜色为桔黄色,背景颜色为黑色private Color backColor = Color.black, frontColor = Color.orange;private int rows, cols, score = 0, scoreForLevelUpdate = 0;private ErsBox[][] boxes;private int boxWidth, boxHeight;//score:得分,scoreForLevelUpdate:上一次升级后的积分/*** 画布类的第一个版本的构造函数* @param rows int, 画布的行数* @param cols int, 画布的列数* 行数和列数以方格为单位,决定着画布拥有方格的数目*/public GameCanvas(int rows, int cols) {this.rows = rows;this.cols = cols;//初始化rows*cols个ErsBox对象boxes = new ErsBox[rows][cols];for (int i = 0; i < boxes.length; i++) {for (int j = 0; j < boxes[i].length; j++) {boxes[i][j] = new ErsBox(false);}}//设置画布的边界setBorder(new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140))); }/*** 画布类的第二个版本的构造函数* @param rows 与public GameCanvas(int rows, int cols)的rows相同* @param cols 与public GameCanvas(int rows, int cols)的cols相同* @param backColor Color, 背景色* @param frontColor Color, 前景色*/public GameCanvas(int rows, int cols,Color backColor, Color frontColor) {this(rows, cols);//调用第一个版本的构造函数this.backColor = backColor;this.frontColor = frontColor;//通过参数设置背景和前景颜色}/*** 设置游戏背景色彩* @param backColor Color, 背景色彩*/public void setBackgroundColor(Color backColor) {this.backColor = backColor;}/*** 取得游戏背景色彩* @return Color, 背景色彩*/public Color getBackgroundColor() {return backColor;}/*** 设置游戏方块色彩* @param frontColor Color, 方块色彩*/public void setBlockColor(Color frontColor) {this.frontColor = frontColor;/*** 取得游戏方块色彩* @return Color, 方块色彩*/public Color getBlockColor() {return frontColor;}/*** 取得画布中方格的行数* @return int, 方格的行数*/public int getRows() {return rows;}/*** 取得画布中方格的列数* @return int, 方格的列数*/public int getCols() {return cols;}/*** 取得游戏成绩* @return int, 分数*/public int getScore() {return score;}/*** 取得自上一次升级后的积分* @return int, 上一次升级后的积分*/public int getScoreForLevelUpdate() {return scoreForLevelUpdate;}/*** 升级后,将上一次升级以来的积分清0public void resetScoreForLevelUpdate() {scoreForLevelUpdate -= ErsBlocksGame.PER_LEVEL_SCORE;}/*** 得到某一行某一列的方格引用。
俄罗斯方块——java源代码
levelField = new TextField(8);
scoreField.setEditable(false);
levelField.setEditable(false);
infoScr.add(scorep);
infoScr.add(scoreField);
int [][] scrArr; //屏幕数组
Block b; //对方快的引用
//画布类的构造方法
GameCanvas(){
rowNum = 15;
columnNum = 10;
maxAllowRowNum = rowNum - 2;
b = new Block(this);
blockInitRow = rowNum - 1;
ers.addWindowListener(win_listener);
}
//俄罗斯方块类的构造方法
ERS_Block(String title){
super(title);
setSize(600,480);
setLayout(new GridLayout(1,2));
gameScr = new GameCanvas();
controlScr.add(pause_b);
controlScr.add(quit_b);
setVisible(true);
gameScr.requestFocus();
}
}
//重写MyPanel类,使P
anel的四周留空间
levelField.setSize(new Dimension(20,60));
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
frame.setVisible(true);
frame.setResizable(false);
}
}
// 创建一个俄罗斯方块类
class Tetrisblok extends JPanel implements KeyListener {
}
}
// 画围墙
public void drawwall() {
for (i = 0; i < 12; i++) {
map[i][21] = 2;
}
for (j = 0; j < 22; j++) {
{ 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
// o
private final int shapes[][][] = new int[][][] {
// i
{ { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },
map[i][j] = 0;
}
}
Hale Waihona Puke } // 初始化构造方法
Tetrisblok() {
newblock();
newmap();
drawwall();
add(a);
}
public static void main(String[] args) {
Tetris frame = new Tetris();
JMenuBar menu = new JMenuBar();
frame.setJMenuBar(menu);
JMenuItem exit = game.add("退出");
JMenu help = new JMenu("帮助");
JMenuItem about = help.add("关于");
menu.add(game);
menu.add(help);
// j
{ { 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(220, 275);
frame.setTitle("Tetris内测版");
{ 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 } } };
// 生成新方块的方法
JMenu game = new JMenu("游戏");
JMenuItem newgame = game.add("新游戏");
JMenuItem pause = game.add("暂停");
JMenuItem goon = game.add("继续");
Timer timer = new Timer(1000, new TimerListener());
timer.start();
}
// 旋转的方法
public void turn() {
int tempturnState = turnState;
public void newblock() {
blockType = (int) (Math.random() * 1000) % 7;
turnState = (int) (Math.random() * 1000) % 4;
x = 4;
{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 } },
// z
{ { 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// t
{ { 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
y = 0;
if (gameover(x, y) == 1) {
newmap();
drawwall();
score = 0;
JOptionPane.showMessageDialog(null, "GAME OVER");
turnState = tempturnState;
}
repaint();
}
// 左移的方法
public void left() {
import javax.swing.*;
import javax.swing.Timer;
public class Tetris extends JFrame {
public Tetris() {
Tetrisblok a = new Tetrisblok();
addKeyListener(a);
turnState = (turnState + 1) % 4;
if (blow(x, y, blockType, turnState) == 1) {
}
if (blow(x, y, blockType, turnState) == 0) {
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
// l
{ { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
map[11][j] = 2;
map[0][j] = 2;
}
}
// 初始化地图
public void newmap() {
for (i = 0; i < 12; i++) {
for (j = 0; j < 22; j++) {
{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } },
{ { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
Java codeimport java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
{ 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 } },
// s
// blockType 代表方块类型
// turnState代表方块状态
private int blockType;
private int score = 0;
private int turnState;
private int x;
{ { 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
private int y;
private int i = 0;
int j = 0;
int flag = 0;
// 定义已经放下的方块x=0-11,y=0-21;
int[][] map = new int[13][23];