Java简易五子棋

界面长这个样子:

这里写图片描述

重要代码分为三个类:
界面类,模拟下棋类,棋子类

界面类代码:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class GameFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private ChessBoard chessBoard;
    private JPanel toolbar;
    private JButton startButton, backButton, giveupButton;

    public GameFrame() {
        setTitle("五子棋-(黑棋先手)");
        chessBoard = new ChessBoard();

        Container contentPane = getContentPane();
        contentPane.add(chessBoard);
        chessBoard.setOpaque(true);

        MyListener list = new MyListener();

        toolbar = new JPanel();

        startButton = new JButton("重新开始");
        giveupButton = new JButton("认输");
        backButton = new JButton("悔棋");

        toolbar.setLayout(new FlowLayout(FlowLayout.CENTER, 80, 20));

        toolbar.add(startButton);
        toolbar.add(giveupButton);
        toolbar.add(backButton);

        startButton.addActionListener(list);
        giveupButton.addActionListener(list);
        backButton.addActionListener(list);

        add(toolbar, BorderLayout.SOUTH);
        add(chessBoard);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }
    private class MyListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            Object obj = e.getSource();
            if(obj == startButton) {
                chessBoard.restartGame();
            } else if(obj == giveupButton)
                chessBoard.giveup();
            else if (obj == backButton) {
                chessBoard.goback();
            }
        }
    }
}

模拟下棋类代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;

public class ChessBoard extends JPanel implements MouseListener {

    private static final long serialVersionUID = 1L;
    public static final int MARGIN = 30;        // 边距
    public static final int GRID_SPAN = 35;     // 网格间距
    public static final int ROWS = 15;          // 棋盘行数
    public static final int COLS = 15;          // 棋盘列数

    private MyPoint[] chessList = new MyPoint[(ROWS + 1) * (COLS + 1)];// 初始每个数组元素为null
    private boolean isBlack = true;                                // 默认开始是黑棋先  表示当前的棋子是不是黑棋
    private boolean gameOver = false;                              // 游戏是否结束
    private int chessCount;                                        // 当前棋盘棋子的个数
    private int xIndex, yIndex;                                    // 当前刚下棋子的索引

    private Color colortemp;

    public ChessBoard() {
        addMouseListener(this);
        addMouseMotionListener(new MouseMotionListener() {
            public void mouseDragged(MouseEvent e) {
            }
            public void mouseMoved(MouseEvent e) {
                int x1 = (e.getX() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
                // 将鼠标点击的坐标位置转成网格索引
                int y1 = (e.getY() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
                // 游戏已经结束        在棋盘外   x,y位置已经有棋子存在,不能下
                if (x1 < 0 || x1 > ROWS || y1 < 0 || y1 > COLS || gameOver || findChess(x1, y1))
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                // 设置成默认状态
                else
                    setCursor(new Cursor(Cursor.HAND_CURSOR));
            }
        });
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);// 画棋盘

        for (int i = 0; i <= ROWS; i++) {// 画横线
            g.drawLine(MARGIN, MARGIN + i * GRID_SPAN, MARGIN + COLS * GRID_SPAN, MARGIN + i * GRID_SPAN);
        }
        for (int i = 0; i <= COLS; i++) {// 画竖线
            g.drawLine(MARGIN + i * GRID_SPAN, MARGIN, MARGIN + i * GRID_SPAN, MARGIN + ROWS * GRID_SPAN);
        }
        // 画棋子
        for (int i=0; i<chessCount; i++) {
            // 网格交叉点x,y坐标
            int xPos = chessList[i].getX() * GRID_SPAN + MARGIN;
            int yPos = chessList[i].getY() * GRID_SPAN + MARGIN;
            g.setColor(chessList[i].getColor());// 设置颜色
            if (colortemp == Color.black) {
                RadialGradientPaint paint = new RadialGradientPaint(xPos - MyPoint.DIAMETER / 2 + 25,
                        yPos - MyPoint.DIAMETER / 2 + 10, 20, new float[] { 0f, 1f },
                        new Color[] { Color.WHITE, Color.BLACK });
                ((Graphics2D) g).setPaint(paint);
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                        RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);

            } else if (colortemp == Color.white) {
                RadialGradientPaint paint = new RadialGradientPaint(xPos - MyPoint.DIAMETER / 2 + 25,
                        yPos - MyPoint.DIAMETER / 2 + 10, 70, new float[] { 0f, 1f },
                        new Color[] { Color.WHITE, Color.BLACK });
                ((Graphics2D) g).setPaint(paint);
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                        RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);

            }

            Ellipse2D e = new Ellipse2D.Float(xPos - MyPoint.DIAMETER / 2, yPos - MyPoint.DIAMETER / 2, 34, 35);
            ((Graphics2D) g).fill(e);
            // 标记最后一个棋子的红矩形框

            if (i == chessCount - 1) {// 如果是最后一个棋子
                g.setColor(Color.red);
                g.drawRect(xPos - MyPoint.DIAMETER / 2, yPos - MyPoint.DIAMETER / 2, 34, 35);
            }
        }
    }

    public void mousePressed(MouseEvent e) {// 鼠标在组件上按下时调用
        if (gameOver)
            return;

        String colorName = isBlack ? "黑棋" : "白棋";
        // 将鼠标点击的坐标位置转换成网格索引
        xIndex = (e.getX() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
        yIndex = (e.getY() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;

        if (xIndex < 0 || xIndex > ROWS || yIndex < 0 || yIndex > COLS)
            return;
        // 如果x,y位置已经有棋子存在,不能下
        if (findChess(xIndex, yIndex))
            return;
        // 可以进行时的处理
        MyPoint ch = new MyPoint(xIndex, yIndex, isBlack ? Color.black : Color.white);
        chessList[chessCount++] = ch;
        repaint();

        if (isWin()) {
            String win = String.format("恭喜,%s赢了!", colorName);
            JOptionPane.showMessageDialog(this, win);
            gameOver = true;
        }
        isBlack = !isBlack;
    }

    public void mouseClicked(MouseEvent e) {
    }
    public void mouseEntered(MouseEvent e) {
    }
    public void mouseExited(MouseEvent e) {
    }
    public void mouseReleased(MouseEvent e) {
    }
    // 在棋子数组中查找是否有索引为x,y的棋子存在
    private boolean findChess(int x, int y) {
        for (MyPoint c : chessList) {
            if (c != null && c.getX() == x && c.getY() == y)
                return true;
        }
        return false;
    }

    private boolean isWin() {
        int continueCount = 1;
        Color c = isBlack ? Color.black : Color.white;
        // 横向寻找
        for (int x = xIndex - 1; x >= 0; x--) {
            if (getChess(x, yIndex, c) != null) {
                continueCount++;
            } else
                break;
        }
        for (int x = xIndex + 1; x <= COLS; x++) {
            if (getChess(x, yIndex, c) != null) {
                continueCount++;
            } else
                break;
        }
        if (continueCount >= 5) {
            return true;
        } else
            continueCount = 1;

        //纵向
        for (int y = yIndex - 1; y >= 0; y--) {
            if (getChess(xIndex, y, c) != null) {
                continueCount++;
            } else
                break;
        }
        for (int y = yIndex + 1; y <= ROWS; y++) {
            if (getChess(xIndex, y, c) != null)
                continueCount++;
            else
                break;
        }
        if (continueCount >= 5)
            return true;
        else
            continueCount = 1;
        //斜向
        for (int x = xIndex + 1, y = yIndex - 1; y >= 0 && x <= COLS; x++, y--) {
            if (getChess(x, y, c) != null) {
                continueCount++;
            } else
                break;
        }
        for (int x = xIndex - 1, y = yIndex + 1; x >= 0 && y <= ROWS; x--, y++) {
            if (getChess(x, y, c) != null) {
                continueCount++;
            } else
                break;
        }
        if (continueCount >= 5)
            return true;
        else
            continueCount = 1;

        //斜向
        for (int x = xIndex - 1, y = yIndex - 1; x >= 0 && y >= 0; x--, y--) {
            if (getChess(x, y, c) != null)
                continueCount++;
            else
                break;
        }
        for (int x = xIndex + 1, y = yIndex + 1; x <= COLS && y <= ROWS; x++, y++) {
            if (getChess(x, y, c) != null)
                continueCount++;
            else
                break;
        }
        if (continueCount >= 5)
            return true;
        else
            continueCount = 1;
        return false;
    }

    private MyPoint getChess(int xIndex, int yIndex, Color color) {
        for (MyPoint p : chessList) {
            if (p != null && p.getX() == xIndex && p.getY() == yIndex && p.getColor() == color)
                return p;
        }
        return null;
    }

    public void restartGame() {
        // 清除棋子
        for (int i = 0; i < chessList.length; i++) {
            chessList[i] = null;
        }
        // 恢复游戏相关的变量值
        isBlack = true;
        gameOver = false; // 游戏是否结束
        chessCount = 0; // 当前棋盘棋子个数
        repaint();
    }

    // 悔棋
    public void goback() {
        if (chessCount == 0)
            return;
        chessList[chessCount - 1] = null;
        chessCount--;
        if (chessCount > 0) {
            xIndex = chessList[chessCount - 1].getX();
            yIndex = chessList[chessCount - 1].getY();
        }
        isBlack = !isBlack;
        repaint();
    }

    public void giveup()
    {
        String colorName = isBlack ? "黑棋" : "白棋";
        String msg = String.format("很遗憾,%s已认输!", colorName);
        JOptionPane.showMessageDialog(this, msg);
        gameOver = true;
    }
    public Dimension getPreferredSize() {
        return new Dimension(MARGIN * 2 + GRID_SPAN * COLS, MARGIN * 2 + GRID_SPAN * ROWS);
    }
}

棋子类:

import java.awt.Color;  

public class MyPoint 
{  
  private int x;//棋盘中的x索引  
  private int y;//棋盘中的y索引  
  private Color color;//颜色  
  public static final int DIAMETER=30;//直径  

  public MyPoint(int x,int y,Color color){  
      this.x=x;  
      this.y=y;  
      this.color=color;  
  }   

  public int getX(){//拿到棋盘中x的索引  
      return x;  
  }  
  public int getY(){  
      return y;  
  }  
  public Color getColor(){//获得棋子的颜色  
      return color;  
  }  
}  

测试类:

public class TestFiveChess {
    public static void main(String[] args)
    {
        GameFrame FiveChess = new GameFrame();
        FiveChess.setVisible(true);
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值