小游戏俄罗斯方块代码(JAVA)

合集下载

俄罗斯方块java代码4

俄罗斯方块java代码4

/*** File: ErsBox.java* User: Administrator* Date: Dec 15, 2003* Describe: 俄罗斯方格的Java 实现*/import java.awt.*;/*** 方格类,是组成俄罗斯方块的基本元素,用自己的颜色来表示块的外观* 一个类实现Cloneable接口,就意味着可以合法地使用Object.clone()方法* 域到域地拷贝类对象,否则这种拷贝将会导致异常*/class ErsBox implements Cloneable {private boolean isColor;private Dimension size = new Dimension();/*** 方格类的构造函数* @param isColor 是不是用前景色来为此方格着色,* true前景色,false用背景色*/public ErsBox(boolean isColor) {this.isColor = isColor;}/*** 此方格是不是用前景色表现* @return boolean,true用前景色表现,false用背景色表现*/public boolean isColorBox() {return isColor;}/*** 设置方格的颜色,* @param isColor boolean,true用前景色表现,false用背景色表现*/public void setColor(boolean isColor) {this.isColor = isColor;}/*** 得到此方格的尺寸* @return Dimension,方格的尺寸*/public Dimension getSize() {return size;}/*** 设置方格的尺寸* @param size Dimension,方格的尺寸*/public void setSize(Dimension size) {this.size = size;}/*** 覆盖Object的Object clone(),实现克隆* @return Object,克隆的结果*/public Object clone() {Object cloned = null;try {cloned = super.clone();} catch (Exception ex) {ex.printStackTrace();}return cloned;}}。

俄罗斯方块JAVA小程序

俄罗斯方块JAVA小程序
3 个不同的类 SingleTetris.java,SuperBrick.java,Tetris.java。分别对应单一俄罗斯方块 游戏类,方块组数据类和俄罗斯方块控制窗口。用 Netbeans 调试运行即可。
以下是源代码:
/*程序: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;//下一个砖块组储存数组

小游戏俄罗斯方块代码JAVA

小游戏俄罗斯方块代码JAVA

东西绝对不多说,直接看!看了拷贝就懂了!!,直接可以拷贝下面的东西,然后记得把那个BLOCK的名字改成你自己的类名,这个很关键哦,不然是错的可别怪我,呵呵~~import .*;importimport .*;import .*;import .*;import .*;import .*;public class Block extends JPanel implementsActionListener,KeyListenerddActionListener(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);(320,15,30,20);(360,15,160,20);;(320,45,30,20);(360,45,160,20);;but[1].setEnabled(false);but[4].setEnabled(false);(320,75,30,20);(360,75,160,20);;(360,360,160,25);(this);(this);(this);(this);(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if() == but[0])etEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);();}if() == but[1]||() == mi0)etEnabled(true); but[1].setEnabled(false);but[4].setEnabled(false);}if() == but[2])//降低级数{("降低级数!");speedMark--;if(speedMark <= 1){speedMark = 1;("已经是最低级数!");}(speedMark + "");}if() == but[3])//提高级数{("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;("已经是最高级数!");}(speedMark + "");}if() == but[4])//游戏暂停{(noStop);(but[4]);("游戏暂停!");();}if() == noStop)//取消暂停{(noStop);(but[4]);("继续游戏!");();}if() == but[5]||() == mi1)//退出游戏{();if() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/");//得到路径byte a[] = new byte[()];(a);();String str = new String(a);(str);}catch(Exception g){}(false);(dlg_1_text);();(false);(200, 120);(400, 240);();}}public void rand_block()//随机产生砖块{int num;num = (int)() * 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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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;("游戏进行中!");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() == &&startSign == 1)//处理下键{();}if() == &&startSign == 1)//处理左键();}if() == &&startSign == 1)//处理右键{();}if() == &&startSign == 1)//处理上键转换{(blockNumber);}if(startSign == 0){("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){;(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){;(30*j,30*(i-4),30,30,true);}if(game_body[i][j] == 2){;(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;}("向左移动!");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;}("向右移动!");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; }("游戏进行中!");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){("游戏结束!");changeColor();repaint();startSign = 0;();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;(gameScore+"");("恭喜得分!");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){= myBlock;}public void run(){while == 1){try{sleep( + 1)*100);();}catch(InterruptedException e){} }}}。

java俄罗斯方块小游戏代码

java俄罗斯方块小游戏代码

java俄罗斯方块小游戏代码package keshe;import java.awt.Color; //颜色import java.awt.Font; //字体import java.awt.Graphics; //绘图import java.awt.event.ActionEvent; //动作import java.awt.event.ActionListener; //事件处理importjava.awt.event.KeyAdapter; //接受键盘信息import java.awt.event.KeyEvent; //键盘信息处理import javax.swing.JFrame; //窗体import javax.swing.JMenu; //菜单import javax.swing.JMenuBar; //菜单条import javax.swing.JMenuItem; //菜单项import javax.swing.JOptionPane; //消息提示框import javax.swing.JPanel; //中间容器import javax.swing.Timer; //时间public class ddddddd extends JFrame{public static void main(String[] args) {ddddddd te = new ddddddd();te.setVisible(true);}private TetrisPanel tp;JMenuItem itemPause;JMenuItem itemContinue;JMenuItem itemgnd;JMenuItem itemdnd;public ddddddd() {this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setLocation(500, 200);this.setSize(220, 275);this.setResizable(false);tp = new TetrisPanel();this.getContentPane().add(tp);//添加菜单JMenuBar menubar = new JMenuBar();this.setJMenuBar(menubar);JMenu menuGame = new JMenu("游戏");menubar.add(menuGame);JMenuItem itemNew = new JMenuItem("新游戏"); itemNew.setActionCommand("new");itemgnd = new JMenuItem("提高难度");itemgnd.setActionCommand("gnd"); itemdnd = new JMenuItem("降低难度");itemdnd.setActionCommand("dnd");itemPause = new JMenuItem("暂停");itemPause.setActionCommand("pause");itemContinue = new JMenuItem("继续");itemContinue.setActionCommand("continue");itemContinue.setEnabled(false);itemdnd.setEnabled(false);menuGame.add(itemNew);menuGame.add(itemPause);menuGame.add(itemContinue);menuGame.add(itemgnd);menuGame.add(itemdnd);MenuListener menuListener = new MenuListener();itemNew.addActionListener(menuListener);itemPause.addActionListener(menuListener);itemContinue.addActionListener(menuListener);itemgnd.addActionListener(menuListener);itemdnd.addActionListener(menuListener);//让整个JFrame添加键盘监听this.addKeyListener( tp.listener );}class MenuListener implements ActionListener{ public void actionPerformed(ActionEvent e) { //玩新游戏if(e.getActionCommand().equals("new")){tp.newGame();}if(e.getActionCommand().equals("pause")){ timer.stop();itemContinue.setEnabled(true);itemPause.setEnabled(false);}if(e.getActionCommand().equals("continue")){ timer.restart(); itemContinue.setEnabled(false);itemPause.setEnabled(true);}if(tp.nandu==1){itemdnd.setEnabled(false);}else itemdnd.setEnabled(true);if(tp.nandu==9)itemgnd.setEnabled(false);else itemgnd.setEnabled(true);if(e.getActionCommand().equals("gnd")){ tp.delay/=1.3;tp.nandu+=1;timer.setDelay(tp.delay);}if(e.getActionCommand().equals("dnd")){ tp.delay*=1.3;tp.nandu-=1;timer.setDelay(tp.delay);}}}private Timer timer; class TetrisPanel extends JPanel{// 方块的形状:// 第一维代表方块类型(包括7种:S、Z、L、J、I、O、T)// 第二维代表旋转次数// 第三四维代表方块矩阵// shapes[type][turnState][i] i--> block[i/4][i%4]int shapes[][][] = new int[][][] {// I (※把版本1中的横条从第1行换到第2行){ { 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, 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 } }, // 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 } } };private int blockType;//方块类型private int turnState;//旋转状态private int dierkuai;private int dierState;private int x;//方块的位置x--列的位置--列号private int y;//方块的位置y--行的位置--行号private int map[][]=new int[13][23];//地图:12列22行。

俄罗斯方块(Java实现)

俄罗斯方块(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俄罗斯方块程序代码

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("拒绝盗版游戏。

俄罗斯方块代码

俄罗斯方块代码

package Eluosifangkuai;import java.awt.Color;import java.awt.FlowLayout;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;import javax.swing.*;public class Game extends JPanel implements ActionListener,KeyListener{ /****/private static final long serialVersionUID = 11L;int fenshu=0;int speed=0;int temp;int[][]map=new int[12][20];public boolean start=false;GameBlock[] block=new GameBlock[4];GameBlock[] block2=new GameBlock[4];JButton newgame=new JButton("开始游戏");JButton endgame=new JButton("退出游戏");JDialog dialog=new JDialog();JLabel label=new JLabel();JButton button=new JButton("ok");Random r=new Random();Thread t;public Game() {for (int i = 0; i <block.length; i++) {block[i]=new GameBlock();}for (int i = 0; i <block2.length; i++) {block2[i]=new GameBlock();}for (int i = 0; i < 12; i++) {for (int j = 0; j < 20; j++) {map[i][j]=0;}}setLayout(new FlowLayout(FlowLayout.RIGHT));add(newgame);add(endgame);newgame.addActionListener(this);endgame.addActionListener(this);addKeyListener(this);dialog.setLayout(new GridLayout(2,1));dialog.add(label);dialog.add(button);button.addActionListener(this);dialog.setSize(200,100);dialog.setLocation(200,200);dialog.setVisible(false);}public boolean newBlock(){switch(temp){//生成横着的横杠case 0:block[0].x=1;block[0].y=0;block[1].x=2;block[1].y=0;block[2].x=3;block[2].y=0;block[3].x=4;block[3].y=0;break;//生成田字形case 1:block[0].x=2;block[0].y=0;block[1].x=3;block[1].y=0;block[2].x=2;block[2].y=1;block[3].x=3;block[3].y=1;break;//生成田字形case 2:block[0].x=2;block[0].y=0;block[1].x=2;block[1].y=1;block[2].x=2;block[2].y=2;block[3].x=3;block[3].y=2;break;//生成田字形case 3:block[0].x=3;block[0].y=0;block[1].x=3;block[1].y=1;block[2].x=3;block[2].y=2;block[3].x=2;block[3].y=2;break;case 4:block[0].x=3;block[0].y=0;block[1].x=2;block[1].y=1;block[2].x=3;block[2].y=1;block[3].x=4;block[3].y=1;break;case 5:block[0].x=2;block[0].y=0;block[1].x=3;block[1].y=0;block[2].x=3;block[2].y=1;block[3].x=4;block[3].y=1;break;case 6:block[0].x=2;block[0].y=1;block[1].x=3;block[1].y=1;block[2].x=3;block[2].y=0;block[3].x=4;block[3].y=0;break;}for (int i = 0; i < 4; i++) {if(maxYes(block[i].x, block[i].y)){return false;}}return true;}public void paintComponent(Graphics g){ super.paintComponent(g);g.drawString("俄罗斯方块游戏", 90,25);g.drawRect(30, 30, 243, 403);g.drawString("分数:"+fenshu, 290, 60);g.drawLine(290, 63, 400, 63);g.drawString("速度:"+speed, 290, 90);g.drawLine(290, 93, 400, 93);g.drawString("下一个方块:", 290, 130);if(start){g.setColor(new Color(255,0,0));for(int i=0;i<4;i++){g.fillRect(33+block[i].x*20, 33+block[i].y*20, 20, 20);}for (int i = 0; i < 12; i++) {for (int j = 0; j < 20; j++) {if(map[i][j]==1){g.fillRect(33+i*20, 33+j*20, 20, 20);}}}g.setColor(new Color(0,0,255));for(int i1=0;i1<4;i1++){g.fillRect(290+block2[i1].x*20, 170+block2[i1].y*20, 20, 20);}}}public void nextBlock(){switch(temp){//生成横着的横杠case 0:block2[0].x=1;block2[0].y=0;block2[1].x=2;block2[1].y=0;block2[2].x=3;block2[2].y=0;block2[3].x=4;block2[3].y=0;break;//生成田字形case 1:block2[0].x=2;block2[0].y=0;block2[1].x=3;block2[1].y=0;block2[2].x=2;block2[2].y=1;block2[3].x=3;block2[3].y=1;break;//生成田字形case 2:block2[0].x=2;block2[0].y=0;block2[1].x=2;block2[1].y=1;block2[2].x=2;block2[2].y=2;block2[3].x=3;block2[3].y=2;break;//生成田字形case 3:block2[0].x=3;block2[0].y=0;block2[1].x=3;block2[1].y=1;block2[2].x=3;block2[2].y=2;block2[3].x=2;block2[3].y=2;break;case 4:block2[0].x=3;block2[0].y=0;block2[1].x=2;block2[1].y=1;block2[2].x=3;block2[2].y=1;block2[3].x=4;block2[3].y=1;break;case 5:block2[0].x=2;block2[0].y=0;block2[1].x=3;block2[1].y=0;block2[2].x=3;block2[2].y=1;block2[3].x=4;block2[3].y=1;break;case 6:block2[0].x=2;block2[0].y=1;block2[1].x=3;block2[1].y=1;block2[2].x=3;block2[2].y=0;block2[3].x=4;block2[3].y=0;break;}}public void actionPerformed(ActionEvent e) {if(e.getSource()==newgame){if(e.getActionCommand().equals("开始游戏")){newgame.setText("重新开始");requestFocus(true);start=true;temp=r.nextInt(7);if(!newBlock()){t=new MyTimer();t.start();temp=r.nextInt(7);nextBlock();repaint();}else{//这里是游戏失败的情况return;}}else{start=false;fenshu=0;speed=0;for (int i = 0; i <12; i++) {for (int j = 0; j < 20; j++) {map[i][j]=0;}}newgame.setText("开始游戏");}}if(e.getSource()==endgame){int val=JOptionPane.showConfirmDialog(this, "确认离开?","离开系统",JOptionPane.YES_NO_OPTION);if(val==JOptionPane.YES_OPTION){System.exit(0);//离开系统}}if(e.getSource()==button){fenshu=0;speed=0;start=false;for (int i = 0; i <12; i++) {for (int j = 0; j < 20; j++) {map[i][j]=0;}}newgame.setText("开始游戏");dialog.setVisible(false);repaint();}}public void moved(int x,int y){if(minYes(x, y)){for (int i = 0; i < 4; i++) {block[i].x+=x;block[i].y+=y;}}repaint();}private void up(){//获取x,y的中心位置int cx;int cy;GameBlock[] b=new GameBlock[4];for (int i = 0; i < 4; i++) {b[i]=new GameBlock();b[i].x=block[i].x;b[i].y=block[i].y;}cx=(b[0].x+b[1].x+b[2].x+b[3].x)/4;cy=(b[0].y+b[1].y+b[2].y+b[3].y)/4;//旋转算法for (int i = 0; i < b.length; i++) {b[i].x=cx+cy-block[i].y;b[i].y=cy-cx+block[i].x;}for (int i = 0; i < block.length; i++) { if(!maxYes(b[i].x, b[i].y)){return;}}for (int i = 0; i < block.length; i++) { block[i].x=b[i].x;block[i].y=b[i].y;}repaint();}public int deleteLine(){int line=0;for (int i = 0; i <20; i++) {int j;for ( j = 0; j < 12; j++) {if(map[j][i]==0)break;}if(j==12){line++;if(i!=0){for (int j2 = i-1; j2 >0; j2--) {for (int k = 0; k <12; k++) {map[k][j2+1]=map[k][j2];}}for (int j2 = 0; j2 < 12; j2++) {map[0][j2]=0;}}}}//repaint();return line;}private void down() {//判断是否在边界内if(minYes(0, 1)){for (int i = 0; i < 4; i++) {block[i].y+=1;}repaint();}else{//t.stop();//不能下落后记录该方块for (int i = 0; i < 4; i++) {map[block[i].x][block[i].y]=1;}int n;if((n=deleteLine())!=0){fenshu+=5*n;if(fenshu%100==0){speed++;}}//生成新的块if(!newBlock()){temp=r.nextInt(7);nextBlock();//t.start();}else{//这里是游戏失败的情况//t.stop();label.setText("游戏结束,你的分数是:"+fenshu);dialog.setVisible(true);}repaint();}}public boolean minYes(int x,int y){for (int i = 0; i < 4; i++) {if(!maxYes(block[i].x+x,block[i].y+y)){return false;}}return true;}public boolean maxYes(int x,int y){if(x<0||x>=12||y<0||y>=20){return false;}//块与块之间的判定,即不会重叠if(map[x][y]==1){return false;}return true;}public void keyPressed(KeyEvent e) {if(start){switch(e.getKeyCode()){case KeyEvent.VK_DOWN:down();break;case KeyEvent.VK_UP://moved(0,-1);up();break;case KeyEvent.VK_LEFT:moved(-1,0);break;case KeyEvent.VK_RIGHT:moved(1,0);break;}}}public void keyReleased(KeyEvent arg0) {}public void keyTyped(KeyEvent arg0) {}class MyTimer extends Thread{public void run() {while(start){try {sleep((10-speed)*100);down();} catch (Exception e) {}}}}}。

Java编写的俄罗斯方块(小游戏)

Java编写的俄罗斯方块(小游戏)
short i,j;
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代码。

首先,需要说明的是,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实现俄罗斯⽅块⼩游戏本⽂实例为⼤家分享了java实现俄罗斯⽅块的具体代码,供⼤家参考,具体内容如下使⽤⼀个⼆维数组保存游戏的地图:// 游戏地图格⼦,每个格⼦保存⼀个⽅块,数组纪录⽅块的状态private State map[][] = new State[rows][columns];游戏前先将所有地图中的格⼦初始化为空:/* 初始化所有的⽅块为空 */for (int i = 0; i < map.length; i++) {for (int j = 0; j < map[i].length; j++) {map[i][j] = State.EMPTY;}}玩游戏过程中,我们能够看到界⾯上的⽅块,那么就得将地图中所有的⽅块绘制出来,当然,除了需要绘制⽅块外,游戏积分和游戏结束的字符串在必要的时候也需要绘制:/*** 绘制窗体内容,包括游戏⽅块,游戏积分或结束字符串*/@Overridepublic void paint(Graphics g) {super.paint(g);for (int i = 0; i < rows; i++) {for (int j = 0; j < columns; j++) {if (map[i][j] == State.ACTIVE) { // 绘制活动块g.setColor(activeColor);g.fillRoundRect(j * BLOCK_SIZE, i * BLOCK_SIZE + 25,BLOCK_SIZE - 1, BLOCK_SIZE - 1, BLOCK_SIZE / 5,BLOCK_SIZE / 5);} else if (map[i][j] == State.STOPED) { // 绘制静⽌块g.setColor(stopedColor);g.fillRoundRect(j * BLOCK_SIZE, i * BLOCK_SIZE + 25,BLOCK_SIZE - 1, BLOCK_SIZE - 1, BLOCK_SIZE / 5,BLOCK_SIZE / 5);}}}/* 打印得分 */g.setColor(scoreColor);g.setFont(new Font("Times New Roman", Font.BOLD, 30));g.drawString("SCORE : " + totalScore, 5, 70);// 游戏结束,打印结束字符串if (!isGoingOn) {g.setColor(Color.RED);g.setFont(new Font("Times New Roman", Font.BOLD, 40));g.drawString("GAME OVER !", this.getWidth() / 2 - 140,this.getHeight() / 2);}}通过随机数的⽅式产⽣⽅块所组成的⼏种图形,⼀般七种图形:条形、⽥形、正7形、反7形、T形、Z形和反Z形,如⽣成条形:map[0][randPos] = map[0][randPos - 1] = map[0][randPos + 1]= map[0][randPos + 2] = State.ACTIVE;⽣成图形后,实现下落的操作。

JAVA课程设计俄罗斯方块(含代码)

JAVA课程设计俄罗斯方块(含代码)

Java程序课程设计任务书俄罗斯方块游戏的开发1、主要内容:俄罗斯方块游戏具有广泛的游戏人群,因为它比较简单有趣,无论老少都比较适合。

俄罗斯方块游戏的设计对于每一个Java语言设计者进行语言提高和进阶都是一个很好的锻炼机会。

俄罗斯方块游戏的设计工作是非常复杂和重要的,它涉及面逛,牵涉面多,如果不好好考虑和设计,将难以成功开发出这个游戏。

在这个游戏的设计中,将牵涉到图形界面的显示与更新,数据的收集与更新并且在这个游戏的开发中还会应用类的继承机制以及一些设计模式。

因此,如何设计和开发好这个俄罗斯方块游戏,对于提高Java开发水平和系统的设计能力有极大的帮助。

在设计开发过程中,开发者需要处理好各个类之间的集成关系,还要处理各个类的相应的封装,并且还要协调好各个模块之间的逻辑依赖关系和数据通信关系。

2、具体要求(包括技术要求等):系统的功能设计要求:本课程设计将实现以下几种功能。

1.游戏界面主框架游戏界面主框架主要包括游戏图形区域界面,游戏速度的选择更新界面,,游戏分数的显示更新界面,下一个图形方块的显示更新区域,开始游戏按钮,重新开始游戏按钮以及退出游戏按钮游戏界面主框架的主要结构如下图所示。

2.游戏图形区域界面的显示更新功能游戏图形区域界面主要是一个图形显示更新区域,主要包括游戏方块显示更新,整行方块的删除和更新,进行中和游戏结束时的分数更新和游戏图形区域界面的清除。

在这个游戏图形区域界面中,主要是一个表格,根据相应格子的设置标志来显示相应的图形图片,这样就实现了俄罗斯方块的实时显示。

3.游戏方块的设计在俄罗斯方块游戏中,具体的游戏方块图形的设计是比较重要的一个方面。

因为俄罗斯方块游戏中主要的动作就是控制游戏方块的移动和翻转,以便于组成一行行连续的方块从而增加游的分数。

由于主要的游戏动作都集中在这个游戏方块上,因此游戏方块的设计就显得格外重要了。

为了增加程序的可扩展性,这里设计一个游戏方块的基类,各个具体的游戏方块都从这个基类开始继承。

java俄罗斯方块代码

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代码

俄罗斯方块java代码

import javax.swing.*;import javax.swing.Timer;import java.awt.*;import java.awt.event.*;import java.util.*;/**Title: 俄罗斯方块*Description: 俄罗斯方块*Copyright: 俄罗斯方块*Company:俄罗斯方块**@author Zhu Yong*@version 1.0*/public class SquaresGame{public static void main(String[]args){ new SquaresFrame().play();}}class SquaresFrame extends JFrame { public final static int WIDTH= 500;public final static int HEIGHT= 600;/***游戏区*/private BoxPanel boxPanel;/***暂停标记*/private boolean isPause= true;/***默认构造函数*/public SquaresFrame(){/***记分面板boxPanel =new BoxPanel(infoPanel);JMenuBar bar = new JMenuBar();JMenu menu = new JMenu("菜单");JMenuItem begin = new JMenuItem("新游戏");final JMenuItem pause = new JMenuItem("暂停"); JMenuItem stop = new JMenuItem("结束");setJMenuBar(bar);bar.add(menu);menu.add(begin);menu.add(pause);menu.add(stop);stop.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){System.exit(0);}});pause.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){if (isPause){boxPanel.supend(false);isPause = ! isPause;pause.setText("恢复");}else {boxPanel.supend(true);isPause = ! isPause;pause.setText("暂停");}}});boxPanel.newGame(); }});boxPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cre ateEtchedBorder(),"Box"));infoPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cr eateEtchedBorder(),"Info"));add(boxPanel,BorderLayout.CENTER);add(infoPanel,BorderLayout.EAST);setTitle("Squares Game");setSize(WIDTH,HEIGHT);//不可改变框架大小setResizable(false);//定位显示到屏幕中间setLocation(((int)Toolkit.getDefaultToolkit().getScreenSize().getWidt h()-WIDTH)/2,((int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()-HEIGHT) /2);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);}public void play() {boxPanel.newGame();}}/****@author Zhu Yong*游戏区面板*/class BoxPanel extends JPanel {/***定义行*/public final static int ROWS= 20;/**public final static int COLS= 10;public final static Color DISPLAY= new Color(128,128,255);/***没有方块时显示的颜色*/public final static Color HIDE= new Color(238,238,238);/***记分面板上显示的下一个方块的颜色*/public final static Color NEXTDISPLAY= Color.ORANGE;/***是否显示网络*/public final static boolean PAINTGRID= false;/***用4个按钮表示一个方块*/private JButton[][]squares= new JButton[ROWS][COLS];/***定义对前位置是否有方块.用颜色区别.*/private int[][]stateTable= new int[ROWS][COLS];private InfoPanel scorePanel;private ABox currentBox;private ABox nextBox;/***各方块颜色数组.其中0号颜色为无方块时颜色.共7种方块 .最后一个消行时颜色 */private static Color[]boxColor= new Color[]{newColor(238,238,238),new Color(128,128,255),new Color(189,73,23), new Color(154,105,22),new Color(101,124,52),newColor(49,100,128),new Color(84,57,119),new Color(111,54,102), new Color(126,50,57),Color.RED};/***定时器,负责方块自动下移*/private Timer timer;/**private int level;/***初时化时的延时*/private final static int INITDELAY= 940;/***每一级别延时减少的步进值*/private final static int INC= 90;public BoxPanel(InfoPanel panel){setLayout(new GridLayout(ROWS,COLS,1,1));//可能获取焦点,才能接受键盘事件setFocusable(true);//setCursor(new Cursor(1));/***初时化,生成JButton,设置颜色.JButton数组按照先第一行再第二行的顺序添加.下标为[行][列]和[x][y]正好相反.*/for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++) {JButton square= new JButton("");square.setEnabled(false);square.setBorderPainted(PAINTGRID);squares[i][j] = square;stateTable[i][j] = 0;add(square);}scorePanel = panel;timer =new Timer(INITDELAY,new autoDownHandler());//注册键盘事件addKeyListener(new KeyAdapter(){ publicvoid keyPressed(KeyEvent e) {int key = e.getKeyCode();//System.out.println(bt.getX()+":"+bt.getY());if (key == KeyEvent.VK_DOWN) dropdown();else if (key == KeyEvent.VK_UP) rotate();else if (key == KeyEvent.VK_RIGHT) right();else if (key == KeyEvent.VK_LEFT) left();/***重新所有方块. 即重新改变所有JButton背景色*/private void showBox(){for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)squares[i][j].setBackground(boxColor[stateTable[i][j]]);}/***只重新显示当前方块*/private void showCurrentBox(){point[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col =location[i].getX();squares[row][col].setBackground(boxColor[stateTable[row][col]]);}}/***消行记分*/private void clearBox(){int clearLines=0;for(int i=ROWS-1;i>=0;i--)for(int j=0;j<COLS;j++) {if (stateTable[i][j]==0) break;if (j==(COLS-1)) {removeLine(i);clearLines++;i++; }}if (clearLines>0) {scorePanel.winScore(clearLines);upgrade();}}/***消行,重置属性表.下移*@param line*/for(int j=0;j<COLS;j++){stateTable[line][j] = 8;//System.out.println(squares[line][j].getBackground());squares[line][j].setBackground(Color.RED);//System.out.println(squares[line][j].getBackground());//validate();}showBox();for (int i=line;i>=0;i--)for(int j=0;j<COLS;j++)if (i!=0)stateTable[i][j] = stateTable[i-1][j];elsestateTable[i][j] = 0;showBox();timer.start();}/***检查把方块移动到(x,y)时是否合法 .*@param x*@param y*@return*/public boolean checkAction(int x,int y) {//先移除当前方块,再判断.当前方块和下一位置的方块有共用的位置.removeCurrentBox();boolean ret = true;point[] list = currentBox.getShape().getList();int xx = 0;int yy = 0;for (int i=0;i<4;i++) {if (i!=0) {xx = list[i].getX()+x;yy = list[i].getY()+y; }else {xx = x; yy = y; }//System.out.println("check"+i+"->"+xx+":"+yy);if ( xx>=COLS|| xx<0) {ret = false;break; } if ( yy>=ROWS|| yy<0 ) {ret = false; break;}//System.out.println("after break check"+i+"->"+xx+":"+yy); if (stateTable[yy][xx]!=0){ret = false; break;}}addCurrentBox();return ret;}*左移*/public void left(){if(checkAction(currentBox.getHead().getX()-1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()-1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***右移*/public void right(){if(checkAction(currentBox.getHead().getX()+1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()+1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***下移*@return*/public boolean down(){int choose=0;if(checkAction(currentBox.getHead().getX(),currentBox.getHead().getY()+1)) {removeCurrentBox();showCurrentBox();etY()+1);addCurrentBox();showCurrentBox();//showBox();return true;}else {clearBox();currentBox = nextBox.setDefault();nextBox = BoxFactory.getBox().setDefault();scorePanel.setNext(nextBox);//showBox();//检查是否游戏结束if (checkGameOver()){supend(false);choose = JOptionPane.showConfirmDialog(this, "游戏结束\n你的积分为"+scorePanel.getScore()+"\n要开始新游戏吗?","GameOver",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);if (choose == JOptionPane.YES_OPTION) newGame();}addCurrentBox();showCurrentBox();//showBox();return false;}}/***丢下.*/public void dropdown() {while (down()) {};}/***判断是否结束*@returnpoint[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col = location[i].getX();if (stateTable[row][col]!=0) return true;}return false;}/***变形*/public void rotate(){if (checkRotate()){removeCurrentBox();showCurrentBox();currentBox.rotate();addCurrentBox();showCurrentBox();//showBox();}}/***检查变形是否合法*@return*/private boolean checkRotate(){removeCurrentBox();int oldheadx =currentBox.getHead().getX(); intoldheady =currentBox.getHead().getY();//System.out.println("oldhead:"+oldheadx+","+oldheady);boolean ret = true;point[] shape = currentBox.getNextShape().getList();int x=0,y=0,newheadx = 0,newheady=0; for(inti=0;i<4;i++) {if (i!=0){x = newheadx + shape[i].getX();y = newheady + shape[i].getY();}else {newheadx = oldheadx + shape[i].getX();newheady = oldheady + shape[i].getY();x = newheadx;y = newheady;//System.out.println("newhead:"+newheadx+":"+newheady);if ( x>=COLS|| x<0) {ret = false;break; } if ( y>=ROWS|| y<0 ){ret = false;break;}//System.out.println("after break checkrotate "+i+"->"+x+":"+y); if (stateTable[y][x]!=0) {ret = false;break;}}addCurrentBox();return ret;}/***移除当前方块.设置颜色为无色.主要用于移动,变形时.清除当前位置方块.显示下一位置方块.*/private void removeCurrentBox(){//System.out.println("removeCurrentBox:"+Thread.currentThread().getNa me());for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = 0;}}/***添加当前方块到属性表.*/private void addCurrentBox(){for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = currentBox.getId();}}/***暂停游戏*false时暂停*@param resume*/public void supend(boolean resume){if (! resume) {timer.stop();else {timer.start();setFocusable(true);this.requestFocus();}}/***设置游戏级别.即改变定时器延时.*@param level*/public void setLevel(int level) {this.level= level;scorePanel.setLevel(level);timer.setDelay(INITDELAY-INC*level);}/***自动下移监听器*@author Administrator**/private class autoDownHandler implements ActionListener { public void actionPerformed(ActionEvent e){ down();}}/***根据积分自动设置级别*/public void upgrade(){int score =scorePanel.getScore();if (score > 3000 &&level<2) setLevel(2); else if (score > 6000 &&level<3) setLevel(3); else if(score > 10000 &&level<4) setLevel(4); else if(score > 15000 &&level<5) setLevel(5); else if(score > 21000 &&level<6) setLevel(6); else if(score > 28000 &&level<7) setLevel(7); else if(score > 35000 &&level<8) setLevel(8); else if(score > 43000 &&level<9) setLevel(9); else if(score > 51000 &&level<10) setLevel(10);}/***重置,开始新游戏.for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)stateTable[i][j] = 0;showBox();setLevel(1);scorePanel.clean();currentBox = BoxFactory.getBox();nextBox = BoxFactory.getBox();scorePanel.setNext(nextBox);setFocusable(true);requestFocus();addCurrentBox();showBox();timer.start();}}/***记分面板*@author Administrator**/class InfoPanel extends JPanel{private JLabel scoreLabel;private JLabel lineLabel;private JLabel levelLabel;private JPanel nextPanel;/***下一个方块*/private JButton[][]nextBox;public InfoPanel(){setLayout(new BorderLayout());Box vbox = Box.createVerticalBox();add(vbox,BorderLayout.CENTER);vbox.add(Box.createRigidArea(new Dimension(12,50)));Box vbox1 = Box.createVerticalBox();vbox.add(vbox1);scoreLabel =new JLabel("0");lineLabel =new JLabel("0");levelLabel =new JLabel("0");nextPanel.setLayout(new GridLayout(4,4,1,1));for(int i=0;i<4;i++)for(int j=0;j<4;j++){JButton bt = new JButton("");bt.setEnabled(false);bt.setBorderPainted(BoxPanel.PAINTGRID);nextPanel.add(bt);nextBox[j][i] = bt;}vbox1.add(new JLabel("Next :"));vbox1.add(nextPanel);vbox1.add(Box.createVerticalStrut(90));vbox1.add(new JLabel("得分:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(scoreLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel("行数:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(lineLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel(" Level :"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(levelLabel);vbox1.add(Box.createVerticalStrut(80));}/***记分.显示在面板上*@param lines*/public void winScore(int lines){int score = 0;lineLabel.setText(""+(Integer.parseInt(lineLabel.getText())+lines));if (lines==1) score = 100;else if (lines ==2) score = 300;else if (lines ==3) score = 500;else if (lines ==4) score = 1000;scoreLabel.setText(""+(Integer.parseInt(scoreLabel.getText())+score)) ;}/***@param next*/public void setNext(ABox next) {for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);int headx = 2; int heady = 0;//设置方块位置if (next.getId() == 1) {headx = 2;heady=0;}else if (next.getId() == 2) {headx = 1;heady = 1;}else if (next.getId() == 3) {headx = 2;heady = 1;}else if (next.getId() == 4) {headx = 1;heady = 1;}else if (next.getId() == 5) {headx = 2;heady = 1;}else if (next.getId() == 6) {headx = 1;heady = 1;}else if (next.getId() == 7) {headx = 1;heady = 1;}point[] shape = next.getShape(0).getList();nextBox[headx][heady].setBackground(BoxPanel.NEXTDISPLAY);nextBox[headx+shape[1].getX()][heady+shape[1].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[2].getX()][heady+shape[2].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[3].getX()][heady+shape[3].getY()].setBackground(B oxPanel.NEXTDISPLAY);}/***设置显示级别*@param level*/public void setLevel(int level) {levelLabel.setText(""+level);}/***获取当前积分*@return*/public int getScore(){return Integer.parseInt(scoreLabel.getText());}*重置*/public void clean(){scoreLabel.setText(""+0);setLevel(1);for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);}}/***方块类*@author Administrator**/class ABox {public final static int ROWS= 20;public final static int COLS= 10;private int id;/***用于存放方块所有样子坐标.*/private ArrayList<BoxShape>shapeTable;private String name;private int currentShapeId;/***当前方块位置.注意这里是坐标(x,y)和squares,stateTable数组的行列顺序正好相反.**/private point[]location;/***方块起始位置.*/private point head= new point(0,COLS/2);public ABox(String name,int id) {= name;this.id= id;shapeTable =new ArrayList<BoxShape>();location =new point[4];}/**public void rotate(){currentShapeId=(currentShapeId+1)>=shapeTable.size()?0:(currentShapeI d+1);point shapehead = shapeTable.get(currentShapeId).getList()[0];setHead(getHead().getX()+shapehead.getX(),getHead().getY()+shapehead. getY());}/***添加方块坐标集*@param shape*/public void addShape(BoxShape shape){shapeTable.add(shape);}/***重设方块位置.定义新的头结点.根据坐标集计算下其它子方块位置.*@param x新位置头结点坐标x*@param y*/public void setHead(int x,int y) {head.setxy(x, y);point[] shapePoint = getShape().getList();location[0] = head;location[1] = head.add(shapePoint[1]);location[2] = head.add(shapePoint[2]);location[3] = head.add(shapePoint[3]);}/***获取位置数组*@return*/public point[] getLocation(){return location;}/***获取头结点*@return*/public point getHead(){/***获取当前坐标集*@return*/public BoxShape getShape(){// get current shapereturn shapeTable.get(currentShapeId);}/***获取下一个坐标集*/public BoxShape getNextShape() {//int index = currentShapeId+1;//if (index>=shapeTable.size()) index = 0;returnshapeTable.get(currentShapeId+1>=shapeTable.size()?0:currentShapeId+1);}/***重置当前方块 .因为游戏中一直在重用方块对象.*@return*/public ABox setDefault(){setHead(4,0);currentShapeId = 0;return this;}/***获取对应坐标集*@param index*@return*/public BoxShape getShape(int index){ return shapeTable.get(index);}/***用于调试*/public String toString(){return ""+name+" "+getHead();}public int getId(){}/***产生方块*@author Administrator**/class BoxFactory {/***ArrayLIst中存放每个方块的一个对象.随机获取.*/private static ArrayList<ABox>aboxes= new ArrayList<ABox>();/***产生方块对象.*/static {/**其中包含4个点.都是相对坐标.第一个坐标是相对变形前根结点坐标的变化量,其它3坐标是相对当前根结点的变化量.对任一方块,可让其处一个3*3或4*4的方阵中,变化时不应脱离此方块,然后以此来计算根结点相对变化值.*****/ABox abox = new ABox("changtiao",1);abox.addShape(new BoxShape(2,-2,0,1,0,2,0,3));abox.addShape(new BoxShape(-2,2,1,0,2,0,3,0));aboxes.add(abox);/** ** **/abox = new ABox("fangkuai",2);abox.addShape(new BoxShape(0,0,1,0,0,1,1,1));aboxes.add(abox);** ***/abox = new ABox("3A",3);abox.addShape(new BoxShape(1,-1,-1,1,0,1,-1,2)); abox.addShape(new BoxShape(-1,1,1,0,1,1,2,1)); aboxes.add(abox);/*** ***/abox = new ABox("3B",4);abox.addShape(new BoxShape(0,0,0,1,1,1,1,2)); abox.addShape(new BoxShape(0,0,1,0,-1,1,0,1)); aboxes.add(abox);/**** **/abox = new ABox("4A",5);abox.addShape(new BoxShape(1,-1,0,1,-1,2,0,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,2,1)); abox.addShape(new BoxShape(1,-1,1,0,0,1,0,2)); abox.addShape(new BoxShape(-1,1,0,1,1,1,2,1)); aboxes.add(abox);/******/abox = new ABox("4b",6);abox.addShape(new BoxShape(1,-1,0,1,0,2,1,2)); abox.addShape(new BoxShape(1,1,-2,1,-1,1,0,1)); abox.addShape(new BoxShape(-1,-1,1,0,1,1,1,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,0,1)); aboxes.add(abox);/**/abox = new ABox("5",7);abox.addShape(new BoxShape(0,0,-1,1,0,1,1,1));abox.addShape(new BoxShape(0,0,-1,1,0,1,0,2));abox.addShape(new BoxShape(-1,1,1,0,2,0,1,1));abox.addShape(new BoxShape(1,-1,0,1,1,1,0,2));aboxes.add(abox);}/***随机获取方块*@return*/public static ABox getBox() {//return aboxes.get(new Random().nextInt(aboxes.size()));return aboxes.get(newRandom().nextInt(aboxes.size())).setDefault();}}/***方块坐标集的一个类,用于简化初始化方块时输入坐标*@author Administrator**/class BoxShape{public int dx1,dx2,dx3,dx4;public int dy1,dy2,dy3,dy4;public BoxShape(int dx1,int dy1,int dx2,int dy2,int dx3,int dy3,int dx4,int dy4){this.dx1= dx1; this.dy2= dy2;this.dx3= dx3; this.dy4= dy4;}/** this.dy1= dy1;this.dy3= dy3;this.dx2= dx2;this.dx4= dx4;*返回坐标点数组*@return*/public point[] getList(){return new point[]{new point(dx1,dy1),new point(dx2,dy2),new point(dx3,dy3),new point(dx4,dy4)};}*一个坐标的类 .可用Point,Dimension代替*@author Administrator**/class point {private int x;private int y;public point (int x,int y) {this.x= x;this.y= y;}public int getX(){return x;}public int getY(){return y;}public point add(point other){return new point(x+other.getX(),y+other.getY());}public void setxy(int x,int y){this.x= x;this.y= y;}public String toString() {return ""+x+":"+y;}}THE UNIVERSITY OF AUCKLANDFIRST SEMESTER, 2011Campus: CityCOMPUTER SCIENCEPrinciples of Programming(Time Allowed: TWO hours)Note:*The use of calculators is NOT permitted.*You should separate the Section A Question Booklet from the Section B Question/Answer Booklet. You may keep the Section A Question Booklet. You must hand in the Section BQuestion/Answer booklet and the Teleform sheet.*Compare the exam version number on the Teleform sheet supplied with the version number above. If they do not match, ask the supervisor for a new sheet.*Enter your name and student ID on the Teleform sheet. Your name should be entered left aligned. If your name is longer than the number of boxes provided, truncate it.*Answer Section A on the Teleform answer sheet provided. Each question in this section is worth 2 marks.*For Section A, use a dark pencil to mark your answers in the answer boxes on the Teleform sheet.Check that the question number on the sheet corresponds to the question number in thisquestion/answer book. Do not cross out answers on the Teleform sheet if you change your mind.You must completely erase one answer before you choose another one. If you spoil your sheet,ask the supervisor for a replacement. There is one correct answer per question.*Answer Section B in the space provided in the Section B Question/Answer Booklet.*Attempt all questions. Write as clearly as possible. The space provided will generally be sufficient but is not necessarily an indication of the expected length. Extra space is providedat the end of this exam book.CONTINUEDVERSION 00000001- 2 -COMPSCI 101PLEASE CHECK BEFORE YOU START:Have you entered your name and student ID on the Teleform sheet (letters written in the boxesand corresponding circles filled in) and on the front of the Section B question/answer booklet?*What output is produced when the following code is executed?System.out.println("[" + 4 + 4 + 3 * 5 / 2 + "," + 2 + 2 + "]");[447.5,22][15.5,22][447,22][15.5,4][15,22]*Which of the following outputs could NOT have been produced by the following code?int a = (int) (Math.random() * (4 - 1));int b = (int) (Math.random() * 4) - 1;System.out.println("a: " + a + " b: " + b);*a: 0 b: 2*a: 2 b: -1*a: 0 b: 0*a: -1 b: 2*None of the above3) What output is produced when the following code is executed?int a = 9;int b = 1;int c = a % (a - 1);int d = b % (b + 1);int sum = c + d;System.out.println("sum: " + sum);*sum: 10*sum: 2*sum: 9*sum: 1*None of the above*What output is produced when the following code is executed?String word = "SPLENDID";int pos1 = word.indexOf("S");int pos2 = word.indexOf("word");int sum = pos1 + pos2;System.out.println(sum);*-2*1*0*-1*None of the above*What output is produced when the following is executed?String word = "JOYFUL";char c = word.charAt(word.length() - 2);word = word.substring(0, 1) + word.substring(3) + c;System.out.println(word);JOFULFJFULUJOFULUJFULFNone of the above*Consider the following variable declarations:Point p1, p2;Rectangle r1, r2;p1 = new Point(10, 20);p2 = new Point(30, 40);r1 = new Rectangle(10, 20, 30, 40);r2 = new Rectangle(50, 60, 70, 80);Given these variable declarations, only ONE of the following statements will COMPILE. Which one?*boolean result = p1.intersects(p2);*boolean result = p1.contains(r1);*boolean result = p2.contains(p2);*boolean result = r2.contains(p1);*boolean result = r1.intersects(p2);7) What is the output of the following code?boolean a = true;boolean b = true;boolean c = false;if (c) {System.out.println("first");} else if (a && c){ if (a || b) {System.out.println("second"); } else {System.out.println("third");}} else if (a || c){ System.out.println("fourth");} else {System.out.println("fifth");}*fifth*third*second*first*fourth*Given the isPerfect() method defined below, which of the following sections of code prints “yes”?private boolean isPerfect(int n1, int n2, int n3) {int sum = n1 + n2 + n3;int product = n1 * n2 * n3;if (sum == product) {return true;}return false;}*if (isPerfect(0, 3, 3)){ System.out.println("yes");}*if (isPerfect(-1, 6, 1)) {System.out.println("yes");}*if (isPerfect(1, 2, 3)){ System.out.println("yes");}*if (isPerfect(2, 2, 2)){ System.out.println("yes");}(e) None of the above*What is the output of the following code?public void start(){ int a, b;a = 1;b = 2;exam(a, b);System.out.print("a: " + a + ", ");System.out.print("b: " + b);}private void exam(int a, int other) {a = a + 1;other = other + 1;}*a: 1, b: 2*a: 2, b: 3*a: 2, b: 2*a: 1, b: 3*The code would not compile because the names of the parameters in the method definition do not match the names of the variables in the statement that calls the method.10) What output is produced by the following code segment?int counter = 1;int sum = 0;while (counter <= 3) {sum += counter;}System.out.println(sum);//6//2//Nothing, because the loop never stops.//Nothing, because the variable sum is out of scope.//311) What output is produced by the following code segment?int i = 7;int counter = 0;while (i >= 0) {counter++;i = i - 3;}System.out.println(counter);*3*4*2*Nothing, because the variable counter is out of scope.*Nothing, because the loop never stops.12) A for loop has the following basic structure:for (initialisation; condition; increment) {...}Which of the following is the correct order in which the three component parts of the loop would be encountered if the loop executed exactly twice?(a) initialisation condition condition increment increment increment(c) initialisation increment increment condition condition condition(d) initialisation condition increment condition increment(e) initialisation increment condition increment condition increment13) What output is produced by the following code?String[] words = {"one", "two", "buckle", "my", "shoe"};for (int i = 0; i < words.length; i++) {if (words[i].length() <= 3){ System.out.print(words[i].charAt(0));}}*tbms*otm*bms*otbms*Nothing would be printed*What output is produced by the following code segment?int sum = 0;for (int i = 1; i < 5; i++) {sum += i;}System.out.println(sum);*15*4*6*10*Nothing, because the variable sum is out of scope.15) Consider the following while loop:int i = 10;while (i > 0) {System.out.println(i * i);i -= 2;}Which of the following for loops is equivalent to this while loop?*for (int i = 0; i < 10; i++) {System.out.println(i * i);}*for (int i = 10; i > 0; i--){ System.out.println(i * i);}*for (int i = 0; i <= 10; i=i+2) {System.out.println(i * i);}*for (int i = 10; i >= 0; i=i-2){ System.out.println(i * i);}*for (int i = 10; i > 0; i=i-2) {System.out.println(i * i);}。

俄罗斯方块java代码1

俄罗斯方块java代码1

/*** File: ErsBlocksGame.java* User: Administrator* Date: Dec 15, 2003* Describe: 俄罗斯方块的Java 实现*/import javax.swing.*;import java.awt.*;import java.awt.event.*;/*** 游戏主类,继承JFrame类,负责游戏的全局控制。

* 内含* 1, 一个GameCanvas画布类的实例引用,* 2, 一个保存当前活动块(ErsBlock)实例的引用,* 3, 一个保存当前控制面板(ControlPanel)实例的引用;*/public class ErsBlocksGame extends JFrame {/*** 每填满一行计多少分*/public final static int PER_LINE_SCORE = 100;/*** 积多少分以后能升级*/public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20;/*** 最大级数是10级*/public final static int MAX_LEVEL = 10;/*** 默认级数是5*/public final static int DEFAULT_LEVEL = 5;//一个GameCanvas画布类的实例引用,private GameCanvas canvas;// 一个保存当前活动块(ErsBlock)实例的引用,private ErsBlock block;// 一个保存当前控制面板(ControlPanel)实例的引用; private ControlPanel ctrlPanel;private boolean playing = false;private JMenuBar bar = new JMenuBar();//菜单条包含4个菜单private JMenumGame = new JMenu("游戏"),mControl = new JMenu("控制"),mWindowStyle = new JMenu("窗口风格"),mInfo = new JMenu("帮助");//4个菜单中分别包含的菜单项private JMenuItemmiNewGame = new JMenuItem("新游戏"),miSetBlockColor = new JMenuItem("设置方块颜色"),miSetBackColor = new JMenuItem("设置背景颜色"),miTurnHarder = new JMenuItem("增加难度"),miTurnEasier = new JMenuItem("降低难度"),miExit = new JMenuItem("退出"),miPlay = new JMenuItem("开始"),miPause = new JMenuItem("暂停"),miResume = new JMenuItem("继续"),miStop = new JMenuItem("停止"),miAuthor = new JMenuItem("作者: Java游戏设计组"),miSourceInfo = new JMenuItem("版本:1.0");//设置窗口风格的菜单private JCheckBoxMenuItemmiAsWindows = new JCheckBoxMenuItem("Windows"),miAsMotif = new JCheckBoxMenuItem("Motif"),miAsMetal = new JCheckBoxMenuItem("Metal", true);/*** 主游戏类的构造函数* @param title String,窗口标题*/public ErsBlocksGame(String title) {super(title);//初始窗口的大小,用户可调控setSize(315, 392);Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();//将游戏窗口置于屏幕中央setLocation((scrSize.width - getSize().width) / 2,(scrSize.height - getSize().height) / 2);//创建菜单createMenu();Container container = getContentPane();// 布局的水平构件之间有6个象素的距离container.setLayout(new BorderLayout(6, 0));// 建立20个方块高,12个方块宽的游戏画布canvas = new GameCanvas(20, 12);//建立一个控制面板ctrlPanel = new ControlPanel(this);//游戏画布和控制面板之间左右摆放container.add(canvas, BorderLayout.CENTER);container.add(ctrlPanel, BorderLayout.EAST);//增加窗口监听器addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {stopGame();System.exit(0);}});//增加构件的适配器,一旦构件改变大小,就调用//fanning()方法,自动调整方格的尺寸addComponentListener(new ComponentAdapter() {public void componentResized(ComponentEvent ce) {canvas.fanning();}});show(); //setVisiable// 根据窗口的大小,自动调整方格的尺寸canvas.fanning();}/*** 让游戏“复位”*/public void reset() {ctrlPanel.reset(); //控制窗口复位canvas.reset(); //游戏画板复位}/*** 判断游戏是否还在进行* @return boolean, true-还在运行,false-已经停止*/public boolean isPlaying() {return playing;}/*** 得到当前活动的块* @return ErsBlock, 当前活动块的引用*/public ErsBlock getCurBlock() {return block;}/*** 得到当前画布* @return GameCanvas, 当前画布的引用*/public GameCanvas getCanvas() {return canvas;}/*** 开始游戏*/public void playGame() {play();ctrlPanel.setPlayButtonEnable(false);miPlay.setEnabled(false);ctrlPanel.requestFocus();}/*** 游戏暂停*/public void pauseGame() {if (block != null) block.pauseMove();ctrlPanel.setPauseButtonLabel(false);miPause.setEnabled(false);miResume.setEnabled(true);}/*** 让暂停中的游戏继续*/public void resumeGame() {if (block != null) block.resumeMove();ctrlPanel.setPauseButtonLabel(true);miPause.setEnabled(true);miResume.setEnabled(false);ctrlPanel.requestFocus();}/*** 用户停止游戏*/public void stopGame() {playing = false;if (block != null) block.stopMove();miPlay.setEnabled(true);miPause.setEnabled(true);miResume.setEnabled(false);ctrlPanel.setPlayButtonEnable(true);ctrlPanel.setPauseButtonLabel(true);}/*** 得到当前游戏者设置的游戏难度* @return int, 游戏难度1-MAX_LEVEL=10 */public int getLevel() {return ctrlPanel.getLevel();}/*** 让用户设置游戏难度系数* @param level int, 游戏难度系数为1-MAX_LEVEL=10 */public void setLevel(int level) {if (level < 11 && level > 0) ctrlPanel.setLevel(level);}/*** 得到游戏积分* @return int, 积分。

java俄罗斯方块完整代码

java俄罗斯方块完整代码
//key按键Pressed按下了
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

俄罗斯方块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源代码

俄罗斯方块——java源代码
scoreField = new TextField(8);
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));

java程序设计俄罗斯方块源代码

java程序设计俄罗斯方块源代码

java程序设计俄罗斯方块源代码这个代码片段展示了俄罗斯方块游戏界面的设计及方块移动的功能实现: ```import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class Board extends JPanel {private static final int ROWS = 20;private static final int COLUMNS = 10;private static final int BLOCK_SIZE = 30;private Tetrominoes[] board;private Shape currentPiece;private Timer timer;private boolean isPlaying;public Board() {board = new Tetrominoes[ROWS * COLUMNS];clearBoard();currentPiece = new Shape();timer = new Timer();isPlaying = true;}for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLUMNS; j++) {drawBlock(g, j * BLOCK_SIZE, i * BLOCK_SIZE, board[i * COLUMNS + j]);}}if (currentPiece != null) {for (int i = 0; i < 4; i++) {drawBlock(g, currentPiece.getX(i) * BLOCK_SIZE, currentPiece.getY(i) * BLOCK_SIZE, currentPiece.getShape());}}}private void drawBlock(Graphics g, int x, int y, Tetrominoes shape) {Color color = shape.getColor();g.setColor(color);g.fillRect(x + 1, y + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2);g.setColor(color.brighter());g.drawLine(x, y + BLOCK_SIZE - 1, x, y);g.drawLine(x, y, x + BLOCK_SIZE - 1, y);g.setColor(color.darker());g.drawLine(x + 1, y + BLOCK_SIZE - 1, x + BLOCK_SIZE - 1, y + BLOCK_SIZE - 1);g.drawLine(x + BLOCK_SIZE - 1, y + BLOCK_SIZE - 1, x + BLOCK_SIZE - 1, y + 1);}private void clearBoard() {for (int i = 0; i < ROWS * COLUMNS; i++) {board[i] = Tetrominoes.NoShape;}}private boolean tryMove(Shape newPiece, int newX, int newY) {for (int i = 0; i < 4; i++) {int x = newX + newPiece.getX(i);int y = newY + newPiece.getY(i);if (x < 0 || x >= COLUMNS || y < 0 || y >= ROWS) {return false;}if (board[y * COLUMNS + x] != Tetrominoes.NoShape) {return false;}}currentPiece = newPiece;currentPiece.setX(newX);currentPiece.setY(newY);return true;}private void dropDown() {int newY = currentPiece.getY();while (newY < ROWS - 1 && tryMove(currentPiece, currentPiece.getX(), newY + 1)) {newY++;}pieceDropped();}private void pieceDropped() {for (int i = 0; i < 4; i++) {int x = currentPiece.getX(i);int y = currentPiece.getY(i);board[y * COLUMNS + x] = currentPiece.getShape();}removeFullRows();if (isPlaying) {timer.start();newPiece();}}private void removeFullRows() {int numRowsRemoved = 0;for (int i = ROWS - 1; i >= 0; i--) {boolean rowIsFull = true;for (int j = 0; j < COLUMNS; j++) {if (board[i * COLUMNS + j] == Tetrominoes.NoShape) { rowIsFull = false;break;}}if (rowIsFull) {numRowsRemoved++;for (int k = i; k > 0; k--) {for (int j = 0; j < COLUMNS; j++) {board[k * COLUMNS + j] = board[(k - 1) * COLUMNS + j];}}for (int j = 0; j < COLUMNS; j++) {board[j] = Tetrominoes.NoShape;}i++;}}}private void newPiece() {currentPiece.setRandomShape();currentPiece.setX(COLUMNS / 2 - 1);currentPiece.setY(0);if (!tryMove(currentPiece, currentPiece.getX(), currentPiece.getY())) { currentPiece.setShape(Tetrominoes.NoShape);timer.stop();isPlaying = false;}}private class Timer implements ActionListener {private final int DROP_INTERVAL = 500;private javax.swing.Timer timer;public Timer() {timer = new javax.swing.Timer(DROP_INTERVAL, this);timer.start();}public void actionPerformed(ActionEvent e) {if (tryMove(currentPiece, currentPiece.getX(), currentPiece.getY() + 1)) { currentPiece.setY(currentPiece.getY() + 1);} else {pieceDropped();}}public void start() {timer.start();}public void stop() {timer.stop();}}private class TAdapter extends KeyAdapter {public void keyPressed(KeyEvent e) {if (!isPlaying) {return;}switch (e.getKeyCode()) {case KeyEvent.VK_LEFT:tryMove(currentPiece, currentPiece.getX() - 1, currentPiece.getY());break;case KeyEvent.VK_RIGHT:tryMove(currentPiece, currentPiece.getX() + 1, currentPiece.getY());break;case KeyEvent.VK_DOWN:tryMove(currentPiece.rotateRight(), currentPiece.getX(), currentPiece.getY());break;case KeyEvent.VK_UP:tryMove(currentPiece.rotateLeft(), currentPiece.getX(), currentPiece.getY());break;case KeyEvent.VK_SPACE:dropDown();break;case 'p':case 'P':timer.stop();break;case 'r':case 'R':timer.start();break;}}} } ```。

android平台俄罗斯方块游戏完整代码

android平台俄罗斯方块游戏完整代码

整个游戏我分为10个java文件:先是俄罗斯方块的形状存储statefang.java,代码如下:package com.example.eluosifangkuai;public class statefang { //方块的逻辑类public static int [][][] state = new i整个游戏我分为10个java文件:先是俄罗斯方块的形状存储statefang.java,代码如下:package com.example.eluosifangkuai;public class statefang { //方块的逻辑类public static int [][][] state = new int[][][] {{// I{ 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// I1 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }, {// I2 { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// I3 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }, {// I4 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O5 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O6 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O7 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O8 { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// L9 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 } }, {// L10 { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// L11 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 } }, {// L12 { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 } }, {// J13{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 } }, {// J14{ 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } }, {// J15{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// J16{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 1, 1, 1, 0 } }, {// T17{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// T18{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 1, 0, 0 } }, {// T19{ 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 0, 0 }, { 1, 0, 0, 0 } }, {// T20{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 1, 1, 0, 0 } }, {// S21{ 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// S22{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 1, 1, 0, 0 } }, {// S23{ 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// Z24{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// Z25{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } }, {// Z26{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// Z27{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } } // 28};}我们当然还要编写音乐播放类,资源播放类了等等。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

东西绝对不多说,直接看!看了拷贝就懂了!!,直接可以拷贝下面的东西,然后记得把那个BLOCK 的名字改成你自己的类名,这个很关键哦,不然是错的可别怪我,呵呵~~import java.awt.*;importimport javax.swing.*;import java.applet.*;import.*;import ng.*;import java.io.*;publicclass 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 scoreT ex=new Label("0");static Label infoT ex=new Label("");static Label speedT ex=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 JT extArea dlg_1_text=new JTextArea();staticint startSign=0;//游戏开始标志0未开始1开始2暂停static String butLab[]={"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"}; staticint game_body[][]=newint[19][10];staticint game_sign_x[]=newint[4];//用于记录4个方格的水平位置staticint game_sign_y[]=newint[4];//用于记录4个方格的垂直位置staticboolean downSign=false;//是否落下staticint blockNumber=1;//砖块的编号staticint gameScore=0;//游戏分数staticint speedMark=1;publicstaticvoid main(Stringargs[]){BlockmyBlock=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();}publicvoid init(){setLayout(null);for(int i=0;i<6;i++){but[i]=new Button(butLab[i]);add(but[i]);but[i].addKeyListener(this);but[i].setBounds(360,(240+30*i),160,25);}add(scoreLab);add(scoreT ex);add(speedLab);add(speedT ex);add(infoLab);add(infoT ex);add(scoreLab);scoreLab.setBounds(320,15,30,20);scoreT ex.setBounds(360,15,160,20);scoreT ex.setBackground(Color.white);speedLab.setBounds(320,45,30,20);speedT ex.setBounds(360,45,160,20);speedT ex.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();}publicvoid actionPerformed(ActionEvente){if(e.getSource()==but[0])//开始游戏{startSign=1;infoTex.setT ext("游戏已经开始!");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();scoreT ex.setT ext("0");infoTex.setT ext("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource()==but[2])//降低级数{infoTex.setT ext("降低级数!"); speedMark--;if(speedMark<=1){speedMark=1;infoTex.setT ext("已经是最低级数!"); }speedT ex.setT ext(speedMark+"");}if(e.getSource()==but[3])//提高级数{infoTex.setT ext("提高级数!"); speedMark++;if(speedMark>=9){speedMark=9;infoTex.setT ext("已经是最高级数!"); }speedT ex.setT ext(speedMark+"");}if(e.getSource()==but[4])//游戏暂停{this.add(noStop);infoTex.setT ext("游戏暂停!");timer.suspend();}if(e.getSource()==noStop)//取消暂停{this.remove(noStop);this.add(but[4]);infoTex.setT ext("继续游戏!");timer.resume();}if(e.getSource()==but[5]||e.getSource()==mi1)//退出游戏{jf.dispose();}if(e.getSource()==mi1_0)//退出游戏{dlg_1=new JDialog(jf,"关于");try{FileInputStreamio=new FileInputStream("resource/guanyu.txt");//得到路径byte a[]=newbyte[io.available()];io.read(a);io.close();Stringstr=new String(a);dlg_1_text.setT ext(str);}catch(Exceptiong){}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();}}publicvoid rand_block()//随机产生砖块{num=(int)(Math.random()*6)+1;//产生0~6之间的随机数blockNumber=num;switch(blockNumber){case1:block1();blockNumber=1;break;case2:block2();blockNumber=2;break;case3:block3();blockNumber=3;break;case4:block4();blockNumber=4;break;case5:block5();blockNumber=5;break;case6:block6();blockNumber=6;break;case7:block7();blockNumber=7;break;}}publicvoid 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][gam e_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.setT ext("游戏进行中!");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][gam e_sign_x[3]+2]!=2){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.setT ext("游戏进行中!");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]==g ame_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][gam e_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[1]==game_sign_y[2]&&game_sign_y[2]==game_sign_y[3]&&game_sign_x[0]==g ame_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.setT ext("游戏进行中!");repaint();}if(game_sign_x[1]==game_sign_x[2]&&game_sign_x[1]==game_sign_x[3]&&game_sign_y[0]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[0]==game_sign_y[1]&&game_sign_y[1]==game_sign_y[2]&&game_sign_x[0]==g ame_sign_x[3]){if(game_body[game_sign_y[0]+1][game_sign_x[0]+1]!=2&&game_body[game_sign_y[2]-1][gam e_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.setT ext("游戏进行中!");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]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[1]==game_sign_y[2]&&game_sign_y[1]==game_sign_y[3]&&game_sign_x[0]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_x[0]==game_sign_x[2]&&game_sign_x[0]==game_sign_x[3]&&game_sign_y[1]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[0]==game_sign_y[1]&&game_sign_y[0]==game_sign_y[2]&&game_sign_x[1]==g{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.setT ext("游戏进行中!");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]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[1]==game_sign_y[2]&&game_sign_y[2]==game_sign_y[3]&&game_sign_x[0]==g ame_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[2]][game_sign_x[2]]=1;game_body[game_sign_y[3]-1][game_sign_x[3]-1]=1;infoTex.setT ext("游戏进行中!");repaint();}}if(game_sign_x[0]==game_sign_x[1]&&game_sign_x[1]==game_sign_x[3]&&game_sign_y[2]==g ame_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.setT ext("游戏进行中!");repaint();}}if(game_sign_y[0]==game_sign_y[1]&&game_sign_y[1]==game_sign_y[2]&&game_sign_x[2]==g ame_sign_x[3]){if(game_body[game_sign_y[0]+1][game_sign_x[0]+1]!=2&&game_body[game_sign_y[2]-1][gam e_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.setT ext("游戏进行中!");repaint();}}}if(blockNumber==6&&downSign==false)//变换两层砖块1的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.setT ext("游戏进行中!");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.setT ext("游戏进行中!");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;infoTex.setT ext("游戏进行中!");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.setT ext("游戏进行中!");repaint();}}}}publicvoid 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;}}}}publicvoid num_csh_restart()//重新开始时数组清零{for(int i=0;i<19;i++)for(int j=0;j<10;j++){game_body[i][j]=0;}}}publicvoid keyT yped(KeyEvente){}publicvoid keyPressed(KeyEvente){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.setT ext("游戏未开始或已结束!");}}publicvoid keyReleased(KeyEvente){}publicvoid paint(Graphicsg){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);}}}}publicvoid 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.setT ext("向左移动!");repaint();}}publicvoid 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.setT ext("向右移动!");repaint();}}publicvoid 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.setT ext("游戏进行中!");repaint();}publicboolean game_over()//判断游戏是否结束{int sign=0;for(int i=0;i<10;i++){if(game_body[4][i]==2){sign=1;}}if(sign==1){infoTex.setT ext("游戏结束!");changeColor();repaint();startSign=0;timer.suspend();returntrue;}elsereturnfalse;}publicvoid 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;scoreT ex.setT ext(gameScore+"");infoTex.setT ext("恭喜得分!");for(int j=i;j>=1;j--){{game_body[j][k]=game_body[j-1][k];}}}}}publicvoid changeColor()//给已经落下的块换色{downSign=false;for(int k=0;k<4;k++){game_body[game_sign_y[k]][game_sign_x[k]]=2; }}publicvoid 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++;}}}}publicvoid cancelDW()//将定位数组初始化{for(int k=0;k<4;k++){game_sign_x[k]=0;game_sign_y[k]=0;}}publicvoid block1()//长条game_body[0][4]=1;game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;}publicvoid block2()//正方形{game_body[3][4]=1;game_body[2][4]=1;game_body[3][5]=1;game_body[2][5]=1;}publicvoid block3()//3加1(下) {game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[3][5]=1;}publicvoid block4()//3加1(中) {game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[2][5]=1;}publicvoid block5()//3加1(上) {game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[1][5]=1;}publicvoid block6()//转折1 {game_body[1][5]=1;game_body[2][5]=1;game_body[2][4]=1;game_body[3][4]=1;}publicvoid 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(BlockmyBlock){this.myBlock=myBlock;}publicvoid run(){while(myBlock.startSign==1){try{sleep((10-myBlock.speedMark+1)*100); myBlock.down();}catch(InterruptedExceptione){}}}}。

相关文档
最新文档