一个Applet的小游戏 (三子棋)
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
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.yellow,1));
this.getContentPane().add(p,BorderLayout.CENTER);
this.getContentPane().add(jlblStatus,BorderLayout.SOUTH);
}
//判断9个格是否有空
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][2].getToken() == token) && (cells[1][1].getToken == token) && (cells[2][0].getToken() == token)){
return true;
}
if((cells[0][0].getToken() == token) && (cells[1][1].getToken == token) && (cells[2][2].getToken() == token)){
return true;
}
return false;
}
//cell 类
public class Cell extends JPanel implements MouseListener{
private char token = '';
public Cell(){
//画每个格子的边框
setBorder(new LineBorder(Color.black,1));
addMouseListener(this);
}
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.drawLine(10,10,getWidth()-10,getHeight()-10);
g.drawLine(getWidth()-10,10,10,getHeight()-10);
}
else if(token == 'O'){
g.drawOval(10,10,getWidth()-20,getHeight()-20);
}
}
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') ? 'O':'X';
jlblStatus.setText(whoseTurn +" 's turn");
}
}
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
}
}
<html>
<head>
</head>
<body>
<applet code="TicTacToe.class" width=300 height=300>
</applet>
</body>
</html>