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写的俄罗斯方块_传智播客汤阳光的PPT资料_Itcast_tetris

北京传智播客教育
—高级软件人才实作培训专家! 高级软件人才实作培训专家!
基本概念: 怎么表示图形, 障碍物
x 坐标
0 0 1
y 坐 标
(0, 0)
1
(1, 0)
2
3
4
5
6
7
8
(0, 1) (2, 2) (3, 2) (3, 3)
障碍物
2 3 4 5
(4, 3)
障碍物 障碍物
(2, 2)
(3, 2) (3, 3)
障碍物
(4, 3)
障碍物
障碍物
障碍物
北京传智播客教育
—高级软件人才实作培训专家! 高级软件人才实作培训专家!
通过事件监听建立联系(完善后)
Controller
触发按键事件 处理按键事件
事件源
GamePanel
Shape
定时下落
事件源
事件源
GamePanel
Shape
定时下落
事件源
下落后,触发事件 shapeMovedDown
状态改变 需要重新显示
重新显示
ShapeListener
北京传智播客教育
—高级软件人才实作培训专家! 高级软件人才实作培训专家!
ShapeListener
ShapeListener : void shapeMovedDown(Shape);
下落前, 询问一下 是否可以下落
isShapeMoveDownable
处理 isShapeMoveDownable 事件(问Ground, 返回结果)
(处理完事件后 需要重新显示)
重新显示
事件源
下落后,触发事件 shapeMoveDown
俄罗斯方块完整源代码

//不多说,直接可以拷贝下面的东西,就可以运行。
package day04;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class ERSBlock extends JPanel implements ActionListener,KeyListener//应该是继承JPanel{static Button but[] = new Button[6];static Button noStop = new Button("取消暂停"); static Label scoreLab = new Label("分数:");static Label infoLab = new Label("提示:");static Label speedLab = new Label("级数:");static Label scoreTex = new Label("0");static Label infoTex = new Label(" ");static Label speedTex = new Label("1");static JFrame jf = new JFrame();static MyTimer timer;static ImageIcon icon=new ImageIcon("resource/Block.jpg");static JMenuBar mb = new JMenuBar();static JMenu menu0 = new JMenu("游戏 ");static JMenu menu1 = new JMenu("帮助 ");static JMenuItem mi0 = new JMenuItem("新游戏"); static JMenuItem mi1 = new JMenuItem("退出");static JMenuItem mi1_0 = new JMenuItem("关于"); static JDialog dlg_1;static JTextArea dlg_1_text = new JTextArea(); static int startSign= 0;//游戏开始标志 0 未开始 1 开始 2 暂停static String butLab[] = {"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};static int game_body[][] = new int[19][10];static int game_sign_x[] = new int[4];//用于记录4个方格的水平位置static int game_sign_y[] = new int[4];//用于记录4个方格的垂直位置static boolean downSign = false;//是否落下static int blockNumber = 1;//砖块的编号static int gameScore = 0;//游戏分数static int speedMark = 1;public static void main(String args[]) {ERSBlock myBlock = new ERSBlock();mb.add(menu0);mb.add(menu1);menu0.add(mi0);menu0.add(mi1);menu1.add(mi1_0);jf.setJMenuBar(mb);myBlock.init();jf.add(myBlock);jf.setSize(565,501);jf.setResizable(false);jf.setTitle("俄罗斯方块");jf.setIconImage(icon.getImage());jf.setLocation(200,100);jf.show();timer = new MyTimer(myBlock); //启动线程timer.setDaemon(true);timer.start();timer.suspend();}public void init(){setLayout(null);for(int i = 0;i < 6;i++){but[i] = new Button(butLab[i]);add(but[i]);but[i].addActionListener(this);but[i].addKeyListener(this);but[i].setBounds(360,(240 + 30 * i),160,25); }add(scoreLab);add(scoreTex);add(speedLab);add(speedTex);add(infoLab);add(infoTex);add(scoreLab);scoreLab.setBounds(320,15,30,20); scoreTex.setBounds(360,15,160,20); scoreTex.setBackground(Color.white); speedLab.setBounds(320,45,30,20); speedTex.setBounds(360,45,160,20); speedTex.setBackground(Color.white);but[1].setEnabled(false);but[4].setEnabled(false);infoLab.setBounds(320,75,30,20); infoTex.setBounds(360,75,160,20); infoTex.setBackground(Color.white); noStop.setBounds(360,360,160,25); noStop.addActionListener(this); noStop.addKeyListener(this);mi0.addActionListener(this);mi1.addActionListener(this);mi1_0.addActionListener(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if(e.getSource() == but[0])//开始游戏{startSign = 1;infoTex.setText("游戏已经开始!");but[0].setEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);timer.resume();}if(e.getSource() == but[1]||e.getSource() == mi0)//重新开始游戏{startSign = 0;gameScore = 0;timer.suspend();num_csh_restart();repaint();rand_block();scoreTex.setText("0");infoTex.setText("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource() == but[2])//降低级数 {infoTex.setText("降低级数!"); speedMark--;if(speedMark <= 1){speedMark = 1;infoTex.setText("已经是最低级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[3])//提高级数 {infoTex.setText("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;infoTex.setText("已经是最高级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[4])//游戏暂停 {this.add(noStop);this.remove(but[4]);infoTex.setText("游戏暂停!"); timer.suspend();}if(e.getSource() == noStop)//取消暂停 {this.remove(noStop);this.add(but[4]);infoTex.setText("继续游戏!"); timer.resume();}if(e.getSource() == but[5]||e.getSource() == mi1)//退出游戏{jf.dispose();}if(e.getSource() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/guanyu.txt");//得到路径byte a[] = new byte[io.available()];io.read(a);io.close();String str = new String(a);dlg_1_text.setText(str);}catch(Exception g){}dlg_1_text.setEditable(false);dlg_1.add(dlg_1_text);dlg_1.pack();dlg_1.setResizable(false);dlg_1.setSize(200, 120);dlg_1.setLocation(400, 240);dlg_1.show();}}public void rand_block()//随机产生砖块{int num;num = (int)(Math.random() * 6) + 1;//产生0~6之间的随机数blockNumber = num;switch(blockNumber){case 1: block1(); blockNumber = 1; break;case 2: block2(); blockNumber = 2; break;case 3: block3(); blockNumber = 3; break;case 4: block4(); blockNumber = 4; break;case 5: block5(); blockNumber = 5; break;case 6: block6(); blockNumber = 6; break;case 7: block7(); blockNumber = 7; break;}}public void change_body(int blockNumber)//改变砖块状态{dingwei();if(blockNumber == 1&&downSign == false)//变换长条2种情况{if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 16)//说明长条是横着的{if(game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] != 2){num_csh_game();game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] >= 1&&game_sign_x[3] <= 7)//说明长条是竖着的{if(game_body[game_sign_y[0] +1][game_sign_x[0]-1] != 2&&game_body[game_sign_y[3] -2][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]]=1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 3&&downSign == false)//变换转弯1有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] >= 1){if(game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;= 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[1] == game_sign_x[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[3] <= 8){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1]= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] == game_sign_x[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 4&&downSign == false)//变换转弯2有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[3] <= 7){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[1] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[2]) {if(game_body[game_sign_y[1]][game_sign_x[1] + 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0]] = 1;game_body[game_sign_y[1]][game_sign_x[1] + 2] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[0] == game_sign_y[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] - 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2] - 2] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 5&&downSign == false)//变换转弯3有4种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[2] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[1] >= 2){if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[1]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[2] == game_sign_y[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] +2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2]][game_sign_x[2] + 2] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[2] == game_sign_x[3]){if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 6&&downSign == false)//变换两层砖块1的2种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] -1 ] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 7&&downSign == false)//变换两层砖块2的2种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] <= 16){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[2] <= 17)if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}}public void num_csh_game()//数组清零for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){game_body[i][j] = 2;}else{game_body[i][j] = 0;}}}}public void num_csh_restart()//重新开始时数组清零 {for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++)game_body[i][j] = 0;}}}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(e.getKeyCode() == KeyEvent.VK_DOWN&&startSign == 1)//处理下键{this.down();}if(e.getKeyCode() == KeyEvent.VK_LEFT&&startSign == 1)//处理左键{this.left();}if(e.getKeyCode() == KeyEvent.VK_RIGHT&&startSign== 1)//处理右键{this.right();}if(e.getKeyCode() == KeyEvent.VK_UP&&startSign== 1)//处理上键转换{this.change_body(blockNumber);}if(startSign == 0){infoTex.setText("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){g.setColor(Color.black);g.fill3DRect(0,0,300,450,true);for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){g.setColor(Color.blue);g.fill3DRect(30*j,30*(i-4),30,30,true); }if(game_body[i][j] == 2){g.setColor(Color.magenta);g.fill3DRect(30*j,30*(i-4),30,30,true); }}}}public void left()//向左移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 0||game_body[game_sign_y[k]][game_sign_x[k] - 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] - 1] = 1; }infoTex.setText("向左移动!");repaint();}}public void right()//向右移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 9||game_body[game_sign_y[k]][game_sign_x[k] + 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] + 1] = 1; }infoTex.setText("向右移动!");repaint();}}public void down()//下落{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_y[k] == 18||game_body[game_sign_y[k] + 1][game_sign_x[k]] == 2){sign = 1;downSign = true;changeColor();cancelDW();getScore();if(game_over() == false){rand_block();repaint();}}}if(sign == 0){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k] + 1][game_sign_x[k]] = 1;}infoTex.setText("游戏进行中!");repaint();}}public boolean game_over()//判断游戏是否结束{int sign=0;for(int i = 0;i < 10;i++){if(game_body[4][i] == 2){sign = 1;}}if(sign == 1){infoTex.setText("游戏结束!");changeColor();repaint();startSign = 0;timer.suspend();return true;}elsereturn false;}public void getScore()//满行消除方法{for(int i = 0;i < 19;i++){int sign = 0;for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){sign++;}}if(sign == 10){gameScore += 100;scoreTex.setText(gameScore+"");infoTex.setText("恭喜得分!");for(int j = i;j >= 1;j--){for(int k = 0;k < 10;k++){game_body[j][k] = game_body[j - 1][k];}}}}}public void changeColor()//给已经落下的块换色{downSign = false;for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k]] = 2; }}public void dingwei()//确定其位置{int k = 0;cancelDW();for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){game_sign_x[k] = j;game_sign_y[k] = i;k++;}}}}public void cancelDW()//将定位数组初始化{for(int k = 0;k < 4;k++){game_sign_x[k] = 0;game_sign_y[k] = 0;}}public void block1()//长条{game_body[0][4] = 1;game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block2()//正方形{game_body[3][4] = 1;game_body[3][5] = 1;game_body[2][5] = 1;}public void block3()//3加1(下) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[3][5] = 1;}public void block4()//3加1(中) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[2][5] = 1;}public void block5()//3加1(上) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[1][5] = 1;}public void block6()//转折1 {game_body[1][5] = 1;game_body[2][5] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block7()//转折2 {game_body[1][4] = 1;game_body[2][4] = 1;game_body[2][5] = 1;game_body[3][5] = 1;}}//定时线程class MyTimer extends Thread {ERSBlock myBlock;public MyTimer(ERSBlock myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。
基于Java的俄罗斯方块的设计和实现(含源文件)

姓 名
学号
专 业
指导教师
摘 要
俄罗斯方块作为一款风靡全球的多样化终端游戏,经久不衰。俄罗斯方块简单的基本游戏规则是旋转、移动,游戏自动随机输出7种形状的方块,经旋转后可形成28种形状,方块堆叠在一起,排列成完整的一行或多行消除得分,积分达到一定程度会自动提升级别。该游戏上手简单、老少皆宜、家喻户晓。
2 系统的
对系统的需求分析就是用户和开发人员在“系统必须做什么”这个问题上实现相互理解,达到共识,从而形成双方认可的软件产品的需求规格。这样有利于提高软件开发过程中的能见度,便于对软件开发过程的控制与管理,便于采用工程化的模式开发软件,从而达到提高软件的质量,为开发人员、维护人员、管理人员之间的交流、协作提供便捷。作为工作成果的原始依据,系统的需求分析可以向潜在用户传递软件功能、性能的需求,使其能够判断该软件是否符合自己的需求。
游戏形状需求:用数组作为存储方块28种状态的数据结构,即长条形、Z字形、反Z形、田字形、7字形、反7形、T字型一共7种形状的向4个方向的旋转变形,各个方块要能实现它的任意变形,可设为顺时针变形或逆时针变形,一般为逆时针变形。方块的可否翻转需要加以判断,以防止其翻转越界。
键盘处理事件需求:方块下落时,可通过键盘方向键(上键、下键、左键、右键)或字母键I、K、J、L对下落方块进行向上(旋转变形)、向下(加速下落)、向左移动、向右移动。
鼠标处理事件需求:通过点击菜单栏中相应的菜单项或控制面板内的按钮,可以实现游戏的开始、结束、暂停、继续、提高等级、降低等级,预显方块形状的显示,分数、等级的显示,以及游戏帮助、颜色变换等功能。
显示需求:当方块填满一行时可以消行,剩余未填满的行逐次向下移动并统计分数。当达到一定分数的时候,会增加相应的等级。当方块充满主界面的每一行,方块不能再下落时,提示“Game Over”的字样。
俄罗斯方块java代码6

=================1======================package russia;/** 控制面板类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class ControlPanel extends JPanel{private TipBlockPanel tipBlockPanel;private JPanel tipPanel,InfoPanel,buttonPanel;private final JTextField levelField,scoreField;private JButton playButton,pauseButton,stopButton,turnHarderButton,turnEasilyButton;private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;private RussiaBlocksGame game;private Timer timer;public ControlPanel(final RussiaBlocksGame game){this.game = game;/**图形界面部分*/setLayout(new GridLayout(3,1,0,4));tipBlockPanel = new TipBlockPanel();tipPanel = new JPanel( new BorderLayout() );tipPanel.add( new JLabel("Next Block:") , BorderLayout.NORTH );tipPanel.add( tipBlockPanel , BorderLayout.CENTER );tipPanel.setBorder(border);InfoPanel = new JPanel( new GridLayout(4,1,0,0) );levelField = new JTextField(""+RussiaBlocksGame.DEFAULT_LEVEL);levelField.setEditable(false);scoreField = new JTextField("0");scoreField.setEditable(false);InfoPanel.add(new JLabel("Level:"));InfoPanel.add(levelField);InfoPanel.add(new JLabel("Score:"));InfoPanel.add(scoreField);InfoPanel.setBorder(border);buttonPanel = new JPanel(new GridLayout(5,1,0,0));playButton = new JButton("Play");pauseButton = new JButton("Pause");stopButton = new JButton("Stop");turnHarderButton = new JButton("Turn harder"); turnEasilyButton = new JButton("Turn easily");buttonPanel.add(playButton);buttonPanel.add(pauseButton);buttonPanel.add(stopButton);buttonPanel.add(turnHarderButton);buttonPanel.add(turnEasilyButton);buttonPanel.setBorder(border);addKeyListener(new ControlKeyListener());//添加add(tipPanel);add(InfoPanel);add(buttonPanel);/**添加事件监听器*/playButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){game.playGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});pauseButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){if(pauseButton.getText().equals("Pause"))game.pauseGame();elsegame.resumeGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});stopButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){game.stopGame();requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});turnHarderButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){int level = 0;try{level = Integer.parseInt(levelField.getText());setLevel(level + 1);}catch(NumberFormatException e){e.printStackTrace();}requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});turnEasilyButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){int level = 0;try{level = Integer.parseInt(levelField.getText());setLevel(level - 1);}catch(NumberFormatException e){e.printStackTrace();}requestFocus();//让ControlPanel重新获得焦点以响应键盘事件}});/** 时间驱动程序,每格500毫秒对level,score值进行更新*/timer = new Timer(500,new ActionListener(){public void actionPerformed(ActionEvent event){scoreField.setText(""+game.getScore());game.levelUpdate();}});timer.start();}/** 设置预显方块的样式*/public void setBlockStyle(int style){tipBlockPanel.setStyle(style);tipBlockPanel.repaint();}/** 重置,将所有数据恢复到最初值*/public void reset(){levelField.setText(""+RussiaBlocksGame.DEFAULT_LEVEL); scoreField.setText("0");setPlayButtonEnabled(true);setPauseButtonLabel(true);tipBlockPanel.setStyle(0);}/**设置playButton是否可用*/public void setPlayButtonEnabled(boolean enable){playButton.setEnabled(enable);/**设置pauseButton的文本*/public void setPauseButtonLabel(boolean pause){pauseButton.setText( pause ? "Pause" : "Rusume" );}/**设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸*/public void fanning(){tipBlockPanel.fanning();}/**根据level文本域的值返回当前的级别*/public int getLevel(){int level = 0;try{level=Integer.parseInt(levelField.getText());}catch(NumberFormatException e){e.printStackTrace();}return level;}/** 设置level文本域的值*/public void setLevel(int level){if(level > 0 && level <= RussiaBlocksGame.MAX_LEVEL) levelField.setText("" + level);}/** 内部类为预显方块的显示区域*/private class TipBlockPanel extends JPanel{private Color bgColor = Color.darkGray,blockColor = Color.lightGray;private RussiaBox [][]boxes = new RussiaBox[RussiaBlock.ROWS][RussiaBlock.COLS]; private int boxWidth, boxHeight,style;private boolean isTiled = false;/** 构造函数*/public TipBlockPanel(){for(int i = 0; i < boxes.length; i ++)for(int j = 0; j < boxes[i].length; j ++){boxes[i][j]=new RussiaBox(false);}style = 0x0000;}/** 构造函数*/public TipBlockPanel(Color bgColor, Color blockColor){this();this.bgColor = bgColor;this.blockColor = blockColor;}/** 设置方块的风格*/public void setStyle(int style){this.style = style;repaint();}/** 绘制预显方块*/public void paintComponent(Graphics g){super.paintComponent(g);int key = 0x8000;if(!isTiled)fanning();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j<boxes[i].length ;j ++){Color color = (style & key) != 0 ? blockColor : bgColor;g.setColor(color);g.fill3DRect(j * boxWidth, i * boxHeight, boxWidth, boxHeight, true);key >>=1;}}/**设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸*/public void fanning(){boxWidth = getSize().width / RussiaBlock.COLS;boxHeight = getSize().height /RussiaBlock.ROWS;isTiled=true;}}/**内部类键盘键听器,响应键盘事件*/class ControlKeyListener extends KeyAdapter {public void keyPressed(KeyEvent ke){if (!game.isPlaying()) return;RussiaBlock block = game.getCurBlock();switch (ke.getKeyCode()) {case KeyEvent.VK_DOWN:block.moveDown();break;case KeyEvent.VK_LEFT:block.moveLeft();break;case KeyEvent.VK_RIGHT:block.moveRight();break;case KeyEvent.VK_UP:block.turnNext();break;case KeyEvent.VK_SPACE://一键到底while(block.moveDown()){}break;default:break;}}}}=================2=================================== package russia;/** 游戏中方块显示的画布类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class GameCanvas extends JPanel{private RussiaBox [][]boxes;private int rows = 20 , cols = 12;private static GameCanvas canvas=null;private int boxWidth, boxHeight;//默认为零需要调用fanning函数设置private Color blockColor = Color.RED, bgColor = new Color(0,204,204);private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;/**采用单件模式,构造函数私有*/private GameCanvas(){boxes = new RussiaBox[rows][cols];for(int i = 0; i < boxes.length; i ++)for(int j = 0; j<boxes[i].length; j ++)boxes[i][j] = new RussiaBox(false);setBorder(border);}/**获得GameCanvas实例*/public static GameCanvas getCanvasInstance(){if(canvas == null)canvas = new GameCanvas();return canvas;}/**设置画布的背景色*/public void setBgColor(Color bgColor){this.bgColor = bgColor;}/** 获得画布的背景色*/public Color getBgColor(){return bgColor;}/**设置方块的颜色*/public void setBlockColor(Color blockColor) {this.blockColor = blockColor;}/**方块的颜色*/public Color getBlockColor(){return blockColor;}/**设置画布中方块的行数*/public void setRows(int rows){this.rows = rows;}/**得到画布中方块的行数*/public int getRows(){return rows;}/**设置画布中方块的列数*/public void setCols(int cols){this.cols = cols;}/**得到画布中方块的列数*/public int getCols(){return cols;}/**得到row行,col列的方格*/public RussiaBox getBox(int row, int col){if(row >= 0 && row < rows && col >= 0 && col < cols)return boxes[row][col];elsereturn null;}/**在画布中绘制方块*/public void paintComponent(Graphics g){super.paintComponent(g);fanning();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j < boxes[i].length; j ++){Color color = boxes[i][j].isColorBox() ? blockColor : bgColor;g.setColor(color);g.fill3DRect(j * boxWidth, i * boxHeight , boxWidth , boxHeight , true);}}/**清除第row行*/public void removeLine(int row){for(int i = row; i > 0; i --)for(int j = 0; j < cols; j ++){boxes[i][j] = (RussiaBox)boxes[i-1][j].clone();}}/**重置为初始时的状态*/public void reset(){for(int i = 0; i < boxes.length; i++)for(int j = 0 ;j < boxes[i].length; j++){boxes[i][j].setColor(false);}repaint();}/** 根据窗体的大小自动调整方格的大小*/public void fanning(){boxWidth = getSize().width / cols;boxHeight = getSize().height / rows;}}====================3======================= package russia;/** 方块类*/public class RussiaBlock extends Thread{private int style,y,x,level;private boolean moving,pausing;private RussiaBox boxes[][];private GameCanvas canvas;public final static int ROWS = 4;public final static int COLS = 4;public final static int BLOCK_KIND_NUMBER = 7; public final static int BLOCK_STATUS_NUMBER = 4; public final static int BETWEEN_LEVELS_TIME = 50; public final static int LEVEL_FLATNESS_GENE = 3;/**方块的所有风格及其不同的状态*/public final static int[][] STYLES = {// 共28种状态{0x0f00, 0x4444, 0x0f00, 0x4444}, // 长条型的四种状态{0x04e0, 0x0464, 0x00e4, 0x04c4}, // 'T'型的四种状态{0x4620, 0x6c00, 0x4620, 0x6c00}, // 反'Z'型的四种状态{0x2640, 0xc600, 0x2640, 0xc600}, // 'Z'型的四种状态{0x6220, 0x1700, 0x2230, 0x0740}, // '7'型的四种状态{0x6440, 0x0e20, 0x44c0, 0x8e00}, // 反'7'型的四种状态{0x0660, 0x0660, 0x0660, 0x0660}, // 方块的四种状态};/**构造函数*/public RussiaBlock(int y,int x,int level,int style){this.y = y;this.x = x;this.level = level;moving = true;pausing = false;this.style = style;canvas = GameCanvas.getCanvasInstance();boxes = new RussiaBox[ROWS][COLS];int key = 0x8000;for(int i = 0; i < boxes.length; i++)for(int j = 0; j < boxes[i].length; j++){boolean isColor = ( (style & key) != 0 );boxes[i][j] = new RussiaBox(isColor);key >>= 1;}display();}/**线程的run方法控制放块的下落及下落速度*/public void run(){while(moving){try{sleep( BETWEEN_LEVELS_TIME * (RussiaBlocksGame.MAX_LEVEL - level + LEVEL_FLATNESS_GENE) );if(!pausing)moving = ( moveTo(y + 1,x) && moving );}catch(InterruptedException e){e.printStackTrace();}}}/**暂停移动*/public void pauseMove(){pausing = true;}/**从暂停状态恢复*/public void resumeMove(){pausing = false;}/**停止移动*/public void stopMove(){moving = false;}/**向左移一格*/public void moveLeft(){moveTo(y , x - 1);}/**向右移一格*/public void moveRight(){moveTo(y , x + 1);}/**向下移一格,返回与其他几个不同,为了一键到底*/public boolean moveDown(){if(moveTo(y + 1, x))return true;elsereturn false;}/**移到newRow,newCol位置*/public synchronized boolean moveTo(int newRow, int newCol){//erase();//必须在判断前进行擦除,否则isMoveable将产生错误行为if(!moving || !isMoveable(newRow,newCol)){display();return false;}y = newRow;x = newCol;display();canvas.repaint();return true;}/**判断能否移到newRow,newCol位置*/private boolean isMoveable(int newRow, int newCol){erase();for(int i = 0; i < boxes.length; i ++)for(int j = 0; j< boxes[i].length; j ++ ){if( boxes[i][j].isColorBox() ){RussiaBox box = canvas.getBox(newRow + i, newCol + j);if(box == null || box.isColorBox())return false;}}return true;/**通过旋转变为下一种状态*/public void turnNext(){int newStyle = 0;for(int i = 0; i < STYLES.length; i ++)for(int j = 0 ;j < STYLES[i].length; j++){if(style == STYLES[i][j]){newStyle = STYLES[i][(j + 1)%BLOCK_STATUS_NUMBER];break;}}turnTo(newStyle);}/**通过旋转变能否变为newStyle状态*/private synchronized boolean turnTo(int newStyle){//erase();//擦除之后在判断isTurnNextAbleif(!moving || !isTurnable(newStyle)){display();return false;}style=newStyle;int key = 0x8000;for(int i = 0; i < boxes.length; i ++)for(int j = 0 ;j < boxes[i].length; j++){boolean isColor = ((key & style) != 0 );boxes[i][j].setColor(isColor);key >>=1;}display();canvas.repaint();return true;}*判断通过旋转能否变为下一种状态*/private boolean isTurnable(int newStyle){erase();int key = 0x8000;for(int i = 0; i< boxes.length; i++)for(int j=0; j<boxes[i].length; j++){if((key & newStyle) != 0){RussiaBox box = canvas.getBox(y + i, x + j);if(box == null || box.isColorBox())return false;}key >>= 1;}return true;}/**擦除当前方块(只是设置isColor属性,颜色并没有清除,为了判断能否移动之用) */private void erase(){for(int i = 0; i < boxes.length; i ++)for(int j = 0; j< boxes[i].length; j ++ ){if( boxes[i][j].isColorBox() ){RussiaBox box = canvas.getBox( y + i, x + j);if(box != null)box.setColor(false);}}}/**显示当前方块(其实只是设置Color属性,在调用repaint方法时才真正显示)*/private void display(){for(int i = 0; i < boxes.length; i ++)for(int j = 0;j< boxes[i].length ; j ++){if(boxes[i][j].isColorBox()){RussiaBox box = canvas.getBox( y + i, x + j);if(box != null)box.setColor( true );}}}}===========================4=================package russia;/** 主游戏类*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class RussiaBlocksGame extends JFrame{public final static int PER_LINE_SCORE = 100;//消去一行得分public final static int PER_LEVEL_SCORE = PER_LINE_SCORE*20;//升一级需要的分数public final static int DEFAULT_LEVEL = 5;//默认级别public final static int MAX_LEVEL = 10;//最高级别private int score=0,curLevelScore = 0;//总分和本级得分private GameCanvas canvas;private ControlPanel controlPanel;private RussiaBlock block;private int style = 0;boolean playing = false;private JMenuBar bar;private JMenu gameMenu,controlMenu,windowStyleMenu,informationMenu;private JMenuItem newGameItem,setBlockColorItem,setBgColorItem,turnHardItem,turnEasyItem,exitItem;private JMenuItem playItem,pauseItem,resumeItem,stopItem;private JRadioButtonMenuItem windowsRadioItem,motifRadioItem,metalRadioItem;private JMenuItem authorItem,helpItem;private ButtonGroup buttonGroup;/** 构造函数public RussiaBlocksGame(String title){super(title);setSize(300,400);Dimension scrSize=Toolkit.getDefaultToolkit().getScreenSize();setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);createMenu();Container container=getContentPane();container.setLayout(new BorderLayout());canvas = GameCanvas.getCanvasInstance();controlPanel = new ControlPanel(this);container.add(canvas,BorderLayout.CENTER);container.add(controlPanel,BorderLayout.EAST);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent event){stopGame();System.exit(0);}});addComponentListener(new ComponentAdapter(){public void componentResized(ComponentEvent event){canvas.fanning();}});canvas.fanning();setVisible(true);}/** 判断游戏是否正在进行public boolean isPlaying(){return playing;}/** 开始游戏并设置按钮和菜单项的可用性*/public void playGame(){play();controlPanel.setPlayButtonEnabled(false); playItem.setEnabled(false);}/** 暂停游戏*/public void pauseGame(){if(block != null) block.pauseMove(); controlPanel.setPauseButtonLabel(false); pauseItem.setEnabled(false); resumeItem.setEnabled(true);}/** 从暂停中恢复游戏*/public void resumeGame(){if(block != null) block.resumeMove(); controlPanel.setPauseButtonLabel(true); pauseItem.setEnabled(true); resumeItem.setEnabled(false);}/** 停止游戏*/public void stopGame(){if(block != null) block.stopMove(); playing = false;controlPanel.setPlayButtonEnabled(true); controlPanel.setPauseButtonLabel(true);playItem.setEnabled(true);}/** 得到当前级别*/public int getLevel(){return controlPanel.getLevel();}/** 设置当前级别,并更新控制面板的显示*/public void setLevel(int level){if(level>0&&level<11)controlPanel.setLevel(level);}/** 得到当前总分数*/public int getScore(){if(canvas != null)return score;return 0;}/** 得到本级得分*/public int getCurLevelScore(){if(canvas != null)return curLevelScore;return 0;}/** 更新等级*/public void levelUpdate(){int curLevel = getLevel();if(curLevel < MAX_LEVEL && curLevelScore >= PER_LEVEL_SCORE) {setLevel(curLevel + 1);curLevelScore -= PER_LEVEL_SCORE;}}/** 获得当前得方块*/public RussiaBlock getCurBlock() {return block;}/** 开始游戏*/private void play(){playing=true;Thread thread = new Thread(new Game());thread.start();reset();}/** 重置*/private void reset(){controlPanel.reset();canvas.reset();score = 0;curLevelScore = 0;}/** 宣告游戏结束*/private void reportGameOver(){JOptionPane.showMessageDialog(this,"Game over!");}/** 创建菜单*/private void createMenu(){gameMenu = new JMenu("Game");newGameItem = new JMenuItem("New Game"); setBlockColorItem = new JMenuItem("Set Block Color..."); setBgColorItem = new JMenuItem("Set BackGround Color...");turnHardItem = new JMenuItem("Turn Harder"); turnEasyItem = new JMenuItem("Turn Easily");exitItem = new JMenuItem("Exit");gameMenu.add(newGameItem);gameMenu.add(setBlockColorItem);gameMenu.add(setBgColorItem);gameMenu.add(turnHardItem);gameMenu.add(turnEasyItem);gameMenu.add(exitItem);controlMenu = new JMenu("Control");playItem = new JMenuItem("Play");pauseItem = new JMenuItem("Pause");resumeItem = new JMenuItem("Resume");stopItem = new JMenuItem("Stop");controlMenu.add(playItem);controlMenu.add(pauseItem);controlMenu.add(resumeItem);controlMenu.add(stopItem);windowStyleMenu = new JMenu("WindowStyle"); buttonGroup = new ButtonGroup();windowsRadioItem = new JRadioButtonMenuItem("Windows"); motifRadioItem = new JRadioButtonMenuItem("Motif"); metalRadioItem = new JRadioButtonMenuItem("Mentel",true); windowStyleMenu.add(windowsRadioItem);buttonGroup.add(windowsRadioItem); windowStyleMenu.add(motifRadioItem);buttonGroup.add(motifRadioItem);windowStyleMenu.add(metalRadioItem);buttonGroup.add(metalRadioItem);informationMenu = new JMenu("Information");authorItem = new JMenuItem("Author:Fuliang");helpItem = new JMenuItem("Help");informationMenu.add(authorItem);informationMenu.add(helpItem);bar = new JMenuBar();bar.add(gameMenu);bar.add(controlMenu);bar.add(windowStyleMenu);bar.add(informationMenu);addActionListenerToMenu();setJMenuBar(bar);}/** 添加菜单响应*/private void addActionListenerToMenu(){newGameItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {stopGame();reset();setLevel(DEFAULT_LEVEL);}});setBlockColorItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {Color newBlockColor =JColorChooser.showDialog(RussiaBlocksGame.this,"Set color for block", canvas.getBlockColor());if (newBlockColor != null)canvas.setBlockColor(newBlockColor);}});setBgColorItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {Color newBgColor =JColorChooser.showDialog(RussiaBlocksGame.this,"Set color for block",canvas.getBgColor());if (newBgColor != null)canvas.setBgColor(newBgColor);}});turnHardItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {int curLevel = getLevel();if (curLevel < MAX_LEVEL) setLevel(curLevel + 1);}});turnEasyItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {int curLevel = getLevel();if (curLevel > 1) setLevel(curLevel - 1);}});exitItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {System.exit(0);}});playItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {playGame();}});pauseItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {pauseGame();}});resumeItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {resumeGame();}});stopItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {stopGame();}});windowsRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();}});motifRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();;}});metalRadioItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent ae) {String plaf = "javax.swing.plaf.metal.MetalLookAndFeel";setWindowStyle(plaf);canvas.fanning();controlPanel.fanning();}});}/** 设定窗口风格*/private void setWindowStyle(String plaf){try {UIManager.setLookAndFeel(plaf);SwingUtilities.updateComponentTreeUI(this);} catch (Exception e) {e.printStackTrace();}}private class Game implements Runnable{/** (non-Javadoc)* @see ng.Runnable#run()* 游戏线程的run函数*/public void run(){int col=(int)(Math.random()*(canvas.getCols()-3));style=RussiaBlock.STYLES[(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER)][(int)(Math.random()*RussiaBlock.BLOCK_STATUS_NUMBER)];while (playing) {if (block != null) { //第一次循环时,block为空if (block.isAlive()) {try {Thread.sleep(100);} catch (InterruptedException ie) {ie.printStackTrace();}continue;}}checkFullLine();if (isGameOver()) { //检查游戏是否应该结束了playItem.setEnabled(true);pauseItem.setEnabled(true);resumeItem.setEnabled(false);controlPanel.setPlayButtonEnabled(true);controlPanel.setPauseButtonLabel(true);reportGameOver();return;}block = new RussiaBlock(-1, col, getLevel(),style);block.start();col=(int)(Math.random()*(canvas.getCols()-3));style=RussiaBlock.STYLES[(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER)][(int )(Math.random()*RussiaBlock.BLOCK_STATUS_NUMBER)];controlPanel.setBlockStyle(style);}}/** 判断是否能消去整行*/public void checkFullLine(){for (int i = 0; i < canvas.getRows(); i++) {int row = -1;boolean fullLineColorBox = true;for (int j = 0; j < canvas.getCols(); j++) {if (!canvas.getBox(i, j).isColorBox()) {fullLineColorBox = false;break;}}if (fullLineColorBox) {curLevelScore += PER_LINE_SCORE;score += PER_LINE_SCORE;row = i--;canvas.removeLine(row);}}}/** 判断游戏是否结束*/private boolean isGameOver() {for (int i = 0; i < canvas.getCols(); i++) {RussiaBox box = canvas.getBox(0, i);if (box.isColorBox()) return true;}return false;}}public static void main(String[] args){new RussiaBlocksGame("Russia Blocks Game");}}========================5=================== package russia;/**虚拟的单个方格类,控制方格的颜色*/public class RussiaBox implements Cloneable{private boolean isColor;public RussiaBox(boolean isColor){this.isColor = isColor;}/**设置颜色*/public void setColor(boolean isColor) {this.isColor=isColor;}/**返回颜色*/public boolean isColorBox(){return isColor;}/** @see ng.Object#clone()*/public Object clone(){Object o = null;try{o=super.clone();}catch(CloneNotSupportedException e) {e.printStackTrace();}return o;}}。
俄罗斯方块程序代码

//包含头文件#include<stdio.h>#include<Windows.h>#include<conio.h>#include<graphics.h>#include<time.h>#include "Tetris.h"//int score=0;//int lever=1;//char scores[10];//char levers[10];/*enum cmd{round, //旋转方块left, //左移方块right, //右移方块down, //下一方块bottom, //方块沉底quit //离开游戏};//定义绘制方块的状态的枚举类型enum draw{show, //显示方块hide //抹掉方块};//定义俄罗斯方块的结构体struct block{int dir[4]; //方块的四个旋转的状态int color; //方块的颜色}*/static T_TrsBlockStyle gz_tBlockStyleTab[7] ={/* 口口口口口口口口口口口口口口口口*/{0x0F00, 0x4444, 0x0F00, 0x4444, RED},/*口口口口口口口口口口口口口口口口*/{0x0660, 0x0660, 0x0660, 0x0660, BLUE},/* 口口口口口口口口口口口口口口口口*/{0x4460, 0x02E0, 0x0622, 0x0740, MAGENTA},/* 口口口口口口口口口口口口口口口口*/{0x2260, 0x0E20, 0x0644, 0x0470, YELLOW},/* 口口口口口口口口口口口口口口口口*/{0x0C60, 0x2640, 0x0C60, 0x2640, CYAN},/* 口口口口口口口口口口口口口口口口*/{0x0360, 0x4620, 0x0360, 0x4620, GREEN},/* 口口口口口口口口口口口口口口口口*/{0x4E00, 0x4C40, 0x0E40, 0x4640, BROWN}};/*//定义俄罗斯方块的信息的结构体struct blockinfo{int id; //7中方块中的哪一种byte dir:2; //1种方块中四个方向中的哪个char x,y; //方块的坐标(不是屏幕中的而是自己设置的游戏区域中的)}curblock,nextblock;*/// 定义游戏区//unsigned char area[width][high] = {0};//函数声明bool TRS_AppCreate(void ** ppUser,void * pFunc);static void TRS_Init(void *pUser);static void TRS_DrawBackground(void *pUser);static void TRS_GameOver(void *pUser);static void TRS_Quit(void *pUser);static void TRS_ScoreShow(void *pUser);static void TRS_NewGame(void *pUser);static AEEEvent TRS_GetMsg(PCTetrisApp pMe);static bool TRS_TetrisHandle(void *pUser, DWORD evt, WORD w,DWORD dw);static void TRS_Newblock(void *pUser);static void TRS_DrawBlock(void *pUser,T_TrsBlockInfo tCurBlck,EDrawStyle eStyle);static bool TRS_Checkblock(void *pUser, T_TrsBlockInfo tCurBlck);static void TRS_HRound(void *pUser);static void TRS_HLeft(void *pUser);static void TRS_HRight(void *pUser);static void TRS_HDown(void *pUser);static void TRS_HBottom(void *pUser);/*------------------------------------------------------------------------------函数名称:main功能说明:主函数参数说明:作者:时间:-------------------------------------------------------------------------------*/void main(){PCTetrisApp pMe;AEEEvent eMsg;//init();TRS_AppCreate((void **)&pMe,NULL);/*while(true){scoreshow();c=getcmd();discmd(c);if (c == quit){HWND wnd = GetHWnd();if (MessageBox(wnd, _T("您要退出游戏吗?"), _T("提醒"), MB_OKCANCEL | MB_ICONQUESTION) == IDOK)Quit();}}*/}bool TRS_AppCreate(void ** ppUser,void * pFunc);{PCTetrisApp pMe;new(pMe);*ppUser = pMe;pMe->m_iScore=0;pMe->m_iLever=0;memset(pMe->m_iScores,0,sizeof(int)*10);memset(pMe->m_iLevers,0,sizeof(int)*10);for(iLoop = 0;iLoop <GSCRN_WIDTH_CL;iLoop++){for(jLoop=0;jLoop <GSCRN_HIGHT_CL;jLoop++){pMe->m_uiArea[iLoop][jLoop]=0;}}pMe->m_dwOldTime = 0;pMe->m_dwNewTime = 0;return true;}static bool TRS_TetrisHandle(void *pUser, DWORD evt, WORD w,DWORD dw) {switch(evt){case EVT_ROUND :TRS_HRound(pUser);break;case EVT_LEFT :TRS_HLeft(pUser);break;case EVT_RIGHT :TRS_HRight(pUser);break;case EVT_DOWN :TRS_HDown(pUser);break;case EVT_BOTTOM:TRS_HBottom(pUser);break;case EVT_QUIT :{HWND wnd = GetHWnd();if (MessageBox(wnd, _T("您要退出游戏吗?"), _T("提醒"), MB_OKCANCEL | MB_ICONQUESTION) == IDOK)TRS_Quit(pUser);}break;default:return false;}return true;}//初始化函数static void TRS_Init(void *pUser){PCTetrisApp pMe =(PCTetrisApp)pUser;initgraph(SCREEN_HIGHT,SCREEN_WIDTH); //初始化屏幕大小srand((unsigned)time(NULL)); //以当前时间作为随机种子TRS_NewGame();}static void TRS_DrawBackground(void *pUser);{PCTetrisApp pMe =(PCTetrisApp)pUser;setfont(TRS_GUIDE_FONT_SIZE,0,TRS_GUIDE_FONT_TYPE); //定义字体宋体,字高16,字宽比例自动适应outtextxy(TRS_OPERATION_TITLE_X,TRS_OPERATION_TITLE_Y,"操作提示:");outtextxy(TRS_MLEFT_X,TRS_MLEFT_Y,"a:左移");outtextxy(TRS_MRIGHT_X,TRS_MRIGHT_Y,"d:右移");outtextxy(TRS_MDOWN_X,TRS_MDOWN_Y,"s:下移");outtextxy(TRS_ROTATION_X,TRS_ROTATION_Y,"w:变形");outtextxy(TRS_MBOTTOM_X,TRS_MBOTTOM_Y,"空格:沉底");outtextxy(TRS_EXIT_X,TRS_EXIT_Y,"ESC:退出");setfont(50,0,"黑体");outtextxy(460,160,"Tetris");setfont(22,0,"宋体");outtextxy(20,20,"得分:");outtextxy(20,80,"等级:");setorigin(220,20); //设置坐标原点setfillstyle(WHITE); //设置填充颜色为白色//画游戏的边框bar3d(-21,-1,-6,GSCRN_HIGHT_CL * CELL_WIDTH,5,1);bar(-21,GSCRN_HIGHT_CL * CELL_WIDTH,GSCRN_WIDTH_CL * CELL_WIDTH,GSCRN_HIGHT_CL * CELL_WIDTH+20);bar3d(GSCRN_WIDTH_CL * CELL_WIDTH,-1,GSCRN_WIDTH_CL * CELL_WIDTH+15,GSCRN_HIGHT_CL * CELL_WIDTH+20,5,1);//画预览方块区域的边框rectangle((GSCRN_WIDTH_CL + 2) * CELL_WIDTH - 1, -1, (GSCRN_WIDTH_CL + 6) * CELL_WIDTH, 4 * CELL_WIDTH);}// 退出游戏static void TRS_Quit(void *pUser){PCTetrisApp pMe =(PCTetrisApp)pUser;closegraph();//释放应用空间free(pMe);exit(0);}// 结束游戏static void TRS_GameOver(void *pUser){HWND wnd = GetHWnd();if (MessageBox(wnd, _T("游戏结束。
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};}我们当然还要编写音乐播放类,资源播放类了等等。
JAVA俄罗斯方块程序代码
import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.*;import javax.swing.Timer;public class Tetris extends JFrame{public Tetris(){Tetrisblok a=new Tetrisblok();addKeyListener(a);add(a);}public static void main(String[]args){Tetris frame=new Tetris();JMenuBar menu=new JMenuBar();frame.setJMenuBar(menu);JMenu game=new JMenu("游戏");JMenuItem newgame=game.add("新游戏");JMenuItem pause=game.add("暂停");JMenuItem goon=game.add("继续");JMenuItem exit=game.add("退出");JMenu help=new JMenu("帮助");JMenuItem about=help.add("关于");menu.add(game);menu.add(help);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(220,275);frame.setTitle("Tetris内测版");//frame.setUndecorated(true);frame.setVisible(true);frame.setResizable(false);}}//创建一个俄罗斯方块类class Tetrisblok extends JPanel implements KeyListener{//blockType代表方块类型//turnState代表方块状态private int blockType;private int score=0;private int turnState;private int x;private int y;private int i=0;int j=0;int flag=0;//定义已经放下的方块x=0-11,y=0-21;int[][]map=new int[13][23];//方块的形状第一组代表方块类型有S、Z、L、J、I、O、T7种第二组代表旋转几次第三四组为方块矩阵private final int shapes[][][]=new int[][][]{//i{{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0}},//s{{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},//z{{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}},//j{{0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0}},//o{{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0}},//l{{1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}}, //t{{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0}}}; //生成新方块的方法public void newblock(){blockType=(int)(Math.random()*1000)%7;turnState=(int)(Math.random()*1000)%4;x=4;y=0;if(gameover(x,y)==1){newmap();drawwall();score=0;JOptionPane.showMessageDialog(null,"GAME OVER");}}//画围墙public void drawwall(){for(i=0;i<12;i++){map[i][21]=2;}for(j=0;j<22;j++){map[11][j]=2;map[0][j]=2;}}//初始化地图public void newmap(){for(i=0;i<12;i++){for(j=0;j<22;j++){map[i][j]=0;}}}//初始化构造方法Tetrisblok(){newblock();newmap();drawwall();Timer timer=new Timer(1000,new TimerListener());timer.start();}//旋转的方法public void turn(){int tempturnState=turnState;turnState=(turnState+1)%4;if(blow(x,y,blockType,turnState)==1){}if(blow(x,y,blockType,turnState)==0){turnState=tempturnState;}repaint();}//左移的方法public void left(){if(blow(x-1,y,blockType,turnState)==1){x=x-1;};repaint();}//右移的方法public void right(){if(blow(x+1,y,blockType,turnState)==1){x=x+1;};repaint();}//下落的方法public void down(){if(blow(x,y+1,blockType,turnState)==1){y=y+1;delline();};if(blow(x,y+1,blockType,turnState)==0){add(x,y,blockType,turnState);newblock();delline();};repaint();}//是否合法的方法public int blow(int x,int y,int blockType,int turnState){for(int a=0;a<4;a++){for(int b=0;b<4;b++){if(((shapes[blockType][turnState][a*4+b]==1)&&(map[x+b+1][y+a]==1))||((shapes[blockType][turnState][a*4+b]==1)&&(map[x+b+1][y+a]==2))){return0;}}}return1;}//消行的方法public void delline(){int c=0;for(int b=0;b<22;b++){for(int a=0;a<12;a++){if(map[a][b]==1){c=c+1;if(c==10){score+=10;for(int d=b;d>0;d--){for(int e=0;e<11;e++){map[e][d]=map[e][d-1];}}}}}c=0;}}//判断你挂的方法public int gameover(int x,int y){if(blow(x,y,blockType,turnState)==0){return1;}return0;}//把当前添加mappublic void add(int x,int y,int blockType,int turnState){int j=0;for(int a=0;a<4;a++){for(int b=0;b<4;b++){if(map[x+b+1][y+a]==0){map[x+b+1][y+a]=shapes[blockType][turnState][j];};j++;}}}//画方块的的方法public void paintComponent(Graphics g){super.paintComponent(g);//画当前方块for(j=0;j<16;j++){if(shapes[blockType][turnState][j]==1){g.fillRect((j%4+x+1)*10,(j/4+y)*10,10,10);}}//画已经固定的方块for(j=0;j<22;j++){for(i=0;i<12;i++){if(map[i][j]==1){g.fillRect(i*10,j*10,10,10);}if(map[i][j]==2){g.drawRect(i*10,j*10,10,10);}}}g.drawString("score="+score,125,10);g.drawString("抵制不良游戏,",125,50);g.drawString("拒绝盗版游戏。
Java编写的俄罗斯方块(小游戏)
for (i=0; i<xblocks; i++)
{
for (j=0; j<yblocks; j++)
{
screendata[i][j]=0;
}
ห้องสมุดไป่ตู้ }
score=0;
emptyline=-1;
int objectdx;
short objecttype;
short objectcolor;
int objectrotation;
int objectrotationd=0;
short objectptr;
short checkptr;
final short itemcount=7;
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
gameInit();
}
//初始化游戏
public void gameInit()
{
0,0, 1,0, 0,1, -1,1, // 被旋转180度
0,0, 0,-1, 1,0, 1,1, // 被旋转270度
0,0, 1,0, -1,0, 0,-1, // L形1,正常状态
0,0, 0,1, 0,-1, -1,0, // 被旋转90度
short screencount=40;
boolean showtitle=true;
int items[]={
0,0, -1,0, 0,-1, -1,-1, // 四方形, 正常状态
俄罗斯方块java代码
俄罗斯方块java代码俄罗斯方块是最经典的休闲益智游戏之一,现在很多人都不玩了,这里就来写一篇俄罗斯方块的Java代码。
首先,需要说明的是,Java代码中有两个类,一个是主类(Tetris.java),一个是方块类(Block.java)。
主类包含的功能是:显示游戏画面、游戏的主逻辑、处理键盘事件、以及控制游戏暂停、游戏结束等;方块类包含的功能是:初始化方块颜色、坐标、方向等,旋转方块。
那么我们来分析一下主类(Tetris.java)的代码。
首先是一些变量的定义:游戏区域的宽度和高度static final int Width = 10;static final int Height = 22;方块的颜色static Color blocksColor[] = {new Color(255, 255, 255), new Color(204, 102, 102),new Color(102, 204, 102), new Color(102, 102, 204),new Color(204, 204, 102), new Color(204, 102, 204),new Color(102, 204, 204), new Color(218, 170, 0) };游戏区域static int[][] wall = new int[Width][Height];当前方块static Block curBlock;下一个方块static Block nextBlock;游戏是否结束static boolean isOver;线程static MyThread t;接下来是一些初始化操作:初始化主窗体public Tetris() {initFrame();initUI();initGame();}初始化游戏界面private void initUI() {设置游戏面板和游戏区域pnlGame = new JPanel();pnlGame.setPreferredSize(new Dimension(blockSize * Width, blockSize * Height));pnlGame.setBorder(BorderFactory.createLineBorder(Color.gray));gameArea = new GameArea();pnlGame.add(gameArea);设置下一个方块显示面板和下一个方块区域pnlNextBlock = new JPanel();pnlNextBlock.setPreferredSize(new Dimension(blockSize * 4, blockSize * 4));pnlNextBlock.setBorder(BorderFactory.createTitledBorder("Next Block"));nextBlockArea = new BlockArea();pnlNextBlock.add(nextBlockArea);将游戏界面和下一个方块界面加入主窗体frmMain.getContentPane().add(pnlGame, BorderLayout.WEST);frmMain.getContentPane().add(pnlNextBlock, BorderLayout.EAST);显示窗体frmMain.pack();frmMain.setVisible(true);}初始化游戏private void initGame() {初始化积分、速度score = 0;speed = 1;初始化游戏区域for (int i = 0; i < Width; i++) {for (int j = 0; j < Height; j++) {wall[i][j] = 0;}}旋转T型方块,初始朝向为横向curBlock = new Block(1, 0);生成下一块方块nextBlock = new Block(0, 0);}我们可以看到,主类(Tetris.java)包含以下方法:1. initFrame()方法,用来初始化主窗体。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package cn.itcast.tetris.controller;import java.awt.Font;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.HashSet;import java.util.Set;import javax.swing.JLabel;import cn.itcast.tetris.entities.Ground;import cn.itcast.tetris.entities.Shape;import cn.itcast.tetris.entities.ShapeFactory;import cn.itcast.tetris.listener.GameListener;import cn.itcast.tetris.listener.GroundListener;import cn.itcast.tetris.listener.ShapeListener;import cn.itcast.tetris.util.Global;import cn.itcast.tetris.view.GamePanel;/*** 控制器<BR>* 控制Ground, Snake, Food<BR>* 负责游戏的逻辑<BR>* 处理按键事件<BR>* <BR>** @version 1.0, 01/01/08** @author 汤阳光**/public class Controller extends KeyAdapter implements ShapeListener, GroundListener {protected Set<GameListener> listeners = new HashSet<GameListener>();/*** 图形工厂**/protected ShapeFactory shapeFactory;protected Shape shape;protected Ground ground;protected GamePanel gamePanel;protected JLabel gameInfoLabel;/*** 当前的游戏状态*/protected boolean playing;/**** @param shapeFactory* @param ground* @param gamePanel*/public Controller(ShapeFactory shapeFactory, Ground ground,GamePanel gamePanel) {super();this.shapeFactory = shapeFactory;this.ground = ground;this.gamePanel = gamePanel;}/*** 多接受一个JTextComponent, 可以给在这个组件上显示提示信息** @param shapeFactory* @param ground* @param gamePanel* @param gameInfoLabel*/public Controller(ShapeFactory shapeFactory, Ground ground,GamePanel gamePanel, JLabel gameInfoLabel) {this(shapeFactory, ground, gamePanel);this.setGameInfoLabel(gameInfoLabel);}/*** 处理键盘按键<BR>* LEFT: 向左移动<BR>* RIGHT:向右移动<BR>* DOWN: 向下移动<BR>* UP: 变形<BR>* PAGE UP: 加快速度<BR>* PAGE DOWN: 减慢速度<BR>* Y: 重新开始游戏<BR>* ENTER: 暂停/继续*/@Overridepublic void keyPressed(KeyEvent e) {if (e.getKeyCode() != KeyEvent.VK_Y && !playing)return;switch (e.getKeyCode()) {/*** 方向左*/case KeyEvent.VK_LEFT:if (isPausingGame()) {this.continueGame();}shape.setSwift(false);if (isPlaying() && ground.isMoveable(shape, Shape.LEFT)) shape.moveLeft();break;/*** 方向右*/case KeyEvent.VK_RIGHT:if (isPausingGame()) {this.continueGame();}shape.setSwift(false);if (isPlaying() && ground.isMoveable(shape, Shape.RIGHT)) shape.moveRight();break;/*** 方向上*/case KeyEvent.VK_UP:if (isPlaying()) {if (!shape.isPause()) {if (ground.isMoveable(shape, Shape.ROTA TE)) {shape.setSwift(false);shape.rotate();}} else {if (ground.isMoveable(shape, Shape.UP))shape.moveUp();else {shape.die();shape = shapeFactory.getShape(this);}}}break;/*** 方向下*/case KeyEvent.VK_DOWN:if (isPausingGame()) {this.continueGame();}if (isPlaying() && isShapeMoveDownable(shape))shape.moveDown();break;/*** PAGE UP*/case KeyEvent.VK_PAGE_UP:shape.speedUp();break;/*** PAGE DOWN*/case KeyEvent.VK_PAGE_DOWN:shape.speedDown();break;/*** 反引号,换一个图形*/case KeyEvent.VK_BACK_QUOTE:if (isPlaying()) {shape.die();shape = shapeFactory.getShape(this);}break;case KeyEvent.VK_ENTER:if (isPausingGame())this.continueGame();elsethis.pauseGame();break;case KeyEvent.VK_Y:if (!isPlaying())newGame();break;case KeyEvent.VK_SPACE:if (isPlaying() && !isPausingGame())shape.setSwift(true);break;}/*** 重新显示*/gamePanel.redisplay(ground, shape);if (gameInfoLabel != null)gameInfoLabel.setText(this.getNewInfo());}/*** 询问一下图形是否可以下落,如果不能下落了,就会让图形变成障碍物<BR> * 这个方法是同步的*/public synchronized boolean isShapeMoveDownable(Shape s) {if (shape == null)return true;if (!playing || shape != s)return false;if (ground.isMoveable(shape, Shape.DOWN))return true;shape.die();ground.accept(shape);if (playing && !ground.isFull()) {shape = shapeFactory.getShape(this);}gamePanel.redisplay(ground, shape);if (gameInfoLabel != null)gameInfoLabel.setText(this.getNewInfo());return false;}/*** 处理图形触发的shapeMovedDown (图形下落) 事件<BR> * 将会重新显示*/public void shapeMovedDown(Shape s) {// TODO Auto-generated method stubif (playing && ground != null && shape != null)gamePanel.redisplay(ground, shape);}/*** 开始一个新游戏*/public void newGame() {playing = true;ground.init();ground.addGroundListener(this);Global.CURRENT_SPEED = Global.DEFAULT_SPEED;shape = shapeFactory.getShape(this);if (playing)gamePanel.redisplay(ground, shape);if (gameInfoLabel != null)gameInfoLabel.setText(this.getNewInfo());for (GameListener l : listeners)l.gameStart();}/*** 停止当前游戏*/public void stopGame() {if (shape == null)return;playing = false;for (GameListener l : listeners)l.gameOver();}/*** 暂停游戏*/public void pauseGame() {if (shape == null)return;shape.setPause(true);for (GameListener l : listeners)l.gamePause();}/*** 继续游戏*/public void continueGame() {shape.setPause(false);for (GameListener l : listeners)l.gameContinue();}/*** 游戏是否是在暂停状态*/public boolean isPausingGame() {return shape.isPause();}/*** 获得游戏的最新提示信息** @return*/public String getNewInfo() {if (!playing || ground.isFull())return " ";// "提示: 按Y开始新游戏";elsereturn new StringBuffer().append("提示: ").append(" 速度").append(shape.getSpeed()).append("毫秒/格").toString();}public ShapeFactory getShapeFactory() {return shapeFactory;}public void setShapeFactory(ShapeFactory shapeFactory) {this.shapeFactory = shapeFactory;}public Ground getGround() {return ground;}public void setGround(Ground ground) {this.ground = ground;}public GamePanel getGamePanel() {return gamePanel;}public void setGamePanel(GamePanel gamePanel) {this.gamePanel = gamePanel;}/*** 处理Ground 触发的beforeDeleteFullLine 事件将会改变满行的颜色并暂停一段时间*/public void beforeDeleteFullLine(Ground ground, int lineNum) {// TODO Auto-generated method stubground.changeFullLineColor(lineNum);gamePanel.redisplay(ground, shape);try {Thread.sleep(Global.STA Y_TIME);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 处理Ground 触发的fullLineDeleted 事件, 这个方法什么也没做, 只是打印了一句话*/public void fullLineDeleted(Ground ground, int deletedLineCount) {// TODO Auto-generated method stubSystem.out.println("消了" + deletedLineCount + " 行");}/*** 是否正在游戏中** @return*/public boolean isPlaying() {if (playing && !ground.isFull())return true;return false;}/*** 得到显示提示信息的组件** @return*/public JLabel getGameInfoLabel() {return gameInfoLabel;}/*** 设置** @param gameInfoLabel*/public void setGameInfoLabel(JLabel gameInfoLabel) {this.gameInfoLabel = gameInfoLabel;this.gameInfoLabel.setSize(Global.WIDTH * Global.CELL_WIDTH, 20);this.gameInfoLabel.setFont(new Font("宋体", Font.PLAIN, 12));gameInfoLabel.setText(this.getNewInfo());}/*** 处理Ground 的groundIsFull() 事件, 将触发游戏结束事件*/public void groundIsFull(Ground ground) {// TODO Auto-generated method stubif (playing) {playing = false;for (GameListener l : listeners)l.gameOver();}}/*** 添加监听器, 可添加多个** @param l*/public void addGameListener(GameListener l) { if (l != null)this.listeners.add(l);}/*** 移除监听器** @param l*/public void removeGameListener(GameListener l) { if (l != null)this.listeners.remove(l);}}package cn.itcast.tetris.entities;import java.awt.Color;import java.awt.Graphics;import java.util.HashSet;import java.util.Random;import java.util.Set;import cn.itcast.tetris.listener.GroundListener;import cn.itcast.tetris.util.Global;/*** 可以叫做地形, 或地面<BR>* 维护障碍物的信息<BR>* 可以使用提供的addObstacle(int, int) 和addStubbornObstacle(int ,int) 方法添加障碍物。