俄罗斯方块java代码.docx
importjavax.swing.暂停标记*/private boolean isPause = true;/ *;importjavax.swing.Timer;importjava.awt.*;importjava.awt.event.*;importjava.util.;*默认构造函数/public SquaresFrameO *记分面板InfoPanel infoPanel = new InfoPanel();Title:俄罗斯方块*Description:俄罗斯方块*Copyright:俄罗斯方块*Company:俄罗斯方块* authorZhUYong* version1.OpublicclassSquaresGamepublicstaticvoidmain(Stringargs)newSquaresFrame().play();)classSqUareSFrameextendsJFramepublicfinalstaticintWIDTH=500;publicfinalstaticintHEIGHT=600;*游戏区*/privateBoxPanelboxPanel;boxPanel=newBoxPanel(infoPanel);JMenuBarbar=newJMenuBar();JMenumenu=newJMenU(“菜单”);JMenuItembegin=newJMenU工tem(“新游戏”);finalJMenuItempause=newJMenU工tem("暂停");JMenuItemstop=newJMenU工tem(“结束”);SetJMenuBar(bar);bar.add(menu);menu.add(begin);menu.add(pause);menu.add(stop);stop.addActIonListener(newActionListenerOpublicvoidactionPerformed(ActionEvente)System.exit(O););pause.addActIonListener(newActionListenerOpublicvoidactionPerformed(ActionEvente)if(isPause)boxPanel.supend(false);isPause=!isPause;pause.setText(“恢复”);elseboxPanel.supend(true);isPause=!isPause;pause.setText(“暂停“););begin.addActIonListener(newActionListenerOpublicvoidactionPerformed(ActionEvente)boxPanel.newGame();)boxPanel.SetBorder(BorderFactory.CreateTitledBorder(BorderFactory.ereateEtChedBorder(),Box);infoPanel.SetBorder(BorderFactory.CreateTitlecfBorcfer(BorderFactory.createEtchedBorder)r,Infon);add(boxPanel,BorderLayout.CENTER);add(infoPanel,BorderLayout.EAST);SetTitle(nSquaresGame',);setSize(WIDTHfHEIGHT);/不可改变框架大小SetResizable(false);/定位显示到屏幕中间SetLocation(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()-IVlDTH)/2,(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()-HEIGHT)/2);SetDefaultcioseOperation(JFrame.EXIT_ON_CLOSE);SetVisible(true);publicvoidplay()boxPanel.newGame();)* authorZhUYong* 游戏区面板* /classBoxPaneIextendsJPanel*定义行*/publicfinalstaticintROWS=20;*定义列public final staticint COLS = 10;publicfinalstaticColorDISPLAY=newColor(128z128z255);* 没有方块时显示的颜色* /publicfinalstaticColorHIDE=newColor(238z238z238);/大记分面板上显示的下一个方块的颜色* /publicfinalstaticColorNEXTDISPLAY=Color.ORANGE;* 是否显示网络publicfinalstaticbooleanPAINTGRID=false;/ Level用定时器的延时控制* 用4个按钮表示一个方块* /privateJButtonsquares=newJButtonROWSCOLS;/* 定义对前位置是否有方块.用颜色区别.* /privateintStateTable=newintROWSCOLS;privateInfoPanelScorePanel;privateABoxCurrentBox;privateABoxnextBox;* 各方块颜色数组.其中0号颜色为无方块时颜色.共7种方块.最后一个消行时颜色*/privatestaticColorboxColor=newColornewColor(238f238f238)znewColor(128z128,255)znewColor(189z73z23)znewColor(154z105f22),newColor(101r124z52),newColor(49r100128),newColor(84z57z119),newColor(Illz54z102)fnewColor(1265057)rColor.RED;* 定时器,负责方块自动下移* /privateTimertimer;privateintlevel;* 初时化时的延时* /privatefinalstaticintINITDELAY=940;* 每一级别延时减少的步进值* /privatefinalstaticintINC=90;publicBoxPanel(InfoPanelpanel)SetLayout(newGridLayout(RoWS,COLSr1,1);/可能获取焦点,才能接受键盘事件SetFocusable(true);/setCursor(newCursor(1);*初时化,生成JBUtton,设置颜色.JButton数组按照先第一行再第二行的顺序添加.下标为行列和x丫正好相反.*/for(inti=0;i<ROWS;i+)for(intj=0;j<COLS;j+)JButtonsquare=newJButton(,);square.SetEnabled(false);square.SetBorderPainted(PAINTGRID);squaresij=square;StateTableij=0;add(square);)ScorePanel=panel;timer=newTimer(INITDELAYrnewautoDownHandler();/注册键盘事件addKeyListener(newKeyAdapter()publicvoidkeyPressed(KeyEvente)intkey=e.getKeyCode();System.out.println(bt.getX()+”:+bt.getY();if(key=KeyEvent.VK_DOWN)dropdown();elseif(key=KeyEvent.VK_UP)rotate();elseif(key=KeyEvent.VK_RIGHT)right();elseif(key=KeyEvent.VK_LEFT)left(););重新所有方块.即重新改变所有JButton背景色privatevoidShowBox()for(inti=0;i<ROWS;i+)for(intj=0;j<COLS;j+)squaresij.SetBackground(boxColorStateTableij);*只重新显示当前方块privatevoidShowCurrentBoxOpointlocation=CurrentBox.getLocation();for(inti=0;i<4;i+)introw=locationi.getY();intcol=locationi.getX();squaresrowcol.SetBackground(boxColorStateTablerowcol);)/* 消行记分* /privatevoidClearBox()intClearLines=O;for(intI=ROWS-I;i>=0;i-)for(intj=0;j<COLS;j+)if(StateTableij=0)break;if(j=(COLS-I)removeLine(i);ClearLines+;i+;)if(clearLines>O)ScorePanel.WinScore(ClearLines);upgrade();)/* 消行,重置属性表.下移* paramline* /publicvoidremoveLine(intline)timer.stop();for(intj=0;j<COLS;j+)StateTablelinej=8;/System.out.println(squareslinej.getBackground();squareslinej.SetBackground(Color.RED);/System.out.printin(squareslinej.gtBackground();/validate();ShowBox();for(inti=line;i>=0;i一一)for(intj=0;j<COLS;j+)if(i!=0)StateTableij=StateTablei-1j;elseStateTableij=O;ShowBox();timer.start();)* 检查把方块移动到(x,y)时是否合法.* paramx* paramy* return*/publicbooleanCheckAction(intx,inty)/先移除当前方块,再判断.当前方块和下一位置的方块有共用的位置.removecurrentBox();booleanret=true;pointlist=CurrentBox.getShape().getList();intxx=O;intyy=O;for(inti=0;i<4;i+)if(i!=0)xx=listi.getX()+x;yy=listi.getY()+y;elsexx=x;yy=y;/System.out.printIn(,check÷i÷,f->+xx÷:w÷yy);if(××>COLSIIxx<0)ret=false;break;if(yy>=ROWSIIyy<O)ret=false;break;/System,out.printIn(',afterbreakcheck,+i+,->,+xx+:,+yy);if(StateTableyyxx!=0)ret=false;break;)aCidCurrentBox();returnret;*左移publicvoidleft()if(CheckAction(CurrentBox.getHead().getX()-lzCurrentBox.getHead().getY()(removecurrentBox();ShowCurrentBox();CurrentBox.setHead(CurrentBox.getHead().getX()-lzCurrentBox.getHead().getY();addCurrentBox();/showBox();ShowCurrentBox();)/* 右移* /publicvoidright()if(CheckAction(CurrentBox.getHead().getX()÷lzCurrentBox.getHead().getY()(removeCurrentBox();ShowCurrentBox();CurrentBox.setHead(CurrentBox.getHead().getX()+lzCurrentBox.getHead().getY();addCurrentBox();/showBox();ShowCurrentBox();)/* 下移* return* /publicbooleandown()intchoose=0;if(CheckAction(CurrentBox.getHead().getX(),CurrentBox.getHead().getY()+1)(removeCurrentBox();ShowCurrentBox();CurrentBox.setHead(currentBox.getHead().getX(),CurrentBox.getHead().getY()+l);addCurrentBox();ShowCurrentBox();/showBox();returntrue;elseClearBox();CurrentBox=nextBox.SetDefault();nextBox=BoxFactory.getBox().SetDefault();ScorePanel.setNext(nextBox);/showBox();/检查是否游戏结束if(CheckGameOver()supend(false);choose=JOptionPane.ShowConfirmDialog(th±sf”游戏结束n你的积分为"+scorePanel.getSCore()+nn要开始新游戏吗?”,”GameOver'½JOptionPane.YES_NO_OPTIONfJOptionPane.WARNING_MESSAGE);if(choose=JOptionPane.YES_OPTION)newGame();)addCurrentBox();ShowCurrentBox();/showBox();returnfalse;)/* 丢下.* /publicvoiddropdown()while(down();)/* 判断是否结束* returnprivatebooleanCheckGameOver()pointlocation=CurrentBox.getLocation();for(inti=0;i<4;i+)introw=locationi.getY();intcol=locationi.getX();if(StateTablerowcol!=0)returntrue;)returnfalse;)/* 变形* /publicvoidrotate()if(CheckRotate()removecurrentBox();ShowCurrentBox();CurrentBox.rotate();addCurrentBox();ShowCurrentBox();/ShowBox();)/* 检查变形是否合法* return* /privatebooleanCheckRotate()removecurrentBox();intoldheadx=CurrentBox.getHead().getX();intOldheady=CurrentBox.getHead().getY();/System,out.printIn("oldhead:,+oldheadx+,l,÷Oldheady);booleanret=true;pointshape=CurrentBox.getNextShape().getList();intx=0ry=0rnewheadx=0newheady=O;for(inti=0;i<4;i+)if(i!=0)x=newheadx+shapei.getX();y=newheady+shapei.getY();)elsenewheadx=oldheadx+shapei.getX();newheady=Oldheady+shapei.getY();x=newheadx;y=newheady;/System.out.printin(,newhead:+newheadx+,:+newheady);)/System.out.printIn(,checkrotate,+i+,->+x+:,+y);if(×>COLSIIx<0)ret=false;break;if(y>=ROWSy<O)ret=false;break;/System,out.rintln(,lafterbreakcheckrotate”+i+”-“+x+”:”+y);if(StateTableyx!=0)ret=false;break;)addCurrentBox();returnret;)* 移除当前方块.设置颜色为无色.主要用于移动,变形时.清除当前位置方块.显示下一位置方块.*/privatevoidremoveCurrentBox()/System,out.println(,removeCurrentBox:"+Thread.CurrentThread().getName();for(inti=0;i<4;i+)intX=CurrentBox.getLocation()i.getX();inty=currentBox.getLocation()i.getY();StateTableyx=O;)* 添加当前方块到属性表.* /privatevoidaddCurrentBox()for(inti=0;i<4;i+)intX=CurrentBox.getLocation()i.getX();inty=currentBox.getLocation()i.getY();stateTableyx=CurrentBox.getId();)/* 暂停游戏* false时暂停* paramresume*/publicvoidsupend(booleanresume)if(!resume)timer.stop();SetFocusable(false);elsetimer.start();SetFocusable(true);thisrequestFocus();)/* 设置游戏级别.即改变定时器延时.* paramlevel* /publicvoidSetLevel(intlevel)this.level=level;ScorePanel.SetLevel(level);timer.setDelay(TJTOELAY-TZC*level);)/* 自动下移监听器* authorAdministrator* /privateclassautODownHandlerimplementsActionListenerpublicvoidactionPerformed(ActionEvente)down();)/* 根据积分自动设置级别* /publicvoidupgrade()intscore=ScorePanel.getScore();if(score>3000&&level<2)SetLevel(2);elseif(score>6000,&&level<3)SetLevel(3);elseif(score>10000&&level<4)SetLevel(4);elseif(score>15000&&level<5)SetLevel(5);elseif(score>21000&&level<6)SetLevel(6);elseif(score>28000&&level<7)SetLevel(7);elseif(score>35000&&level<8)SetLevel(8);elseif(score>43000&&level<9)SetLevel(9);elseif(score>51000&&level<10)SetLevel(10);)/* 重置,开始新游戏publicvoidnewGame()for(inti=0;i<ROWS;i+)for(intj=0;j<COLS;j+)StateTableij=0;ShowBox();SetLevel(1);ScorePanel.clean();CurrentBox=BoxFactory.getBox();nextBox=BoxFactory.getBox();ScorePanel.setNext(nextBox);SetFocusable(true);requestFocus();addCurrentBox();ShowBox();timer.start();)/*记分面板*authorAdministratorclassInfoPanelextendsJPanelprivate private private privateJLabel JLabel JLabel JPanelScoreLabel;IineLabel;IevelLabel;nextPanel;*下一个方块privateJButtonnextBox;publicInfoPanel()SetLayout(newBorderLayout();Boxvbox=Box.CreateVerticalBox();add(vbox,BorderLayout.CENTER);vbox.add(Box.ereateRigidArea(newDimension(12z50);Boxvboxl=Box.CreateVerticalBox();vbox,add(vboxl);ScoreLabel=newJLabel(,0);IineLabel=newJLabel(,0);IevelLabel=newJLabel(,0);nextPanel=newJPanel();nextBox=newJButton44;nextPanel.SetLayout(newGridLayout(4,4,1,1);for(inti=0;i<4;i+)for(intj=0;j<4;j+)JButtonbt=newJButton(,',);bt.SetEnabled(false);bt,SetBorderPainted(BoxPanel.PAINTGRID);nextPaneladd(bt);nextBoxji=bt;)vboxl.add(newJLabel("Next:,l);vboxl.add(nextPanel);vboxl.add(Box.CreateVerticalStrut(90);vboxl.add(newJLabel(,得分:”);vboxl.add(Box.CreateVerticalStrut(10);vboxl.add(ScoreLabel);vboxl.add(Box.CreateVerticalStrut(10);vboxl.add(newJLabel(',行数:”);vboxl.add(Box.CreateVerticalStrut(10);vboxl.add(IineLabel);vboxl.add(Box.CreateVerticalStrut(10);vboxl.add(newJLabel(Level:n);vbox1.add(BoxCreateVerticalStrut(10);vboxl.add(IevelLabel);vboxl.add(Box.CreateVerticalStrut(80);)/*记分.显示在面板上*paramlines*/publicvoidWinScore(intlines)intscore=O;IineLabel.setText(,+(Integer.parselnt(IineLabel.getText()+lines);if(Iines=I)score=100;elseif(lines=2)score=300;elseif(lines=3)score=500;elseif(lines=4)score=1000;ScoreLabel.setText("',+(Integer.parseint(scoreLabel.getText()+score)设置下一个方块.paramnextpublicvoidsetNext(ABoxnext)for(inti=0;i<4;i+)for(intj=0;j<4;j+)nextBoxij.SetBackground(BoxPanel.HIDE);intheadx=2;intheady=O;/设置方块位置if(next.getld()=1)headx=2;heady=O;elseif(next.getld()=2)headx=1;heady=1;elseif(next.getld()=3)headx=2;heady=1;)elseif(next.getld()=4)headx=1;heady=1;)elseif(next.getld()=5)headx=2;heady=1;elseif(next.getld()=6)headx=1;heady=1;)elseif(next.getld()=7)headx=1;heady=1;)pointshape=next.getShape(O).getList();nextBoxheadxheady.SetBackground(BoxPanel.NEXTDISPLAY);nextBoxheadx+shape1.getX()heady+shape1.getY().setBackground(BoxPanel.NEXTDISPLAY);nextBoxheadx+shape2.getX()heady+shape2.getY().SetBackground(BoxPanel.NEXTDISPLAY);nextBoxheadx+shape3.getX()heady+shape3.getY().SetBackground(BOXPanel.NEXTDISPLAY);)/* 设置显示级别* paramlevel* /publicvoidSetLevel(intlevel)IevelLabel.setText(”,+level);)/* 获取当前积分* return* /publicintgetScore()returnInteger.arselnt(ScoreLabel.getText();*重置publicvoidclean()ScoreLabel.setText(,+O);SetLevel(1);for(inti=0;i<4;i+)for(intj=0;j<4;j+)nextBoxij.SetBackground(BoxPanel.HIDE);*方块类*authorAdministrator/classABoxpublicfinalstaticintROWS=20;publicfinalstaticintCOLS=10;privateintid;*用于存放方块所有样子坐标.*/privateArrayList<BoxShape>ShapeTable;privateStringname;privateintCurrentShapeId;*当前方块位置.注意这里是坐标(x,y)和SquaresrStateTable数组的行列顺序正好相反.privatepointlocation;*方块起始位置.privatepointhead=newpoint(0zCOLS/2);publicABox(Stringname,intid)this.name=name;this.id=id;ShapeTable=newArrayList<BoxShape>();location=newpoint4;*方块变形,选取下一个坐标集.从小到大顺序选取.变形后重设方块位置(头结点)publicvoidrotate()CurrentShapeId=(currentShapeId+1)>=shapeTable.size()?0:(CurrentShapeId+l);pointshapehead=ShapeTable.get(CurrentShapeId).getList()0;setHead(getHead().getX()+shapehead.getX(),getHead().getY()+shapehead.getY();)/* 添加方块坐标集* paramshape*/publicvoidaddShape(BoxShapeshape)ShapeTable.add(shape);/* 重设方块位置定义新的头结点.根据坐标集计算下其它子方块位置.* paramX新位置头结点坐标X* paramy* /publicvoidsetHead(intx,inty)head.setxy(x,y);pointShapePoint=getShape().getList();locationO=head;location1=head.add(ShapePoint1);location2=head.add(ShapePoint2);location3=head.add(ShapePoint3);)* 获取位置数组* return* /publicpointgetLocation()returnlocation;)* 获取头结点* return*/publicpointgetHead()returnhead;* 获取当前坐标集* return* /publicBoxShapegetShape()/getcurrentshapereturnShapeTable.get(CurrentShapeId);)* 获取下一个坐标集publicBoxShapegetNextShape()/intindex=currentShapeld+l;/if(index>=shapeTable.size()index=0;returnShapeTable.get(currentShapeId+l>=shapeTable.size()?0:currentShapeld+l);/* 重置当前方块.因为游戏中一直在重用方块对象* return* /publicABoxSetDefault()SetHead(4,O);CurrentShapeIci=O;returnthis;)/* 获取对应坐标集* paramindex* return* /publicBoxShapegetShape(intindex)returnShapeTable.get(index);)/* 用于调试* /publicStringtoString()return,+name+getHead();publicintgetld()returnid;* 产生方块* authorAdministrator* /classBoxFactory* ArrayL工St中存放每个方块的一个对象.随机获取.* /privatestaticArrayList<ABox>aboxes=newArrayList<ABox>();* 产生方块对象* /static/*其中包含4个点.都是相对坐标.第一个坐