3一个JAVA编写的俄罗斯方块游戏代码
小游戏俄罗斯方块代码(JAVA)
东西绝对不多说,直接看!看了拷贝就懂了!!,直接可以拷贝下面的东西,然后记得把那个BLOCK的名字改成你自己的类名,这个很关键哦,不然是错的可别怪我,呵呵~~import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class Block 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[]) {Block myBlock = new Block();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;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[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;game_body[game_sign_y[3] - 1][game_sign_x[3] - 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[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[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[2][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[3][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{Block myBlock;public MyTimer(Block myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){} }}}。
俄罗斯方块JAVA小程序
以下是源代码:
/*程序:SingleTetris.java *说明:单一俄罗斯方块游戏类 */
//产生下一组砖块 public void createNextBrick(){
//产生预备砖块组编号 NextBrickArray.add(new Integer((int)(Math.random()*BrickArray.size()))); //产生预备砖块组颜色 NextBrickColorArray.add(new Color((int)(Math.random()*128+127),
createNextBrick(); }
//建立绘出砖块组对象 d=new Draw(this);
//画出外框 d.DrawMapFrame(0,0,GRIDX*BRICK_WIDTH+2*5,GRIDY*BRICK_WIDTH+2*5,5) ; d.DrawMapFrame(290,0,200,350,5);//预备方块外框 d.DrawMapFrame(290,350,200,140,5);//游戏数据外框
int NOW_BRICK_X;//现在动作砖块组的 x 坐标 int NOW_BRICK_Y;//现在动作砖块组的 y 坐标 SuperBrick NowBrick;//现在动作的砖块组 Color NOW_BRICK_COLOR;//现在动作砖块组的颜色
ArrayList BrickArray;//所有砖块组类数组 ArrayList NextBrickArray;//下一个砖块组储存数组 ArrayList NextBrickColorArray;//下一个砖块组储存数组
俄罗斯方块完整源代码
//不多说,直接可以拷贝下面的东西,就可以运行。
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代码6
=================1======================package russia;/** 控制面板类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class ControlPanel extends JPanel{private TipBlockPanel tipBlockPanel;private JPanel tipPanel,InfoPanel,buttonPanel;private final JTextField levelField,scoreField;private JButton playButton,pauseButton,stopButton,turnHarderButton,turnEasilyButton;private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;private RussiaBlocksGame game;private Timer timer;public ControlPanel(final RussiaBlocksGame game){this.game = game;/**图形界面部分*/setLayout(new GridLayout(3,1,0,4));tipBlockPanel = new TipBlockPanel();tipPanel = new JPanel( new BorderLayout() );tipPanel.add( new JLabel("Next Block:") , BorderLayout.NORTH );tipPanel.add( tipBlockPanel , BorderLayout.CENTER );tipPanel.setBorder(border);InfoPanel = new JPanel( new GridLayout(4,1,0,0) );levelField = new JTextField(""+RussiaBlocksGame.DEFAULT_LEVEL);levelField.setEditable(false);scoreField = new JTextField("0");scoreField.setEditable(false);InfoPanel.add(new JLabel("Level:"));InfoPanel.add(levelField);InfoPanel.add(new JLabel("Score:"));InfoPanel.add(scoreField);InfoPanel.setBorder(border);buttonPanel = new JPanel(new GridLayout(5,1,0,0));playButton = new JButton("Play");pauseButton = new JButton("Pause");stopButton = new JButton("Stop");turnHarderButton = new JButton("Turn harder"); turnEasilyButton = new JButton("Turn easily");buttonPanel.add(playButton);buttonPanel.add(pauseButton);buttonPanel.add(stopButton);buttonPanel.add(turnHarderButton);buttonPanel.add(turnEasilyButton);buttonPanel.setBorder(border);addKeyListener(new ControlKeyListener());//添加add(tipPanel);add(InfoPanel);add(buttonPanel);/**添加事件监听器*/playButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){game.playGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});pauseButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){if(pauseButton.getText().equals("Pause"))game.pauseGame();elsegame.resumeGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});stopButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){game.stopGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});turnHarderButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){int level = 0;try{level = Integer.parseInt(levelField.getText());setLevel(level + 1);}catch(NumberFormatException e){e.printStackTrace();}requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});turnEasilyButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){int level = 0;try{level = Integer.parseInt(levelField.getText());setLevel(level - 1);}catch(NumberFormatException e){e.printStackTrace();}requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});/** 时间驱动程序,每格500毫秒对level,score值进行更新*/timer = new Timer(500,new ActionListener(){public void actionPerformed(ActionEvent event){scoreField.setText(""+game.getScore());game.levelUpdate();}});timer.start();}/** 设置预显方块的样式*/public void setBlockStyle(int style){tipBlockPanel.setStyle(style);tipBlockPanel.repaint();}/** 重置,将所有数据恢复到最初值*/public void reset(){levelField.setText(""+RussiaBlocksGame.DEFAULT_LEVEL); scoreField.setText("0");setPlayButtonEnabled(true);setPauseButtonLabel(true);tipBlockPanel.setStyle(0);}/**设置playButton是否可用*/public void setPlayButtonEnabled(boolean enable){playButton.setEnabled(enable);/**设置pauseButton的文本*/public void setPauseButtonLabel(boolean pause){pauseButton.setText( pause ? "Pause" : "Rusume" );}/**设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸*/public void fanning(){tipBlockPanel.fanning();}/**根据level文本域的值返回当前的级别*/public int getLevel(){int level = 0;try{level=Integer.parseInt(levelField.getText());}catch(NumberFormatException e){e.printStackTrace();}return level;}/** 设置level文本域的值*/public void setLevel(int level){if(level > 0 && level <= RussiaBlocksGame.MAX_LEVEL) levelField.setText("" + level);}/** 内部类为预显方块的显示区域*/private class TipBlockPanel extends JPanel{private Color bgColor = Color.darkGray,blockColor = Color.lightGray;private RussiaBox [][]boxes = new RussiaBox[RussiaBlock.ROWS][RussiaBlock.COLS]; private int boxWidth, boxHeight,style;private boolean isTiled = false;/** 构造函数*/public TipBlockPanel(){for(int i = 0; i < boxes.length; i ++)for(int j = 0; j < boxes[i].length; j ++){boxes[i][j]=new RussiaBox(false);}style = 0x0000;}/** 构造函数*/public TipBlockPanel(Color bgColor, Color blockColor){this();this.bgColor = bgColor;this.blockColor = blockColor;}/** 设置方块的风格*/public void setStyle(int style){this.style = style;repaint();}/** 绘制预显方块*/public void paintComponent(Graphics g){super.paintComponent(g);int key = 0x8000;if(!isTiled)fanning();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j<boxes[i].length ;j ++){Color color = (style & key) != 0 ? blockColor : bgColor;g.setColor(color);g.fill3DRect(j * boxWidth, i * boxHeight, boxWidth, boxHeight, true);key >>=1;}}/**设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸*/public void fanning(){boxWidth = getSize().width / RussiaBlock.COLS;boxHeight = getSize().height /RussiaBlock.ROWS;isTiled=true;}}/**内部类键盘键听器,响应键盘事件*/class ControlKeyListener extends KeyAdapter {public void keyPressed(KeyEvent ke){if (!game.isPlaying()) return;RussiaBlock block = game.getCurBlock();switch (ke.getKeyCode()) {case KeyEvent.VK_DOWN:block.moveDown();break;case KeyEvent.VK_LEFT:block.moveLeft();break;case KeyEvent.VK_RIGHT:block.moveRight();break;case KeyEvent.VK_UP:block.turnNext();break;case KeyEvent.VK_SPACE://一键到底while(block.moveDown()){}break;default:break;}}}}=================2=================================== package russia;/** 游戏中方块显示的画布类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class GameCanvas extends JPanel{private RussiaBox [][]boxes;private int rows = 20 , cols = 12;private static GameCanvas canvas=null;private int boxWidth, boxHeight;//默认为零需要调用fanning函数设置private Color blockColor = Color.RED, bgColor = new Color(0,204,204);private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;/**采用单件模式,构造函数私有*/private GameCanvas(){boxes = new RussiaBox[rows][cols];for(int i = 0; i < boxes.length; i ++)for(int j = 0; j<boxes[i].length; j ++)boxes[i][j] = new RussiaBox(false);setBorder(border);}/**获得GameCanvas实例*/public static GameCanvas getCanvasInstance(){if(canvas == null)canvas = new GameCanvas();return canvas;}/**设置画布的背景色*/public void setBgColor(Color bgColor){this.bgColor = bgColor;}/** 获得画布的背景色*/public Color getBgColor(){return bgColor;}/**设置方块的颜色*/public void setBlockColor(Color blockColor) {this.blockColor = blockColor;}/**方块的颜色*/public Color getBlockColor(){return blockColor;}/**设置画布中方块的行数*/public void setRows(int rows){this.rows = rows;}/**得到画布中方块的行数*/public int getRows(){return rows;}/**设置画布中方块的列数*/public void setCols(int cols){this.cols = cols;}/**得到画布中方块的列数*/public int getCols(){return cols;}/**得到row行,col列的方格*/public RussiaBox getBox(int row, int col){if(row >= 0 && row < rows && col >= 0 && col < cols)return boxes[row][col];elsereturn null;}/**在画布中绘制方块*/public void paintComponent(Graphics g){super.paintComponent(g);fanning();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j < boxes[i].length; j ++){Color color = boxes[i][j].isColorBox() ? blockColor : bgColor;g.setColor(color);g.fill3DRect(j * boxWidth, i * boxHeight , boxWidth , boxHeight , true);}}/**清除第row行*/public void removeLine(int row){for(int i = row; i > 0; i --)for(int j = 0; j < cols; j ++){boxes[i][j] = (RussiaBox)boxes[i-1][j].clone();}}/**重置为初始时的状态*/public void reset(){for(int i = 0; i < boxes.length; i++)for(int j = 0 ;j < boxes[i].length; j++){boxes[i][j].setColor(false);}repaint();}/** 根据窗体的大小自动调整方格的大小*/public void fanning(){boxWidth = getSize().width / cols;boxHeight = getSize().height / rows;}}====================3======================= package russia;/** 方块类*/public class RussiaBlock extends Thread{private int style,y,x,level;private boolean moving,pausing;private RussiaBox boxes[][];private GameCanvas canvas;public final static int ROWS = 4;public final static int COLS = 4;public final static int BLOCK_KIND_NUMBER = 7; public final static int BLOCK_STATUS_NUMBER = 4; public final static int BETWEEN_LEVELS_TIME = 50; public final static int LEVEL_FLATNESS_GENE = 3;/**方块的所有风格及其不同的状态*/public final static int[][] STYLES = {// 共28种状态{0x0f00, 0x4444, 0x0f00, 0x4444}, // 长条型的四种状态{0x04e0, 0x0464, 0x00e4, 0x04c4}, // 'T'型的四种状态{0x4620, 0x6c00, 0x4620, 0x6c00}, // 反'Z'型的四种状态{0x2640, 0xc600, 0x2640, 0xc600}, // 'Z'型的四种状态{0x6220, 0x1700, 0x2230, 0x0740}, // '7'型的四种状态{0x6440, 0x0e20, 0x44c0, 0x8e00}, // 反'7'型的四种状态{0x0660, 0x0660, 0x0660, 0x0660}, // 方块的四种状态};/**构造函数*/public RussiaBlock(int y,int x,int level,int style){this.y = y;this.x = x;this.level = level;moving = true;pausing = false;this.style = style;canvas = GameCanvas.getCanvasInstance();boxes = new RussiaBox[ROWS][COLS];int key = 0x8000;for(int i = 0; i < boxes.length; i++)for(int j = 0; j < boxes[i].length; j++){boolean isColor = ( (style & key) != 0 );boxes[i][j] = new RussiaBox(isColor);key >>= 1;}display();}/**线程的run方法控制放块的下落及下落速度*/public void run(){while(moving){try{sleep( BETWEEN_LEVELS_TIME * (RussiaBlocksGame.MAX_LEVEL - level + LEVEL_FLATNESS_GENE) );if(!pausing)moving = ( moveTo(y + 1,x) && moving );}catch(InterruptedException e){e.printStackTrace();}}}/**暂停移动*/public void pauseMove(){pausing = true;}/**从暂停状态恢复*/public void resumeMove(){pausing = false;}/**停止移动*/public void stopMove(){moving = false;}/**向左移一格*/public void moveLeft(){moveTo(y , x - 1);}/**向右移一格*/public void moveRight(){moveTo(y , x + 1);}/**向下移一格,返回与其他几个不同,为了一键到底*/public boolean moveDown(){if(moveTo(y + 1, x))return true;elsereturn false;}/**移到newRow,newCol位置*/public synchronized boolean moveTo(int newRow, int newCol){//erase();//必须在判断前进行擦除,否则isMoveable将产生错误行为if(!moving || !isMoveable(newRow,newCol)){display();return false;}y = newRow;x = newCol;display();canvas.repaint();return true;}/**判断能否移到newRow,newCol位置*/private boolean isMoveable(int newRow, int newCol){erase();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j< boxes[i].length; j ++ ){if( boxes[i][j].isColorBox() ){RussiaBox box = canvas.getBox(newRow + i, newCol + j);if(box == null || box.isColorBox())return false;}}return true;/**通过旋转变为下一种状态*/public void turnNext(){int newStyle = 0;for(int i = 0; i < STYLES.length; i ++)for(int j = 0 ;j < STYLES[i].length; j++){if(style == STYLES[i][j]){newStyle = STYLES[i][(j + 1)%BLOCK_STATUS_NUMBER];break;}}turnTo(newStyle);}/**通过旋转变能否变为newStyle状态*/private synchronized boolean turnTo(int newStyle){//erase();//擦除之后在判断isTurnNextAbleif(!moving || !isTurnable(newStyle)){display();return false;}style=newStyle;int key = 0x8000;for(int i = 0; i < boxes.length; i ++)for(int j = 0 ;j < boxes[i].length; j++){boolean isColor = ((key & style) != 0 );boxes[i][j].setColor(isColor);key >>=1;}display();canvas.repaint();return true;}*判断通过旋转能否变为下一种状态*/private boolean isTurnable(int newStyle){erase();int key = 0x8000;for(int i = 0; i< boxes.length; i++)for(int j=0; j<boxes[i].length; j++){if((key & newStyle) != 0){RussiaBox box = canvas.getBox(y + i, x + j);if(box == null || box.isColorBox())return false;}key >>= 1;}return true;}/**擦除当前方块(只是设置isColor属性,颜色并没有清除,为了判断能否移动之用) */private void erase(){for(int i = 0; i < boxes.length; i ++)for(int j = 0; j< boxes[i].length; j ++ ){if( boxes[i][j].isColorBox() ){RussiaBox box = canvas.getBox( y + i, x + j);if(box != null)box.setColor(false);}}}/**显示当前方块(其实只是设置Color属性,在调用repaint方法时才真正显示)*/private void display(){for(int i = 0; i < boxes.length; i ++)for(int j = 0;j< boxes[i].length ; j ++){if(boxes[i][j].isColorBox()){RussiaBox box = canvas.getBox( y + i, x + j);if(box != null)box.setColor( true );}}}}===========================4=================package russia;/** 主游戏类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class RussiaBlocksGame extends JFrame{public final static int PER_LINE_SCORE = 100;//消去一行得分public final static int PER_LEVEL_SCORE = PER_LINE_SCORE*20;//升一级需要的分数public final static int DEFAULT_LEVEL = 5;//默认级别public final static int MAX_LEVEL = 10;//最高级别private int score=0,curLevelScore = 0;//总分和本级得分private GameCanvas canvas;private ControlPanel controlPanel;private RussiaBlock block;private int style = 0;boolean playing = false;private JMenuBar bar;private JMenu gameMenu,controlMenu,windowStyleMenu,informationMenu;private JMenuItem newGameItem,setBlockColorItem,setBgColorItem,turnHardItem,turnEasyItem,exitItem;private JMenuItem playItem,pauseItem,resumeItem,stopItem;private JRadioButtonMenuItem windowsRadioItem,motifRadioItem,metalRadioItem;private JMenuItem authorItem,helpItem;private ButtonGroup buttonGroup;/** 构造函数public RussiaBlocksGame(String title){super(title);setSize(300,400);Dimension scrSize=Toolkit.getDefaultToolkit().getScreenSize();setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);createMenu();Container container=getContentPane();container.setLayout(new BorderLayout());canvas = GameCanvas.getCanvasInstance();controlPanel = new ControlPanel(this);container.add(canvas,BorderLayout.CENTER);container.add(controlPanel,BorderLayout.EAST);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent event){stopGame();System.exit(0);}});addComponentListener(new ComponentAdapter(){public void componentResized(ComponentEvent event){canvas.fanning();}});canvas.fanning();setVisible(true);}/** 判断游戏是否正在进行public boolean isPlaying(){return playing;}/** 开始游戏并设置按钮和菜单项的可用性*/public void playGame(){play();controlPanel.setPlayButtonEnabled(false); playItem.setEnabled(false);}/** 暂停游戏*/public void pauseGame(){if(block != null) block.pauseMove(); controlPanel.setPauseButtonLabel(false); pauseItem.setEnabled(false); resumeItem.setEnabled(true);}/** 从暂停中恢复游戏*/public void resumeGame(){if(block != null) block.resumeMove(); controlPanel.setPauseButtonLabel(true); pauseItem.setEnabled(true); resumeItem.setEnabled(false);}/** 停止游戏*/public void stopGame(){if(block != null) block.stopMove(); playing = false;controlPanel.setPlayButtonEnabled(true); controlPanel.setPauseButtonLabel(true);playItem.setEnabled(true);}/** 得到当前级别*/public int getLevel(){return controlPanel.getLevel();}/** 设置当前级别,并更新控制面板的显示*/public void setLevel(int level){if(level>0&&level<11)controlPanel.setLevel(level);}/** 得到当前总分数*/public int getScore(){if(canvas != null)return score;return 0;}/** 得到本级得分*/public int getCurLevelScore(){if(canvas != null)return curLevelScore;return 0;}/** 更新等级*/public void levelUpdate(){int curLevel = getLevel();if(curLevel < MAX_LEVEL && curLevelScore >= PER_LEVEL_SCORE) {setLevel(curLevel + 1);curLevelScore -= PER_LEVEL_SCORE;}}/** 获得当前得方块*/public RussiaBlock getCurBlock() {return block;}/** 开始游戏*/private void play(){playing=true;Thread thread = new Thread(new Game());thread.start();reset();}/** 重置*/private void reset(){controlPanel.reset();canvas.reset();score = 0;curLevelScore = 0;}/** 宣告游戏结束*/private void reportGameOver(){JOptionPane.showMessageDialog(this,"Game over!");}/** 创建菜单*/private void createMenu(){gameMenu = new JMenu("Game");newGameItem = new JMenuItem("New Game"); setBlockColorItem = new JMenuItem("Set Block Color..."); setBgColorItem = new JMenuItem("Set BackGround Color...");turnHardItem = new JMenuItem("Turn Harder"); turnEasyItem = new JMenuItem("Turn Easily");exitItem = new JMenuItem("Exit");gameMenu.add(newGameItem);gameMenu.add(setBlockColorItem);gameMenu.add(setBgColorItem);gameMenu.add(turnHardItem);gameMenu.add(turnEasyItem);gameMenu.add(exitItem);controlMenu = new JMenu("Control");playItem = new JMenuItem("Play");pauseItem = new JMenuItem("Pause");resumeItem = new JMenuItem("Resume");stopItem = new JMenuItem("Stop");controlMenu.add(playItem);controlMenu.add(pauseItem);controlMenu.add(resumeItem);controlMenu.add(stopItem);windowStyleMenu = new JMenu("WindowStyle"); buttonGroup = new ButtonGroup();windowsRadioItem = new JRadioButtonMenuItem("Windows"); motifRadioItem = new JRadioButtonMenuItem("Motif"); metalRadioItem = new JRadioButtonMenuItem("Mentel",true); windowStyleMenu.add(windowsRadioItem);buttonGroup.add(windowsRadioItem); windowStyleMenu.add(motifRadioItem);buttonGroup.add(motifRadioItem);windowStyleMenu.add(metalRadioItem);buttonGroup.add(metalRadioItem);informationMenu = new JMenu("Information");authorItem = new JMenuItem("Author:Fuliang");helpItem = new JMenuItem("Help");informationMenu.add(authorItem);informationMenu.add(helpItem);bar = new JMenuBar();bar.add(gameMenu);bar.add(controlMenu);bar.add(windowStyleMenu);bar.add(informationMenu);addActionListenerToMenu();setJMenuBar(bar);}/** 添加菜单响应*/private void addActionListenerToMenu(){newGameItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {stopGame();reset();setLevel(DEFAULT_LEVEL);}});setBlockColorItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {Color newBlockColor =JColorChooser.showDialog(RussiaBlocksGame.this,"Set color for block", canvas.getBlockColor());if (newBlockColor != null)canvas.setBlockColor(newBlockColor);}});setBgColorItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {Color newBgColor =JColorChooser.showDialog(RussiaBlocksGame.this,"Set color for block",canvas.getBgColor());if (newBgColor != null)canvas.setBgColor(newBgColor);}});turnHardItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {int curLevel = getLevel();if (curLevel < MAX_LEVEL) setLevel(curLevel + 1);}});turnEasyItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {int curLevel = getLevel();if (curLevel > 1) setLevel(curLevel - 1);}});exitItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {System.exit(0);}});playItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {playGame();}});pauseItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {pauseGame();}});resumeItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {resumeGame();}});stopItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {stopGame();}});windowsRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();}});motifRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();;}});metalRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "javax.swing.plaf.metal.MetalLookAndFeel";setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();}});}/** 设定窗口风格*/private void setWindowStyle(String plaf){try {UIManager.setLookAndFeel(plaf);SwingUtilities.updateComponentTreeUI(this);} catch (Exception e) {e.printStackTrace();}}private class Game implements Runnable{/** (non-Javadoc)* @see ng.Runnable#run()* 游戏线程的run函数*/public void run(){int col=(int)(Math.random()*(canvas.getCols()-3));style=RussiaBlock.STYLES[(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER)][(int)(Math.random()*RussiaBlock.BLOCK_STATUS_NUMBER)];while (playing) {if (block != null) { //第一次循环时,block为空if (block.isAlive()) {try {Thread.sleep(100);} catch (InterruptedException ie) {ie.printStackTrace();}continue;}}checkFullLine();if (isGameOver()) { //检查游戏是否应该结束了playItem.setEnabled(true);pauseItem.setEnabled(true);resumeItem.setEnabled(false);controlPanel.setPlayButtonEnabled(true);controlPanel.setPauseButtonLabel(true);reportGameOver();return;}block = new RussiaBlock(-1, col, getLevel(),style);block.start();col=(int)(Math.random()*(canvas.getCols()-3));style=RussiaBlock.STYLES[(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER)][(int )(Math.random()*RussiaBlock.BLOCK_STATUS_NUMBER)];controlPanel.setBlockStyle(style);}}/** 判断是否能消去整行*/public void checkFullLine(){for (int i = 0; i < canvas.getRows(); i++) {int row = -1;boolean fullLineColorBox = true;for (int j = 0; j < canvas.getCols(); j++) {if (!canvas.getBox(i, j).isColorBox()) {fullLineColorBox = false;break;}}if (fullLineColorBox) {curLevelScore += PER_LINE_SCORE;score += PER_LINE_SCORE;row = i--;canvas.removeLine(row);}}}/** 判断游戏是否结束*/private boolean isGameOver() {for (int i = 0; i < canvas.getCols(); i++) {RussiaBox box = canvas.getBox(0, i);if (box.isColorBox()) return true;}return false;}}public static void main(String[] args){new RussiaBlocksGame("Russia Blocks Game");}}========================5=================== package russia;/**虚拟的单个方格类,控制方格的颜色*/public class RussiaBox implements Cloneable{private boolean isColor;public RussiaBox(boolean isColor){this.isColor = isColor;}/**设置颜色*/public void setColor(boolean isColor) {this.isColor=isColor;}/**返回颜色*/public boolean isColorBox(){return isColor;}/** @see ng.Object#clone()*/public Object clone(){Object o = null;try{o=super.clone();}catch(CloneNotSupportedException e) {e.printStackTrace();}return o;}}。
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;⽣成图形后,实现下落的操作。
俄罗斯方块游戏代码
#include <stdio.h>#include <dos.h>#include <conio.h>#include <graphics.h>#include <stdlib.h>#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endif#define MINBOXSIZE 15 /* 最小方块的尺寸*/#define BGCOLOR 7 /* 背景着色*/#define GX 200#define GY 10#define SJNUM 10000 /* 每当玩家打到一万分等级加一级*/ /* 按键码*/#define VK_LEFT 0x4b00#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_HOME 0x4700#define VK_END 0x4f00#define VK_SPACE 0x3920#define VK_ESC 0x011b#define VK_ENTER 0x1c0d/* 定义俄罗斯方块的方向(我定义他为4种)*/#define F_DONG 0#define F_NAN 1#define F_XI 2#define F_BEI 3#define NEXTCOL 20 /* 要出的下一个方块的纵坐标*/#define NEXTROW 12 /* 要出的下一个方块的横从标*/#define MAXROW 14 /* 游戏屏幕大小*/#define MAXCOL 20#define SCCOL 100 /*游戏屏幕大显示器上的相对位置*/#define SCROW 60int gril[22][16]; /* 游戏屏幕坐标*/int col=1,row=7; /* 当前方块的横纵坐标*/int boxfx=0,boxgs=0; /* 当前寺块的形壮和方向*/int nextboxfx=0,nextboxgs=0,maxcol=22;/*下一个方块的形壮和方向*/ int minboxcolor=6,nextminboxcolor=6;int num=0; /*游戏分*/int dj=0,gamedj[10]={18,16,14,12,10,8,6,4,2,1};/* 游戏等级*//* 以下我用了一个3维数组来纪录方块的最初形状和方向*/int boxstr[7][4][16]={{{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}},{{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}},{{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0},{0,0,1,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,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{1,1,1,0,0,0,1,0,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},{0,0,0,0,1,1,1,1,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},{1,1,0,0,1,1,0,0,0,0,0,0.0,0,0,0}},{{0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{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}}};/* 随机得到当前方块和下一个方块的形状和方向*/void boxrad(){minboxcolor=nextminboxcolor;boxgs=nextboxgs;boxfx=nextboxfx;nextminboxcolor=random(14)+1;if(nextminboxcolor==4||nextminboxcolor==7||nextminboxcolor==8) nextminboxcolor=9;nextboxfx=F_DONG;nextboxgs=random(7);}/*初始化图形模试*/void init(int gdrive,int gmode){int errorcode;initgraph(&gdrive,&gmode,"e:\\tc");errorcode=graphresult();if(errorcode!=grOk){printf("error of: %s",grapherrormsg(errorcode));exit(1);}}/* 在图形模式下的清屏*/void cls(){setfillstyle(SOLID_FILL,0);setcolor(0);bar(0,0,640,480);}/*在图形模式下的高级清屏*/void clscr(int a,int b,int c,int d,int color){setfillstyle(SOLID_FILL,color);setcolor(color);bar(a,b,c,d);}/*最小方块的绘制*/void minbox(int asc,int bsc,int color,int bdcolor){int a=0,b=0;a=SCCOL+asc;b=SCROW+bsc;clscr(a+1,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE,color);if(color!=BGCOLOR){setcolor(bdcolor);line(a+1,b+1,a-1+MINBOXSIZE,b+1);line(a+1,b+1,a+1,b-1+MINBOXSIZE);line(a-1+MINBOXSIZE,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE); line(a+1,b-1+MINBOXSIZE,a-1+MINBOXSIZE,b-1+MINBOXSIZE); }}/*游戏中出现的文字*/void txt(int a,int b,char *txt,int font,int color){setcolor(color);settextstyle(0,0,font);outtextxy(a,b,txt);}/*windows 绘制*/void win(int a,int b,int c,int d,int bgcolor,int bordercolor){clscr(a,b,c,d,bgcolor);setcolor(bordercolor);line(a,b,c,b);line(a,b,a,d);line(a,d,c,d);line(c,b,c,d);}/* 当前方块的绘制*/void funbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+row+a)*MINBOXSIZE,(i+col+b)*MINBOXSIZE,color,bdcolor); }/*下一个方块的绘制*/void nextfunbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[nextboxgs][nextboxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+a)*MINBOXSIZE,(i+b)*MINBOXSIZE,color,bdcolor);}/*时间中断定义*/#define TIMER 0x1cint TimerCounter=0;void interrupt ( *oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*由于游戏的规则,消掉都有最小方块的一行*/void delcol(int a){int i,j;for(i=a;i>1;i--)for(j=1;j<15;j++){minbox(j*MINBOXSIZE,i*MINBOXSIZE,BGCOLOR,BGCOLOR);gril[i][j]=gril[i-1][j];if(gril[i][j]==1)minbox(j*MINBOXSIZE,i*MINBOXSIZE,minboxcolor,0);}/*消掉所有都有最小方块的行*/ void delete(){int i,j,zero,delgx=0;char *nm="00000";for(i=1;i<21;i++){zero=0;for(j=1;j<15;j++)if(gril[j]==0)zero=1;if(zero==0){delcol(i);delgx++;}}num=num+delgx*delgx*10;dj=num/10000;sprintf(nm,"%d",num);clscr(456,173,500,200,4);txt(456,173,"Number:",1,15);txt(456,193,nm,1,15);}/*时间中断结束*/void KillTimer(){disable();setvect(TIMER,oldhandler); enable();}/* 测试当前方块是否可以向下落*/ int downok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i]; for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i+1][row+j])k=0;return(k);/* 测试当前方块是否可以向左行*/int leftok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j-1])k=0;return(k);}/* 测试当前方块是否可以向右行*/int rightok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j+1])k=0;return(k);}/* 测试当前方块是否可以变形*/int upok(){int i,j,k=1,a[4][4];for(i=0;i<4;i++)for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx+1][i];for(i=3;i>=0;i--)for(j=3;j>=0;j--)if(a[j] && gril[col+i][row+j])k=0;return(k);}/*当前方块落下之后,给屏幕坐标作标记*/ void setgril(){int i,j,a[4][4];funbox(0,0,minboxcolor,0);for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j])gril[col+i][row+j]=1;col=1;row=7;}/*游戏结束*/void gameover(){int i,j;for(i=20;i>0;i--)for(j=1;j<15;j++)minbox(j*MINBOXSIZE,i*MINBOXSIZE,2,0);txt(103,203,"Game Over",3,10);}/*按键的设置*/void call_key(int keyx){switch(keyx){case VK_DOWN: { /*下方向键,横坐标加一。
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代码
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俄罗斯方块完整代码
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)。
return 1; }
// 消行的方法 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) {
turnState = tempturnState; } repaint(); }
// 左移的方法 public void left() {
if (blow(x - 1, y, blockType, turnState) == 1) {
x = x - 1; } ; repaint(); }
// 右移的方法 public void right() {
如图
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;
// 方块的形状 第一组代表方块类型有 S、Z、L、J、I、O、T 7 种 第二组 代表旋转几 次 第三四组为 方块矩阵
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 } },
// 生成新方块的方法 public void newblock() {
blockType = (int) (Math.random() * 1000) % 7; turnState = (int) (Math.random() * 1000) % 4; x = 4; y = 0; if (gameover(x, y) == 1) {
} }
// 初始化构造方法 Tetrisblok() {
newblock(); newmap(); drawwall(); Timer timer = new Timer(1000, new TimerListener()); timer.start(); }
// 旋转的方法 public void turn() {
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))) {
// 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 } } };
if (blow(x, y, blockType, turnState) == 0) { return 1;
} return 0; }
// 把当前添加 map public void add(int x, int y, int blockType, int turnState) {
int j = 0; for (int a = 0; a < 4; a++) {
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];
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);
newmap(); drawwall(); sБайду номын сангаасore = 0; JOptionPane.showMessageDialog(null, "GAME OVER"); } }
// 画围墙 public void drawwall() {
for (i = 0; i < 12; i++) { map[i][21] = 2;
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++;
} 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; }
} ; 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) {
public class Tetris extends JFrame { public Tetris() { Tetrisblok a = new Tetrisblok(); addKeyListener(a); add(a); }