使用Java写一个简单的五子棋游戏

五子棋的由来:

        五子棋起源于中国,相传中华民族的祖先轩辕黄帝无意之中画了一些纵横交叉的线段,然后在上面摆上小石块,就想出了连五子的玩法。

实现过程:

  1. 创建棋盘类(Board.java):
public class Board {
    public static final int ROW = 15; // 棋盘行数
    public static final int COLUMN = 15; // 棋盘列数

    private int[][] board; // 存储棋盘上每个格子的棋子状态,0表示未落子,1表示黑棋,2表示白棋

    public Board() {
        board = new int[ROW][COLUMN];
    }

    // 在指定位置落子,返回true表示落子成功,false表示该位置已经有棋子了
    public boolean makeMove(int row, int column, int player) {
        if (board[row][column] != 0) {
            return false;
        }
        
        board[row][column] = player;
        return true;
    }

    // 判断是否有玩家获胜,返回1表示黑棋获胜,2表示白棋获胜,0表示未分胜负
    public int checkWin() {
        int i, j, k;
        for (i = 0; i < ROW; i++) { // 横向判断
            for (j = 0; j < COLUMN - 4; j++) {
                if (board[i][j] == board[i][j+1] && board[i][j] == board[i][j+2] && board[i][j] == board[i][j+3] && board[i][j] == board[i][j+4]) {
                    return board[i][j];
                }
            }
        }

        for (j = 0; j < COLUMN; j++) { // 竖向判断
            for (i = 0; i < ROW - 4; i++) {
                if (board[i][j] == board[i+1][j] && board[i][j] == board[i+2][j] && board[i][j] == board[i+3][j] && board[i][j] == board[i+4][j]) {
                    return board[i][j];
                }
            }
        }

        for (i = 0; i < ROW - 4; i++) { // 斜向判断(左上到右下)
            for (j = 0; j < COLUMN - 4; j++) {
                if (board[i][j] == board[i+1][j+1] && board[i][j] == board[i+2][j+2] && board[i][j] == board[i+3][j+3] && board[i][j] == board[i+4][j+4]) {
                    return board[i][j];
                }
            }
        }

        for (i = ROW-1; i >= 4; i--) { // 斜向判断(右上到左下)
            for (j = 0; j < COLUMN - 4; j++) {
                if (board[i][j] == board[i-1][j+1] && board[i][j] == board[i-2][j+2] && board[i][j] == board[i-3][j+3] && board[i][j] == board[i-4][j+4]) {
                    return board[i][j];
                }
            }
        }

        return 0; // 未分胜负
    }

    // 判断棋盘是否已满
    public boolean isFull() {
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COLUMN; j++) {
                if (board[i][j] == 0) {
                    return false;
                }
            }
        }
        return true;
    }

    // 获取棋盘上指定位置的状态
    public int getCell(int row, int column) {
        return board[row][column];
    }
}

 2.游戏界面类(GameFrame):
     

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

public class GameFrame extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1L;

    private Board board; // 棋盘对象
    private JButton[][] buttons; // 每个格子对应的按钮
    private JLabel messageLabel; // 显示游戏信息的标签
    private int currentPlayer = 1; // 当前落子玩家,1表示黑棋,2表示白棋

    public GameFrame() {
        board = new Board();

        setTitle("五子棋");
        setSize(600, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new GridLayout(Board.ROW, Board.COLUMN));
        add(panel, BorderLayout.CENTER);

        buttons = new JButton[Board.ROW][Board.COLUMN];
        for (int i = 0; i < Board.ROW; i++) {
            for (int j = 0; j < Board.COLUMN; j++) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(30, 30));
                button.addActionListener(this);
                panel.add(button);

                buttons[i][j] = button;
            }
        }

        JPanel bottomPanel = new JPanel(new FlowLayout());
        add(bottomPanel, BorderLayout.SOUTH);

        messageLabel = new JLabel("黑棋先行");
        bottomPanel.add(messageLabel);
    }

    // 处理按钮点击事件
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        int row = -1, column = -1;

        // 根据按钮在二维数组中的位置计算出在棋盘上的坐标
        for (int i = 0; i < Board.ROW; i++) {
            for (int j = 0; j < Board.COLUMN; j++) {
                if (button == buttons[i][j]) {
                    row = i;
                    column = j;
                    break;
                }
            }
        }

        if (row >= 0 && column >= 0) {
            if (board.makeMove(row, column, currentPlayer)) {
                updateButton(button, currentPlayer);
                int winner = board.checkWin();
                if (winner != 0) {
                    gameOver(winner);
                } else if (board.isFull()) {
                    gameOver(0); // 平局
                } else {
                    switchPlayer();
                }
            }
        }
    }

    // 更新按钮上的显示内容
    private void updateButton(JButton button, int player) {
        if (player == 1) {
            button.setIcon(new ImageIcon("black.png"));
        } else {
            button.setIcon(new ImageIcon("white.png"));
        }
    }

    // 切换落子玩家
    private void switchPlayer() {
        currentPlayer = currentPlayer == 1 ? 2 : 1;
        messageLabel.setText(currentPlayer == 1 ? "黑棋下一步" : "白棋下一步");
    }

    // 游戏结束,显示胜利信息,并禁用所有按钮
    private void gameOver(int winner) {
        if (winner == 1) {
            messageLabel.setText("黑棋获胜!");
        } else if (winner == 2) {
            messageLabel.setText("白棋获胜!");
        } else {
            messageLabel.setText("平局!");
        }

        for (int i = 0; i < Board.ROW; i++) {
            for (int j = 0; j < Board.COLUMN; j++) {
                buttons[i][j].setEnabled(false);
            }
        }
    }

    public static void main(String[] args) {
        GameFrame frame = new GameFrame();
        frame.setVisible(true);
    }
}

最后,Black.png和white.png是用于白棋和黑棋的图片文件,自己网上找到,放在程序所在的目录下。即可运行开始游戏。

新人第一次发博客,请勿乱喷,谢谢 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,我可以给你提供一个简单五子棋游戏的代码实现。这个游戏使用Java Swing库来实现GUI界面。 首先,我们需要定义一个 `ChessBoard` 类来表示棋盘,并在其中添加落子、判断胜负等方法。 ```java public class ChessBoard { private int rows; private int cols; private int[][] board; public ChessBoard(int rows, int cols) { this.rows = rows; this.cols = cols; board = new int[rows][cols]; } public void reset() { board = new int[rows][cols]; } public boolean isValidMove(int row, int col) { return row >= 0 && row < rows && col >= 0 && col < cols && board[row][col] == 0; } public boolean play(int row, int col, int player) { if (!isValidMove(row, col)) { return false; } board[row][col] = player; return true; } public boolean isWin(int player) { // 判断横向是否连成五子 for (int i = 0; i < rows; i++) { for (int j = 0; j <= cols - 5; j++) { boolean win = true; for (int k = 0; k < 5; k++) { if (board[i][j + k] != player) { win = false; break; } } if (win) { return true; } } } // 判断纵向是否连成五子 for (int i = 0; i <= rows - 5; i++) { for (int j = 0; j < cols; j++) { boolean win = true; for (int k = 0; k < 5; k++) { if (board[i + k][j] != player) { win = false; break; } } if (win) { return true; } } } // 判断左上到右下是否连成五子 for (int i = 0; i <= rows - 5; i++) { for (int j = 0; j <= cols - 5; j++) { boolean win = true; for (int k = 0; k < 5; k++) { if (board[i + k][j + k] != player) { win = false; break; } } if (win) { return true; } } } // 判断右上到左下是否连成五子 for (int i = 0; i <= rows - 5; i++) { for (int j = cols - 1; j >= 4; j--) { boolean win = true; for (int k = 0; k < 5; k++) { if (board[i + k][j - k] != player) { win = false; break; } } if (win) { return true; } } } return false; } public int get(int row, int col) { return board[row][col]; } public int getRows() { return rows; } public int getCols() { return cols; } } ``` 接下来,我们需要定义一个 `ChessBoardPanel` 类来显示棋盘,并在其中添加点击事件处理方法。 ```java public class ChessBoardPanel extends JPanel { private static final int CELL_SIZE = 40; private ChessBoard board; private int currentPlayer; private int lastRow; private int lastCol; public ChessBoardPanel(ChessBoard board) { this.board = board; currentPlayer = 1; lastRow = -1; lastCol = -1; setPreferredSize(new Dimension(board.getCols() * CELL_SIZE, board.getRows() * CELL_SIZE)); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int row = e.getY() / CELL_SIZE; int col = e.getX() / CELL_SIZE; if (row == lastRow && col == lastCol) { return; } if (board.play(row, col, currentPlayer)) { lastRow = row; lastCol = col; repaint(); if (board.isWin(currentPlayer)) { JOptionPane.showMessageDialog(ChessBoardPanel.this, "Player " + currentPlayer + " wins!"); reset(); } else { currentPlayer = 3 - currentPlayer; } } } }); } public void reset() { board.reset(); currentPlayer = 1; lastRow = -1; lastCol = -1; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < board.getRows(); i++) { for (int j = 0; j < board.getCols(); j++) { g.setColor(Color.WHITE); g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE); g.setColor(Color.BLACK); g.drawRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE); if (board.get(i, j) != 0) { g.setColor(board.get(i, j) == 1 ? Color.BLACK : Color.WHITE); g.fillOval(j * CELL_SIZE + 2, i * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4); } } } } } ``` 最后,我们可以在 `Main` 类中创建一个窗口,将 `ChessBoardPanel` 添加到其中,并在点击“重置”按钮时调用 `reset()` 方法。 ```java public class Main { public static void main(String[] args) { JFrame frame = new JFrame("五子棋"); ChessBoard board = new ChessBoard(15, 15); ChessBoardPanel panel = new ChessBoardPanel(board); JPanel controlPanel = new JPanel(); JButton resetButton = new JButton("重置"); resetButton.addActionListener(e -> panel.reset()); controlPanel.add(resetButton); frame.getContentPane().add(BorderLayout.CENTER, panel); frame.getContentPane().add(BorderLayout.SOUTH, controlPanel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } ``` 这样,一个简单五子棋游戏就完成了。运行程序后,你可以看到一个带有棋盘和重置按钮的窗口。在棋盘上点击鼠标即可落子,当有一方获胜时,程序会弹出提示框,并自动重置棋盘。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Small Cow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值