本源代码实现的是一单机双人对战五子棋游戏
本源代码由五个java源程序文件组成,Game.java、GameFrame.java、GamePanel.java、 ChessMan.java、Player.java
源代码下载
源代码:
Game.java
import javax.swing.*;
public class Game {
public static void main(String[] args) {
GameFrame GFrame=new GameFrame();
GFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GFrame.setVisible(true);
}
}
GameFrame.java
import java.awt.*;
import javax.swing.*;
class GameFrame extends JFrame {
private static final int Width=570;
private static final int Height=470;
GameFrame(){
setTitle("五子棋游戏");
CenteredFrame();
setSize(Width,Height);
GamePanel Gpanel=new GamePanel();
add(Gpanel);
}
void CenteredFrame(){
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
int screenHeight=screenSize.height;
int screenWidth=screenSize.width;
int Xposition=(screenWidth-Width)/2;
int Yposition=(screenHeight-Height)/2;
setLocation(Xposition,Yposition);
}
}
GamePanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GamePanel extends JPanel {
private Point cursor=new Point(40,60); //棋盘坐标
private int[][] ChessState=new int[18][18];//棋盘状态
private int i=0;//横坐标
private int j=0;//纵坐标
private final static int testnum=5;//五子棋的规定棋子数
private Player Black=new Player(1,Color.BLACK,"黑方");//黑方棋子
private Player White=new Player(2,Color.WHITE,"白方");//白方棋子
private Player Cplayer=null;//当前用户的引用
private JTextField textBlack=new JTextField("",5);//黑方文本提示框对象和文本长度设置
private JTextField textWhite=new JTextField("",5);//白方文本提示框对象和文本长度设置
private String Nothing="";
private String textblack="请黑方下子";//黑方提示文本
private String textwhite="请白方下子";//白方提示文本
GamePanel(){
setLayout(null);
Initialization();
setFocusable(true);
JButton Rutton=new JButton("重新开局");
Rutton.setBounds(20,14,100,26);
RestartListener restart=new RestartListener();
Rutton.addActionListener(restart);
add(Rutton);
textBlack.setHorizontalAlignment(JTextField.CENTER);
textBlack.setBounds(150,14,110,26);
textBlack.setEditable(false);
add(textBlack);
textWhite.setHorizontalAlignment(JTextField.CENTER);
textWhite.setBounds(290,14,110,26);
textWhite.setEditable(false);
add(textWhite);
JTextA
rea gInstruction=new JTextArea();
gInstruction.setSelectedTextColor(new Color(238,238,238));
String gSInstruction=
"Play1(黑方) Key \nup--------W \ndown----S \nleft--------A \nright------F \n\n"+
"Play2(白方) Key \nup--------up \ndown----down \nleft--------left \nright------right \n\n"+
"Exit game: \nPress Esc";
gInstruction.setText(gSInstruction);
gInstruction.setEditable(false);
gInstruction.setBounds(440,60,100,340);
add(gInstruction);
ChessManPerformListener Perform=new ChessManPerformListener();
addKeyListener(Perform);
}
// 设置第一个JTextField输出"请黑方下棋",坐标为(40,60)
void Initialization(){
for(int i=0,j;i<18;i++)
for(j=0;j<18;j++){
ChessState[i][j]=0;
}
cursor.setLocation(40,60);
Cplayer=Black;
textBlack.setText(textblack);
textWhite.setText(Nothing);
}
//画棋盘和初始化棋局状态
protected void paintComp