【IT168技术文档】
首先说明一下我做了一个什么游戏。这个游戏是一个同色相溶的游戏,在手机上玩过,觉得很有意思,就照着做了一个。同色相溶游戏规则是这样的:在游戏面板上有N×N个不同颜色的小球,用鼠标单击其中任意一个小球,如果相邻的小球与之颜色相同,则消去所有同色小球。消去的空位由同一列上面的小球下落补充。如果某一列所有小球都消去了,则右面的所有列左移补充空列。消去的小球越多,成绩越高。
游戏中包括这几个类:
XXGame:实现游戏逻辑的类;
XXPanel:游戏面板类;
ControlPanel:游戏控制面板和其他信息显示;
XXFrame:游戏主窗口;
PotInterface:定义小球属性的接口。
其中XXGame继承了java.util.Observable,为被观察者。该类关键是trigger方法,当游戏者点击的游戏面板上的一个小球时,调用此方法处理游戏逻辑。
XXPanel显示游戏面板,并作为观察者随时根据游戏状态显示游戏界面://XXGame.java
![]()
class XXGame extends Observable ...{
private int rows, cols;
private int count;
private Pot[] pot;
![]()
public XXGame(int rows, int cols)...{
this.rows = rows;
this.cols = cols;
pot = new Pot[rows * cols];
![]()
reset();
}
//初始化
public void reset()...{
for(int i=0;i<pot.length;i++)
pot[i] = new Pot(Pot.newColor());
count = 0;
![]()
setChanged();
notifyObservers(this);
}
//返回行数
public int getRows()...{
return rows;
}
//返回列数
public int getCols()...{
return cols;
}
//返回指定位置的小球对象
public PotInterface getPot(int row,int col)...{
return pot[row * rows + col];
}
//当位于row,col的小球被单击时,调用该方法处理游戏逻辑
public void trigger(int row, int col)...{
PotInterface p = pot[row * rows + col];
if(p==null)return;
//调用消去小球的方法
int c = dissolvePot(row,col, p);
if( c>0)...{
pot[row*rows + col]=null;
count = count + c;
![]()
arrange();//重新排列
setChanged();
notifyObservers(this);//通知观察者
}
}
//返回得分
public int getCount()...{
return count;
}
//返回还未消去的小球数
public int getAvaliableCount()...{
![]()
}
//小球指定位置的小球
private int dissolvePot(int row, int col, PotInterface p)...{
![]()
}
![]()
![]()
/**//**
* 消除小球后重新排列版面
*
*/
private void arrange()...{
}
}
//XXPanel.java
![]()
public class XXPanel extends Canvas implements Observer...{
private XXGame game;
private int width, height;
![]()
public XXPanel(XXGame game)...{
this.game = game;
![]()
setBackground(Color.BLACK);
addMouseListener(new ML());
}
//当用户点击小球时,调用gamesss
class ML extends MouseAdapter...{
public void mousePressed(MouseEvent e)...{
int row,col;
col = e.getX() / width;
row = e.getY() / height;
![]()
if(col <game.getCols() && row<game.getRows())
game.trigger(row,col);
}
}
//绘制游戏界面
public void paint(Graphics g) ...{
int rows,cols;
![]()
Rectangle rect = g.getClipBounds();
rows = game.getRows();
cols = game.getCols();
width = rect.width / cols;
height = rect.height / rows;
![]()
for(int i=0; i<rows; i++)
for(int j=0; j<cols; j++)...{
PotInterface p = (PotInterface)game.getPot(i,j);
if(p!=null)...{
g.setColor(p.getColor());
g.fillArc(j*width,i*height, width, height, 0, 360);
}
}
}
![]()
public void update(Observable o, Object arg) ...{
repaint();
}
}