Java ——简易俄罗斯方块( 三 )


2.画游戏静态界面
在这一部分中需要绘制三部分 , 用到了三种方法 , 分别是(正在下落的四格方块) , (等待进入的四格方块) , (背景墙) 。
绘制需要重写类中的paint( g)方法 , 具体代码实现如下:
public void paint(Graphics g){//绘制背景/** g:画笔* g.drawImage(image,x,y,null)* x:开始绘制的横坐标* y:开始绘制的纵坐标*/g.drawImage(background,0,0,null);//平移坐标轴g.translate(15, 15);//绘制墙paintWall(g);//绘制正在下落的四格方块paintCurrentOne(g);//绘制下一个即将下落的四格方块paintNextOne(g);}/** 绘制下一个即将下落的四格方块* 绘制到面板的右上角的相应区域*/public void paintNextOne(Graphics g){//获取nextOne对象的四个元素Cell[] cells=nextOne.cells;for (Cell c:cells) {//获取每一个元素的行号和列号int row=c.getRow();int col=c.getCol();//横坐标和纵坐标int x=col*CELL_SIZE+260;int y=row*CELL_SIZE+26;g.drawImage(c.getImage(), x, y, null);}}/** 绘制正在下落的四格方块* 取出数组的元素* 绘制数组的图片* 横坐标x* 纵坐标y*/public void paintCurrentOne(Graphics g){Cell[] cells=currentOne.cells;for (Cell c:cells) {int x=c.getCol()*CELL_SIZE;int y=c.getRow()*CELL_SIZE;g.drawImage(c.getImage(), x, y, null);}}/** 墙是20行 , 10列的表格* 是一个二维数组* 用双层循环* 绘制正方形*/public void paintWall(Graphics a){//外层循环控制行数for (int i = 0; i < 20; i++) {//内层循环控制列数for (int j = 0; j < 10; j++) {int x=j*CELL_SIZE;int y=i*CELL_SIZE;Cell cell=wall[i][j];a.drawRect(x, y, CELL_SIZE, CELL_SIZE);if(wall[i][j]==null){a.drawRect(x, y, CELL_SIZE, CELL_SIZE);}else{a.drawImage(cell.getImage(),x,y,null);}}}}
实现效果如下:

Java ——简易俄罗斯方块

文章插图
3.让四格方块动起来
光有静态的画面是不能够称为游戏的 , 还有要动态效果和接收键盘指令并响应的能力 。
(1)动态效果
俄罗斯方块中的动态效果主要指7种四格方块拥有自动下降 , 软下降 , 左移 , 右移 , 旋转的能力 , 分别使用() , () , () , () , ()方法来实现 , 与此同时 , 还需根据游戏规则注意四格方块可能遇到触碰到左右边界 , 方块覆盖等错误 , 在此使用() , ()方法来避免 。当不能下落时 , 需要将四格方块 , 嵌入到墙中 , 使用()方法 。
具体代码实现如下:
/** 使用left键控制向左的行为*/public void moveLeftAction() {currentOne.moveLeft();if(outOfBounds()||coincide()){currentOne.moveRight();}}/** 使用right键控制向右的行为*/public void moveRightAction() {currentOne.moveRight();if(outOfBounds()||coincide()){currentOne.moveLeft();}}/** 使用down键控制四格方块的下落*/public void softDropAction() {if(canDrop()){currentOne.softDrop();}else{landToWall();currentOne=nextOne;nextOne=Tetromino.randomOne();}}public boolean outOfBounds(){Cell[] cells=currentOne.cells;for (Cell c : cells) {int col=c.getCol();if(col<0||col>9){return true;}}return false; }public boolean coincide(){Cell[] cells=currentOne.cells;for (Cell c : cells) {int row=c.getRow();int col=c.getCol();if(wall[row][col]!=null){return true;}}return false;}public boolean canDrop(){Cell[] cells=currentOne.cells;for (Cell c: cells) {//获取每个元素的行号/** 判断:* 只要有一个元素的下一行上有方块* 或者只要有一个元素到达最后一行 , 就不能下落了*/int row=c.getRow();int col=c.getCol();if(row==19){return false;}if(wall[row+1][col]!=null){return false;}}return true;}/** 当不能下落时 , 需要将四格方块 , 嵌入到墙中* 也就是存储到二维数组中相应的位置上*/public void landToWall(){Cell[] cells=currentOne.cells;for (Cell c : cells) {//获取最终的行号和列号int row=c.getRow();int col=c.getCol();wall[row][col]=c;}}