首先7种俄罗斯方块都是由4块小方块组成的,所以我们可以抽象出一个Cell类:
Cell类:
import java.awt.image.BufferedImage;public class Cell {private int x;private int y;private BufferedImage image;public Cell() {super();}public Cell(int x, int y, BufferedImage image) {super();this.x = x;this.y = y;this.image = image;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public BufferedImage getImage() {return image;}public void setImage(BufferedImage image) {this.image = image;}public void cellMoveLeft(){this.y--;}public void cellMoveRight(){this.y++;}public void cellMoveDown(){this.x++;}}
4个Cell即Cell数组作为俄罗斯方块Tetris类的一个属性
Tetris类中以上部分
public class Tetris {protected Cell[] cells;public Tetris(){lls=new Cell[4];}public Cell[] getCells() {return cells;}public void setCells(Cell[] cells) {lls = cells;}public void moveLeft(){for(Cell c:cells){c.cellMoveLeft();}}public void moveRight(){for(Cell c:cells){c.cellMoveRight();}}public void moveDown(){for(Cell c:cells){c.cellMoveDown();}}public Tetris randomTetris(){Tetris t=null;switch ((int)(Math.random()*7)) {case 0:t=new I();break;case 1:t=new O();break;case 2:t=new T();break;case 3:t=new J();break;case 4:t=new L();break;case 5:t=new S();break;case 6:t=new Z();break;}return t;}}
然后是最关键的旋转
俄罗斯方块旋转的过程中,总会有1个方块其位置是不变的,我们不妨将这个不变的方块当做轴心,所以我们在具体类实例化的时候应该将Cell数组的第一个元素当做轴心,其他方块旋转后的位置都是相对于轴心,所以我们可以把每次旋转后的相对位置存储在一个State数组中。也考虑到不同类型的俄罗斯方块旋转形态种类不同(比如I只有两种形态,O只有一种形态即不能旋转),而且应该在具体类中实例化,所以State[]数组的修饰词也应该是protected。
我们可以设置一个较大的计数器,向左旋转即计数器-1,向右+1,通过计数器对数组长度取余来指定State数组中的相对状态。如果通过随机State数组中的元素就不能达到向左向右旋转后回到原始状态的效果,所以才需要一个State数组来"记忆"旋转顺序。
Tetris类中旋转部分
protected State[] states;
int rotateCount=1000;public class State{int x0,y0,x1,y1,x2,y2,x3,y3;public State(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3) {super();this.x0 = x0;this.y0 = y0;this.x1 = x1;this.y1 = y1;this.x2 = x2;this.y2 = y2;this.x3 = x3;this.y3 = y3;}}public void getTrueXY(State s){int x=cells[0].getX();int y=cells[0].getY();cells[1].setX(x+s.x1);cells[2].setX(x+s.x2);cells[3].setX(x+s.x3);cells[1].setY(y+s.y1);cells[2].setY(y+s.y2);cells[3].setY(y+s.y3);}public v
本文发布于:2024-01-28 09:50:08,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064066166561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |