import javax.swing.border.LineBorder; import java.awt.event.*;
public class tictactoe extends JApplet{
private char whoseturn = 'x';
private Cell [][] cells = new Cell [3][3];
private JLabel jlblstatus = new JLabel(\" x's turn to play \");
public tictactoe(){ JPanel p = new JPanel (new GridLayout(3,3,0,0)); for(int i=0;i<3;i++) for(int j=0;j<3;j++)
p.add(cells[i][j]=new Cell()); p.setBorder(new LineBorder(Color.red,1)); jlblstatus.setBorder(new LineBorder(Color.BLUE,2)); add(p,BorderLayout.CENTER); add(jlblstatus,BorderLayout.SOUTH); }
public boolean isfull(){ for(int i=0;i<3;i++){ for(int j=0;j<3;j++) if(cells[i][j].gettoken()==' '); return false;} return true; }
public boolean iswon(char token){ for(int i= 0;i<3;i++) if((cells[i][0].gettoken()==token)&&(cells[i][1].gettoken()==token) &&(cells[i][2].gettoken()==token) ) {return true;} for(int j= 0;j<3;j++) if((cells[0][j].gettoken()==token)&&(cells[1][j].gettoken()==token) &&(cells[2][j].gettoken()==token) ) {return true;}
if((cells[0][0].gettoken()==token)&&(cells[1][1].gettoken()==token) &&(cells[2][2].gettoken()==token) ) {return true;} if((cells[0][2].gettoken()==token)&&(cells[1][1].gettoken()==token) &&(cells[2][0].gettoken()==token) ) {return true;} return false; }
public class Cell extends JPanel{ private char token = ' '; public Cell(){ setBorder(new LineBorder(Color.black,1)); addMouseListener(new MyMouseLisntener()); } public char gettoken(){ return token; } public void settoken(char c){ token = c; repaint(); } protected void paintComponent(Graphics g){ super.paintComponent(g); if(token=='x'){ g.setColor(Color.black); g.drawLine(10, 10, getWidth()-10, getHeight()-10); g.drawLine(getWidth()-10, 10, 10, getHeight()-10); } else if(token=='0'){ g.setColor(Color.RED); g.drawOval(10, 10, getWidth()-20, getHeight()-20); } } private class MyMouseLisntener extends MouseAdapter{ public void mouseClicked(MouseEvent e){ if(token==' '&&whoseturn!=' '){ settoken(whoseturn);
} }
}
if(iswon(whoseturn)){ jlblstatus.setText(whoseturn+\" won! the game is over\"); whoseturn=' '; } else if(isfull()){ jlblstatus.setText(\"Draw! the game is over\"); whoseturn=' '; } else{
whoseturn =(whoseturn =='x')?'0':'x'; jlblstatus.setText(whoseturn +\" 's turn \"); } } }
因篇幅问题不能全部显示,请点此查看更多更全内容