這是圈圈叉叉遊戲,目前還沒有計分機制
Tip: 用矩陣儲存格子是否被畫過;
用MouseListener的Pressed物件來抓取滑鼠所點選的位置,以得知要畫記在哪裡;
在paint()中,用if及布林變數來分階段畫出隔線與圈叉;
運用除法及家法運算 將同格子範圍內的x,y值統一訂至格子中心;
Int在除法上有瑕疵,運算過程有個地方理應為負數,卻自動進位成0,要透過(int)(Math.floor((mx-100.0)/100));來解決;但也可以直接在範圍限制中用上下界值來判斷
package ex02;
import java.awt.*;
import java.awt.event.*;
public class mm extends Frame implements WindowListener, MouseListener{
int mx=100,my=100;
boolean first=true;int mode = 0;
int[][] map = new int[3][3];
public static void main(String[] args){
mm p = new mm();
}
mm(){
this.setSize(1000,1000);
this.setLocation(100,100);
this.setLayout(null);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
map[i][j]=0;
}
this.addWindowListener(this);/*interface*/
this.addMouseListener(this);/*interface*/
this.setVisible(true);
}
/*Override*/
public void update(Graphics g){paint(g);}
public void paint(Graphics g){
if(first==true){
for(int i=0;i<4;i++){
g.drawLine(100+100*i, 100, 100+100*i, 400);
g.drawLine(100, 100+100*i, 400, 100+100*i);
first = false;
}
}else{
if(/**(mx>100)&&**/(mx<400)&&/**(my>100)&&**/(my<400)){
//g.setColor(new Color(fun.Rand(0,255),fun.Rand(0,255),fun.Rand(0,255)));
int px,py,nx,ny;
/**px = (int)((mx-100)/100);**//*value changed for opt*/
/**py = (int)((my-100)/100);**//*value changed for opt*/
px = (int)(Math.floor((mx-100.0)/100));/*deal with integer problem of set -1 to 0*/
py = (int)(Math.floor((my-100.0)/100));/*deal with integer problem of set -1 to 0*/
nx = 150+px*100;/*for drawing*/
ny = 150+py*100;/*for drawing*/
/*System.out.println("px="+px+"py="+py);*/
if(map[px][py]==0){
if(mode==0){
g.drawOval(nx-30, ny-30, 61, 61); /*畫圈圈*/
mode = 1-mode;
}else if(mode==1){
g.drawLine(nx+30, ny+30, nx-30, ny-30); /*畫叉叉*/
g.drawLine(nx-30, ny+30, nx+30, ny-30);
mode = 1-mode;
}
map[px][py]=1;
}
}
}
}
/*WindowListener Event*/
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowClosing(WindowEvent e) {dispose();}
@Override
public void windowClosed(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
/*MouseListener Event*/
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
mx=e.getX();
my=e.getY();
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
留言列表