import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class MyFrame extends JFrame {
private Board board = new Board(); // 创建棋盘类的对象
private Image offImage = new BufferedImage(800, 800, BufferedImage.TYPE_INT_RGB);
public MyFrame() {
this.setTitle("五子棋"); // 设置窗口标题
this.setSize(800, 800); // 设置窗口宽度和高度
this.setResizable(false); // 设置窗口大小不可改变
this.setLocationRelativeTo(null); // 设置窗口居中
this.getContentPane().setBackground(new Color(200, 185, 25)); // 设置窗口背景色
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 关闭窗口时结束应用程序
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
board.makeAMove();
repaint(); // 通知操作系统通知你的窗口调用paint方法重新绘制界面
}
});
timer.start();
}
@Override
public void paint(Graphics g) { // 重写此方法的目的是在窗口上绘制自己想要的东西
Graphics newG = offImage.getGraphics();
super.paint(newG);
board.draw(newG);
g.drawImage(offImage, 0, 0, 800, 800, null);
}
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
public class Board {
private int[][] b = new int[15][15];
private boolean blackTurn = true; // 是否轮到黑方走棋
/**
* 绘制棋盘
* @param g 画笔
*/
public void draw(Graphics g) {
g.setColor(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
Stroke oldStroke = g2d.getStroke(); // 记录画笔原来的粗细(保存现场)
g2d.setStroke(new BasicStroke(5)); // 修改画笔的粗细
g.drawRect(50, 50, 700, 700); // 绘制棋盘边框
g2d.setStroke(oldStroke); // 将画笔还原为原来的粗细(恢复现场)
// 绘制横纵线条
for (int i = 0; i < 13; i++) {
g.drawLine(50, 100 + 50 * i, 750, 100 + 50 * i);
g.drawLine(100 + 50 * i, 50, 100 + 50 * i, 750);
}
g.fillOval(395, 395, 10, 10); // 绘制天元
// 绘制四个星
g.fillOval(195, 195, 10, 10);
g.fillOval(595, 595, 10, 10);
g.fillOval(195, 595, 10, 10);
g.fillOval(595, 195, 10, 10);
// 画棋子
for(int i = 0; i < b.length; i++) { // 行控制纵坐标
for(int j = 0; j < b[i].length; j++) { // 列控制横坐标
if(b[i][j] != 0) {
g.setColor(b[i][j] == 1? Color.BLACK : Color.WHITE);
g.fillOval(25 + 50 * j, 25 + 50 * i, 50, 50);
}
}
}
}
/**
* 随机下棋
*/
public void makeAMove() {
int row = (int) (Math.random() * 15);
int col = (int) (Math.random() * 15);
if(b[row][col] == 0) {
b[row][col] = blackTurn ? 1 : 2; // 用数字1表示黑棋用; 数字2表示白棋
blackTurn = !blackTurn; // 交换走棋方
}
}