應用程序的殼(界面、事件驅動)與算法的關係
兩者是骨骼和肉體的關係,當應用程序的殼創建好了,就需要把相應的算法寫入到事件驅動當中去,這樣才能實現程序應有的功能。
Exp:淺析五子棋
1、五子棋的算法包含什麼?
畫棋子的算法 判斷輸贏的算法 人機對戰算法
2、每個算法怎麼用計算機語言實現?
//畫棋子的算法
if(e.getX()>=50 && e.getX()<=770 && e.getY()>=50 && e.getY()<=770){
//定義單擊棋盤所在的點緩衝區大小爲20
//定義單擊在棋盤上所在的行列數爲x,y
x=(e.getX()+20)/50;
y=(e.getY()+20)/50;
//畫棋子
//利用白棋:0 黑棋:1
//判斷不爲下棋位置不爲空時才下棋,否則在已下棋位置重下報錯
if(a[x][y]==null){
if(count==0){
//畫透明的白棋
g.drawOval(x*50-10, y*50-10, 20, 20);
//建立每次下的白棋子對象
qiZi m=new qiZi();
m.type=0;
m.x=x*50-10;
m.y=y*50-10;
//在行列出賦值
a[x][y]=m;
count=1;
}
else
{ //畫黑顏色的黑棋
g.fillOval(x*50-10, y*50-10, 20,20);
// System.out.println("這是黑子"+count);
//建立每次下的白棋子對象
count=0;
qiZi o=new qiZi();
o.type=1;
o.x=x*50-10;
o.y=y*50-10;
a[x][y]=o;
}
}
else{
//如果在同一點重新下棋報錯
javax.swing.JFrame jf=new javax.swing.JFrame("錯誤提示");
jf.setSize(300,300);
javax.swing.JLabel jl=new javax.swing.JLabel("不能在以下過棋的位置重新下棋");
jf.add(jl);
jf.setVisible(true);
}
}
//判斷輸贏
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
//當找到的第一個有子位置的白棋時
if(a[i][j]!=null && a[i][j].type==0){
// System.out.println(a[i][j].x+"和"+a[i][j].y);
//判斷搜尋到的白字的周圍八個方向爲白棋且字數爲5點情況
//開始計數
//上下方計數
int record1=1;
//左右方計數
int record2=1;
//45度角方向計數
int record3=1;
//135度方向計數
int record4=1;
//利用for循環不斷的判斷
for(int w=1;w<=4;w++){
//45度方向的判斷
if(i+w<17 && j+w<17){
if(a[i+w][j+w]!=null && a[i+w][j+w].type==0){
record3++;
//System.out.print(record);
if(record3==5){
System.out.print("白棋贏了");
}
}
}
//135度方向判定
if(i-w>=0 && j+w<17){
if(a[i-w][j+w]!=null && a[i-w][j+w].type==0){
record4++;
//System.out.print(record);
if(record4==5){
System.out.print("白棋贏了");
}
}
}
//判斷上方情況
if(j+w<17){
if(a[i][j+w]!=null && a[i][j+w].type==0){
record1++;
//System.out.print(record);
if(record1==5){
System.out.print("白棋贏了");
}
}
}
//用於判斷右方的情況
if(i+w<17){
if(a[i+w][j]!=null && a[i+w][j].type==0){
record2++;
//System.out.print(record);
if(record2==5){
System.out.print("白棋贏了");
}
}
}
}
}
// 黑氣
//當找到的第一個有子位置的黑棋時
if(a[i][j]!=null && a[i][j].type==1){
// System.out.println(a[i][j].x+"和"+a[i][j].y);
//判斷搜尋到的白字的周圍八個方向爲白棋且字數爲5點情況
//開始計數
//上下方計數
int record1=1;
//左右方計數
int record2=1;
//45度角方向計數
int record3=1;
//135度方向計數
int record4=1;
//利用for循環不斷的判斷
for(int w=1;w<=4;w++){
//45度方向的判斷
if(i+w<17 && j+w<17){
if(a[i+w][j+w]!=null && a[i+w][j+w].type==1){
record3++;
//System.out.print(record);
if(record3==5){
System.out.print("黑棋贏了");
}
}
}
//135度方向判定
if(i-w>=0 && j+w<17){
if(a[i-w][j+w]!=null && a[i-w][j+w].type==1){
record4++;
//System.out.print(record);
if(record4==5){
System.out.print("黑棋贏了");
}
}
}
//判斷上方情況
if(j+w<17)
{
if(a[i][j+w]!=null && a[i][j+w].type==1){
record1++;
//System.out.print(record);
if(record1==5){
System.out.print("黑棋贏了");
}
}
}
//用於判斷右方的情況
if(i+w<17){
if(a[i+w][j]!=null && a[i+w][j].type==1){
record2++;
//System.out.print(record);
if(record2==5){
System.out.print("黑棋贏了");
}
}
}
}
}
}
}
//判斷輸贏結束
3、將相應的代碼發到哪裏?
畫棋子寫到鼠標監聽器中,利用計數器決定黑白棋
判斷的輸贏的也是寫在這裏