一个五子棋的java程序

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

public class Gomoku extends JFrame {
 
   privatefinal int CHESSBOARD_SIZE = 15;
    privateJLabel jblWhite = new JLabel("White: 0s");
    privateJLabel jblBlack = new JLabel("Black: 0s");
    privateJButton jbtIcon = new JButton("Start!");
    privateChessBoard chessboard = new ChessBoard();
    privateint[][] grid = new int[CHESSBOARD_SIZE][CHESSBOARD_SIZE]; // 1 forwhite, 2 for black
    privateboolean gameStatue = false;  // to show statue ofgame: true for continue, false for end.
    privateboolean isWinned = false;
    privateboolean player = true; // true for white, false for black
    private intwhiteTime = 0; // record white player's playing time(unitesecond)
    private intblackTime = 0; // record black player's playing time(unitesecond)
    privateTimer time = new Timer(1000, new TimerListener());
    
    publicGomoku() {
      for (int i = 0; i < grid.length;i++)
         for (int j = 0; j <grid[0].length; j++)
            grid[i][j] = 0;
      
      JPanel p1 = new JPanel();
      p1.setLayout(new GridLayout(1, 3, 20, 5));
      
      p1.add(jblWhite);
      p1.add(jbtIcon);
      p1.add(jblBlack);
      
      jbtIcon.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
            if (!gameStatue&& !isWinned) {
               gameStatue = true;
               time.start();
               jbtIcon.setText("New game");
            }
            else {
               setDefaultStatue();
                chessboard.repaint();
            }
         }
      });
      
      add(p1, BorderLayout.NORTH);
      add(chessboard, BorderLayout.CENTER);
    }
    
    privateclass TimerListener implements ActionListener {
      public void actionPerformed(ActionEvent e){
         if (player) {
            whiteTime++;
            if (whiteTime < 60)
               jblWhite.setText("White: " + String.valueOf(whiteTime) +"s");
            else if (whiteTime < 3600)
               jblWhite.setText("White: " +String.valueOf(whiteTime / 60) + "min" + String.valueOf(whiteTime %60) + "s");
            else
               jblWhite.setText("White: " +String.valueOf(whiteTime / 3600) + "h" + String.valueOf((whiteTime% 3600) / 60) + "min" + String.valueOf(whiteTime % 60) +"s");
         }
         else {
            blackTime++;
            if (blackTime < 60)
               jblBlack.setText("Black: " + String.valueOf(blackTime) +"s");
            else if (blackTime < 3600)
               jblBlack.setText("Black: " +String.valueOf(blackTime / 60) + "min" + String.valueOf(blackTime %60) + "s");
            else
               jblBlack.setText("Black: " +String.valueOf(blackTime / 3600) + "h" + String.valueOf((blackTime% 3600) / 60) + "min" + String.valueOf(blackTime % 60) +"s");
         }
      }
    }

    public voidsetDefaultStatue() {
      for (int i = 0; i < grid.length;i++)
         for (int j = 0; j <grid[0].length; j++)
            grid[i][j] = 0;
      
      gameStatue = false;
      isWinned = false;
      player = true;
      
      time.stop();
      whiteTime = 0;
      blackTime = 0;
      jblWhite.setText("White: 0s");
      jblBlack.setText("Black: 0s");
      
      jbtIcon.setText("Start!");
    }

    publicstatic void main(String[] args) {
      Gomoku frame = new Gomoku();
      frame.setTitle("Gomoku Game");
      frame.setSize(400, 440);
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
    }
    
    // checkwhether any five chess in a line are same color
    publicstatic boolean checkFiveSame(int[][] grid) {
      for (int i = 0; i < grid.length;i++) {
         for (int j = 0; j <grid[0].length; j++) {
            if (i < (grid.length - 4))
               if (grid[i][j] != 0
                && grid[i][j] ==grid[i + 1][j]
                && grid[i][j] ==grid[i + 2][j]
                && grid[i][j] ==grid[i + 3][j]
                && grid[i][j] ==grid[i + 4][j])
                  return true;
            
            if (j < (grid[0].length -4))
               if (grid[i][j] != 0
                && grid[i][j] ==grid[i][j + 1]
                && grid[i][j] ==grid[i][j + 2]
                && grid[i][j] ==grid[i][j + 3]
                && grid[i][j] ==grid[i][j + 4])
                  return true;
            
            if (i < (grid.length -4)  && j< (grid[0].length - 4))
               if (grid[i][j] != 0
                && grid[i][j] ==grid[i + 1][j + 1]
                && grid[i][j] ==grid[i + 2][j + 2]
                && grid[i][j] ==grid[i + 3][j + 3]
                && grid[i][j] ==grid[i + 4][j + 4])
                  return true;
            
            if (i < (grid.length - 4)&& j >= 4)
               if (grid[i][j] != 0
                && grid[i][j] ==grid[i + 1][j - 1]
                && grid[i][j] ==grid[i + 2][j - 2]
                && grid[i][j] ==grid[i + 3][j - 3]
                && grid[i][j] ==grid[i + 4][j - 4])
                  return true;
            }
         }
      
      return false;
    }
    
    classChessBoard extends JPanel {
      private int width;
      private int height;
      private int widthStep;
      private int heightStep;
      
      private int xStart;
      private int yStart;
      private int xEnd;
      private int yEnd;
       
      public ChessBoard() {
         setBackground(Color.GRAY);
         
         addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
               if (gameStatue) {
                  int mouseX = 0;
                  int mouseY = 0;
                  int gridX = 0;
                  int gridY = 0;
                  
                  mouseX = e.getX();
                  mouseY = e.getY();
                  if (mouseX >= xStart&& mouseX <= xEnd&& mouseY >= yStart&& mouseY <= yEnd){
                      gridX = (mouseX - xStart) / widthStep;
                      gridY = (mouseY - yStart) / heightStep;
                      
                      if (player) {
                        if (grid[gridX][gridY] == 0) {
                              grid[gridX][gridY] = 1;
                              repaint();
                              if (checkFiveSame(grid)) {
                                 jbtIcon.setText("White win!");
                                 gameStatue = false;
                                 isWinned = true;
                                 time.stop();
                              }
                              else if (checkChessboardFull(grid)) {
                                 jbtIcon.setText("Game end!");
                                 gameStatue = false;
                                 time.stop();
                              }
                              player = !player;
                        }
                      }
                      else {
                        if (grid[gridX][gridY] == 0) {
                            grid[gridX][gridY] = 2;
                            repaint();
                            if (checkFiveSame(grid)) {
                                 jbtIcon.setText("Black win!");
                                 gameStatue = false;
                                 isWinned = true;
                                 time.stop();
                              }
                            else if (checkChessboardFull(grid)) {
                               jbtIcon.setText("Game end!");
                               gameStatue = false;
                               time.stop();
                            }
                            player = !player;
                        }
                      }
                  }
               }
            }
         });
      }
      
      private boolean checkChessboardFull(int[][]grids) {
         for (int i = 0; i < grids.length;i++) {
            for (int j = 0; j <grids[0].length; j++) {
               if (grids[i][j] == 0)
                  return false;
            }
         }
         
         return true;
      }
      
      protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         
         width = (int)(getWidth() * 0.98);
          height = (int)(getHeight() * 0.98);
          widthStep = width / CHESSBOARD_SIZE;
          heightStep = height / CHESSBOARD_SIZE;
         
          xStart = (int)(width * 0.01);
          yStart = (int)(height * 0.01);
          xEnd = xStart + CHESSBOARD_SIZE *widthStep;
          yEnd = yStart + CHESSBOARD_SIZE *heightStep;
          
         // draw chessboard
         g.setColor(Color.BLACK);
         g.drawLine(xStart, yStart, xStart, yEnd);
         g.drawLine(xStart, yStart, xEnd, yStart);
         g.drawLine(xEnd, yStart, xEnd, yEnd);
         g.drawLine(xStart, yEnd, xEnd, yEnd);
         for (int i = 1; i <CHESSBOARD_SIZE; i++) {
            g.drawLine(xStart + i * widthStep, yStart, xStart+ i * widthStep, yEnd);
            g.drawLine(xStart, yStart + i * heightStep, xEnd,yStart + i * heightStep);
         }
         
         // draw chess
         int chessRadius = (int)(Math.min(widthStep,heightStep) * 0.9 *0.5);
         for (int i = 0; i < grid.length;i++) {
            for (int j = 0; j <grid[0].length; j++) {
               if (grid[i][j] == 1) {
                  g.setColor(Color.WHITE);
                  int xCenter = (int)(xStart + (i + 0.5) * widthStep);
                  int yCenter = (int)(yStart + (j + 0.5) * heightStep);
                  g.fillOval(xCenter - chessRadius, yCenter - chessRadius, 2 *chessRadius, 2 * chessRadius);
               }
               else if (grid[i][j] == 2) {
                  g.setColor(Color.BLACK);
                  int xCenter = (int)(xStart + (i + 0.5) *widthStep);
                  int yCenter = (int)(yStart + (j + 0.5) * heightStep);
                  g.fillOval(xCenter - chessRadius, yCenter - chessRadius, 2 *chessRadius, 2 * chessRadius);
               }
            }
         }
      }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的五子棋程序Java代码: ```java import java.util.Scanner; public class FiveChessGame { private static final int BOARD_SIZE = 15; // 棋盘大小 private static final char BLACK_CHESS = '●'; // 黑棋 private static final char WHITE_CHESS = '○'; // 白棋 private char[][] board; // 棋盘 private boolean blackTurn; // 轮到黑棋下了吗 public FiveChessGame() { board = new char[BOARD_SIZE][BOARD_SIZE]; blackTurn = true; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { board[i][j] = '╋'; // 初始化棋盘 } } } public void start() { System.out.println("欢迎来玩五子棋!"); Scanner scanner = new Scanner(System.in); while (true) { printBoard(); if (isGameOver()) { break; } char chess = blackTurn ? BLACK_CHESS : WHITE_CHESS; System.out.print("请" + (blackTurn ? "黑" : "白") + "方下棋(格式:x y):"); int x = scanner.nextInt(); int y = scanner.nextInt(); if (!isValidMove(x, y)) { System.out.println("无效的落子,请重新输入!"); continue; } board[x][y] = chess; blackTurn = !blackTurn; } printBoard(); System.out.println("游戏结束!"); } private void printBoard() { System.out.print(" "); for (int i = 0; i < BOARD_SIZE; i++) { System.out.print(i + " "); } System.out.println(); for (int i = 0; i < BOARD_SIZE; i++) { System.out.print(i + " "); for (int j = 0; j < BOARD_SIZE; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } private boolean isGameOver() { if (hasWon(BLACK_CHESS)) { System.out.println("黑方胜利!"); return true; } else if (hasWon(WHITE_CHESS)) { System.out.println("白方胜利!"); return true; } else if (isFull()) { System.out.println("平局!"); return true; } else { return false; } } private boolean hasWon(char chess) { // 检查每一行 for (int i = 0; i < BOARD_SIZE; i++) { int count = 0; for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j] == chess) { count++; if (count == 5) { return true; } } else { count = 0; } } } // 检查每一列 for (int i = 0; i < BOARD_SIZE; i++) { int count = 0; for (int j = 0; j < BOARD_SIZE; j++) { if (board[j][i] == chess) { count++; if (count == 5) { return true; } } else { count = 0; } } } // 检查正对角线 for (int i = 0; i < BOARD_SIZE - 4; i++) { for (int j = 0; j < BOARD_SIZE - 4; j++) { int count = 0; for (int k = 0; k < 5; k++) { if (board[i+k][j+k] == chess) { count++; if (count == 5) { return true; } } else { break; } } } } // 检查反对角线 for (int i = 0; i < BOARD_SIZE - 4; i++) { for (int j = 4; j < BOARD_SIZE; j++) { int count = 0; for (int k = 0; k < 5; k++) { if (board[i+k][j-k] == chess) { count++; if (count == 5) { return true; } } else { break; } } } } return false; } private boolean isFull() { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j] == '╋') { return false; } } } return true; } private boolean isValidMove(int x, int y) { return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == '╋'; } } ``` 你可以在 `main` 方法中创建一个 `FiveChessGame` 对象并调用 `start` 方法来开始游戏。例如: ```java public static void main(String[] args) { FiveChessGame game = new FiveChessGame(); game.start(); } ``` 在游戏中,你需要输入一个坐标来下棋。例如,如果你想在第3行第4列下黑棋,可以输入 `2 3`。如果输入的坐标无效(例如超出了棋盘范围或已经有棋子了),程序会提示你重新输入。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值