用JAVA编写五子棋

各部分功能实现

1、开发界面

计算棋盘中每一条线的间距:这里是19*19的围棋盘
总宽度为467-17=450,总高度533-89=450
分18份,每一份:x:25 y:25
此代码获取棋盘四个端点的坐标

@Override

    public void mousePressed(MouseEvent e) {

        // TODO Auto-generated method stub

        System.out.println("X"+e.getX());

        System.out.println("Y"+e.getY());

    }

2、在棋盘上的鼠标点击位置,显示一个旗子

黑子:实心黑圆
白子:实心白圆

repaint():表示重新执行repaint

3、保存之前下过的旗子

通过一个二维数组来保存之前下过的棋子

4、判断游戏胜负

五子棋的基本规则,是否有同一颜色的棋子连成五个(核心算法)

public boolean checKwin() {

        boolean flag=false;

        //判断横向的是否有五个棋子,特点 纵坐标是相同的即allChess[X][Y]中Y值是相同的

        int color=allChess[x][y];

        //保存共有多少相同颜色的棋子

        int count=1;

 count=this.checkCount(1, 0, color);

        if(count>=5) {

            flag=true;

        }else {

            //判断纵向

            count=this.checkCount(0, 1, color);

            if(count>=5) {

                flag=true;

        }else {

            //右下

            count=this.checkCount(1, -1, color);

            if(count>=5) {

                flag=true;

            }else {

                //左上

                count=this.checkCount(-1, 1, color);

                if(count>=5) {

                    flag=true;

                    }else {

                        //右上

                        count=this.checkCount(1, 1, color);

                        if(count>=5) {

                            flag=true;

                    }else {

                        //左上

                        count=this.checkCount(-1,-1, color);

                        if(count>=5) {

                            flag=true;

                            }

                        }

                    }

                }

            }

        }

        return flag;

    }

    //判断棋子连接的数量

    private int checkCount(int xChange,int yChange,int color) {

        int count =1;

        int tempX=xChange;

        int tempY=yChange;

        while(x+xChange>=0 &&x+xChange<=18 && y+yChange>=0 &&y+yChange<=18 && color==allChess[x+xChange][y+yChange]) {

            count++;

            if(xChange!=0

                xChange++;

            if(yChange!=0) {

                if(yChange>0

                    yChange++;

                else {

                    yChange--;

                }

            }

        }

        xChange=tempY;

        yChange=tempX;

         

        while(color==allChess[x-xChange][y-yChange]) {

            count++;

            if(xChange!=0

                xChange++;

            if(yChange!=0) {

                if(yChange>0

                    yChange++;

                else {

                    yChange--;

                }

            }

        }

        return count;

         

    }

5、实现各个按钮的功能

开始游戏:重新开始

游戏设置:设置倒计时

线程实现

//点击 游戏设置 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=154 &&e.getY()<=190) {

            String input=JOptionPane.showInputDialog("请输入游戏的最大时间(分钟),输入0表示没有时间限制");

            try {

                maxTime=Integer.parseInt(input)*60;

                if(maxTime<0) {

                    JOptionPane.showMessageDialog(this, "不允许输入负数");

                }

                if(maxTime>0){

                    int r1=JOptionPane.showConfirmDialog(this,"是否重新开始游戏?");

                    if(r1==0) {

                        //重新开始游戏1、棋盘清空;allChess==0;2、将游戏信息的显示改到开始位置;3、将下一步要下棋的改为黑方

                        allChess=new int[19][19];

                        message="黑方先行";

                        blackTime=maxTime;

                        whiteTime=maxTime;

                        blackMessage=maxTime/3600+":"

                                +(maxTime/60-maxTime/3600*60)+":"

                                +(maxTime-maxTime/60*60);

                        whiteMessage=maxTime/3600+":"+

                                (maxTime/60-maxTime/3600*60)+":"

                                +(maxTime-maxTime/60*60);

                        isBlack=true;

                        t.resume();

                        //重新绘制棋盘

                        this.repaint();

                        }

                    }

                }catch(NumberFormatException e1){

                    JOptionPane.showMessageDialog(this, "请正确输入信息");

                }

            }

public void run() {

        // TODO Auto-generated method stub

        //判断是否有时间限制

        if(maxTime>0) {

            while(true) {

                if(isBlack) {

                    blackTime--;

                    if(blackTime==0) {

                        JOptionPane.showMessageDialog(this,"黑方超时,游戏结束");

                    }

                }else {

                    whiteTime--;

                    if(whiteTime==0) {

                        JOptionPane.showMessageDialog(this,"白方超时,游戏结束");

                    }

                }

                blackMessage=blackTime/3600+":"

                        +(blackTime/60-blackTime/3600*60)+":"

                        +(blackTime-blackTime/60*60);

                whiteMessage=whiteTime/3600+":"+

                        (whiteTime/60-whiteTime/3600*60)+":"

                        +(whiteTime-whiteTime/60*60);

                //刷新屏幕

                this.repaint();

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

                 

            }

        }

    }

游戏说明:用来说明游戏规则和操作

认输: 是某一方放弃游戏
关于 : 作者,版本
退出: 退出游戏

总代码

public class test {

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        FiveChessFream jj=new FiveChessFream();

    }

}

package FiveChessDome;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Toolkit;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

public class FiveChessFream extends JFrame implements MouseListener,Runnable{

     

    int width=Toolkit.getDefaultToolkit().getScreenSize().width;

    int higth=Toolkit.getDefaultToolkit().getScreenSize().height;

    //背景图片

    BufferedImage bgImage=null;

    //保存旗子的坐标

    int x=0;

    int y=0;

    //保存之前下过的旗子的坐标,其中数据内容是0:表示这个点没有旗子,1:表示是黑子,2:表示的是白子

    int [][] allChess=new int[19][19];

    //标识当前应该是黑棋还是白棋

    Boolean isBlack=true;

    //标识当前游戏是否继续进行

    boolean canPlay=true;

    //保存显示信息

    String message="黑方先行";

    //保存最多拥有多少时间

    int maxTime=0;

    //做倒计时的线程类

    Thread t=new Thread(this);

    //保存黑方与白方的剩余时间

    int blackTime=0;

    int whiteTime=0;

    //保存双方剩余的时间

    String blackMessage="无限制";

    String whiteMessage="无限制";

     

     

    public FiveChessFream() {

        //标题

        this.setTitle("五子棋");

        //窗体大小

        this.setSize(626, 625);

        //窗体在屏幕的位置

        this.setLocation((width-500)/2,(higth-500)/2);

        //窗体不可变

        this.setResizable(false);

        //窗体关闭

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //为窗体加入监听器

        this.addMouseListener(this);

        //窗体显示

        this.setVisible(true);

         

        //启动线程

        t.start();

        t.suspend();

        //刷新屏幕,防止开始游戏时无法显示屏幕的情况

        this.repaint();

         

        //背景图的导入

        try {

            bgImage=ImageIO.read(new File("d:/桌面/五子棋2.png"));

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    public void paint(Graphics g) {

        //双缓冲技术防止屏幕闪烁

        BufferedImage bi=new BufferedImage(626, 625, BufferedImage.TYPE_INT_ARGB);

        Graphics g2=bi.createGraphics();

        //绘制背景

        g.drawImage(bgImage, 3, 20, this);

        //输出标题信息

        g.setFont(new Font("黑体",Font.BOLD,20));

        g.drawString("游戏信息:"+message,100, 60);

        //输出时间信息

        g.setFont(new Font("宋体",10,14));

        g.drawString("黑色的时间:"+blackMessage, 40, 585);

        g.drawString("白色的时间:"+whiteMessage, 330, 585);

         

         

        //绘制棋盘

        for(int i=0;i<19;i++) {

            //横轴

            g.drawLine(17,89+25*i,467,89+25*i);

            //竖轴

            g.drawLine(17+25*i, 89, 17+25*i, 538);

        }

         

        //标志点位,四个点

        g.fillOval(90, 162,4,4);

        g.fillOval(90, 462,4,4);

        g.fillOval(390, 162,4,4);

        g.fillOval(390,462,4,4);

         

        //绘制全部旗子

        for(int i=0;i<19;i++) {

            for(int j=0;j<19;j++) {

                if(allChess[i][j]==1) {

                    //黑子

                    int tempx=i*25+17;

                    int tempy=j*25+89;

                    g.fillOval(tempx-7,tempy-7,14,14);

                }

                if(allChess[i][j]==2) {

                    //白子

                    int tempx=i*25+17;

                    int tempy=j*25+89;

                    g.setColor(Color.WHITE);

                    g.fillOval(tempx-7,tempy-7,14,14);

                    g.setColor(Color.BLACK);

                    g.drawOval(tempx-7,tempy-7,14,14);

                }

            }

        }

    }

    @Override

    public void mouseClicked(MouseEvent e) {

        // TODO Auto-generated method stub

         

    }

    @Override

    public void mousePressed(MouseEvent e) {

        if(canPlay==true) {

         x=e.getX();

         y=e.getY();

        //判断旗子落在棋盘上

        if(x>17&&x<=467 && y>89&&y<=538) {

            x=(x-17)/25;

            y=(y-89)/25;

            if(allChess[x][y]==0) {

            //判断当前要下的是什么旗子

                if(isBlack==true) {

                    allChess[x][y]=1;

                    isBlack=false;

                    message="轮到白方";

                }else {

                    allChess[x][y]=2;

                    isBlack=true;

                    message="轮到黑方";

                }

                 

                //判断这个棋子是否和其他的棋子连成五个

                boolean winFlag=this.checKwin();

                if(winFlag==true) {

                    JOptionPane.showMessageDialog(this,"游戏结束"

                +(allChess[x][y]==1?"黑色":"白色")+"获胜");

                    canPlay=false;

                }

                 

            }else {

                JOptionPane.showMessageDialog(this,"当前位置已经有棋子,请重新落子!");

            }

            this.repaint();

            }

        }

         

        //System.out.println(e.getX()+"`````"+e.getY());

        //点击 游戏开始 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=90 &&e.getY()<=125) {

            int r1=JOptionPane.showConfirmDialog(this,"是否重新开始游戏?");

            if(r1==0) {

                //重新开始游戏1、棋盘清空;allChess==0;2、将游戏信息的显示改到开始位置;3、将下一步要下棋的改为黑方

                allChess=new int[19][19];

                message="黑方先行";

                isBlack=true;

                //重新绘制棋盘

                this.repaint();

            }

        }

        //点击 游戏设置 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=154 &&e.getY()<=190) {

            String input=JOptionPane.showInputDialog("请输入游戏的最大时间(分钟),输入0表示没有时间限制");

            try {

                maxTime=Integer.parseInt(input)*60;

                if(maxTime<0) {

                    JOptionPane.showMessageDialog(this, "不允许输入负数");

                }

                if(maxTime>0){

                    int r1=JOptionPane.showConfirmDialog(this,"是否重新开始游戏?");

                    if(r1==0) {

                        //重新开始游戏1、棋盘清空;allChess==0;2、将游戏信息的显示改到开始位置;3、将下一步要下棋的改为黑方

                        allChess=new int[19][19];

                        message="黑方先行";

                        blackTime=maxTime;

                        whiteTime=maxTime;

                        blackMessage=maxTime/3600+":"

                                +(maxTime/60-maxTime/3600*60)+":"

                                +(maxTime-maxTime/60*60);

                        whiteMessage=maxTime/3600+":"+

                                (maxTime/60-maxTime/3600*60)+":"

                                +(maxTime-maxTime/60*60);

                        isBlack=true;

                        t.resume();

                        //重新绘制棋盘

                        this.repaint();

                        }

                    }

                }catch(NumberFormatException e1){

                    JOptionPane.showMessageDialog(this, "请正确输入信息");

                }

            }

        //点击 游戏说明 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=214 &&e.getY()<=248) {

            JOptionPane.showMessageDialog(this," 这是一个五子棋游戏,黑白双方轮流下");

        }

        //点击 认输 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=344 &&e.getY()<=378) {

            int result=JOptionPane.showConfirmDialog(this,"是否确认认输?");

            if(result==0) {

                if(isBlack) {

                    JOptionPane.showMessageDialog(this,"黑方认输");

                }else {

                    JOptionPane.showMessageDialog(this,"白方认输");

                }

            }

        }

        //点击 关于 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=406 &&e.getY()<=438) {

            JOptionPane.showMessageDialog(this,"本游戏由@JiaHao制作,视频地址https://www.bilibili."

                    + "com/video/BV1kJ411s7zf?p=10&share_source=copy_web");

        }

        //点击 退出 按钮

        if(e.getX()>=508 && e.getX()<=595 &&e.getY()>=466 &&e.getY()<=501) {

            JOptionPane.showMessageDialog(this,"退出");

            System.exit(0);

        }

         

    }

    //判断什么棋子赢

    public boolean checKwin() {

        boolean flag=false;

        //判断横向的是否有五个棋子,特点 纵坐标是相同的即allChess[X][Y]中Y值是相同的

        int color=allChess[x][y];

        //保存共有多少相同颜色的棋子

        int count=1;

        //判断横向

        count=this.checkCount(1, 0, color);

        if(count>=5) {

            flag=true;

        }else {

            //判断纵向

            count=this.checkCount(0, 1, color);

            if(count>=5) {

                flag=true;

        }else {

            //右下

            count=this.checkCount(1, -1, color);

            if(count>=5) {

                flag=true;

            }else {

                //左上

                count=this.checkCount(-1, 1, color);

                if(count>=5) {

                    flag=true;

                    }else {

                        //右上

                        count=this.checkCount(1, 1, color);

                        if(count>=5) {

                            flag=true;

                    }else {

                        //左上

                        count=this.checkCount(-1,-1, color);

                        if(count>=5) {

                            flag=true;

                            }

                        }

                    }

                }

            }

        }

        return flag;

    }

    //判断棋子连接的数量

    private int checkCount(int xChange,int yChange,int color) {

        int count =1;

        int tempX=xChange;

        int tempY=yChange;

        while(x+xChange>=0 &&x+xChange<=18 && y+yChange>=0 &&y+yChange<=18 && color==allChess[x+xChange][y+yChange]) {

            count++;

            if(xChange!=0

                xChange++;

            if(yChange!=0) {

                if(yChange>0

                    yChange++;

                else {

                    yChange--;

                }

            }

        }

        xChange=tempY;

        yChange=tempX;

         

        while(color==allChess[x-xChange][y-yChange]) {

            count++;

            if(xChange!=0

                xChange++;

            if(yChange!=0) {

                if(yChange>0

                    yChange++;

                else {

                    yChange--;

                }

            }

        }

        return count;

         

    }

    @Override

    public void mouseReleased(MouseEvent e) {

        // TODO Auto-generated method stub

         

    }

    @Override

    public void mouseEntered(MouseEvent e) {

        // TODO Auto-generated method stub

         

    }

    @Override

    public void mouseExited(MouseEvent e) {

        // TODO Auto-generated method stub

         

    }

    @Override

    public void run() {

        // TODO Auto-generated method stub

        //判断是否有时间限制

        if(maxTime>0) {

            while(true) {

                if(isBlack) {

                    blackTime--;

                    if(blackTime==0) {

                        JOptionPane.showMessageDialog(this,"黑方超时,游戏结束");

                    }

                }else {

                    whiteTime--;

                    if(whiteTime==0) {

                        JOptionPane.showMessageDialog(this,"白方超时,游戏结束");

                    }

                }

                blackMessage=blackTime/3600+":"

                        +(blackTime/60-blackTime/3600*60)+":"

                        +(blackTime-blackTime/60*60);

                whiteMessage=whiteTime/3600+":"+

                        (whiteTime/60-whiteTime/3600*60)+":"

                        +(whiteTime-whiteTime/60*60);

                //刷新屏幕

                this.repaint();

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

}

编写完成,多多支持哦!

  • 27
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Java五子棋游戏实现示例: 首先,我们需要创建一个棋盘类来表示游戏状态。这个类应该包含一个二维数组来表示每个位置的棋子状态,一个方法来判断游戏是否结束,以及一些方法来放置棋子和计算得分等。 ```java public class ChessBoard { private int[][] board; private int size; private int winLength; public ChessBoard(int size, int winLength) { this.board = new int[size][size]; this.size = size; this.winLength = winLength; } public boolean placeChess(int x, int y, int color) { if (x < 0 || x >= size || y < 0 || y >= size || board[x][y] != 0) { return false; } board[x][y] = color; return true; } public boolean isGameOver() { return checkHorizontal() || checkVertical() || checkDiagonal(); } private boolean checkHorizontal() { for (int i = 0; i < size; i++) { for (int j = 0; j <= size - winLength; j++) { int count = 0; for (int k = 0; k < winLength; k++) { if (board[i][j+k] == board[i][j]) { count++; } } if (count == winLength) { return true; } } } return false; } private boolean checkVertical() { for (int i = 0; i <= size - winLength; i++) { for (int j = 0; j < size; j++) { int count = 0; for (int k = 0; k < winLength; k++) { if (board[i+k][j] == board[i][j]) { count++; } } if (count == winLength) { return true; } } } return false; } private boolean checkDiagonal() { for (int i = 0; i <= size - winLength; i++) { for (int j = 0; j <= size - winLength; j++) { int count1 = 0; int count2 = 0; for (int k = 0; k < winLength; k++) { if (board[i+k][j+k] == board[i][j]) { count1++; } if (board[i+k][j+winLength-1-k] == board[i][j]) { count2++; } } if (count1 == winLength || count2 == winLength) { return true; } } } return false; } public int getScore(int color) { int score = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (board[i][j] == color) { score++; } } } return score; } } ``` 接下来,我们需要创建一个玩家类来放置棋子。这个类可以通过控制台或图形用户界面实现。 ```java public class Player { private int color; public Player(int color) { this.color = color; } public int getColor() { return color; } public void makeMove(ChessBoard board) { Scanner scanner = new Scanner(System.in); System.out.print("Player " + color + " make a move (x y): "); int x = scanner.nextInt(); int y = scanner.nextInt(); if (!board.placeChess(x, y, color)) { System.out.println("Invalid move, please try again."); makeMove(board); } } } ``` 最后,我们需要创建一个游戏控制类来协调棋盘和玩家之间的交互。 ```java public class Game { private ChessBoard board; private Player[] players; private int currentPlayerIndex; public Game(int size, int winLength, Player[] players) { this.board = new ChessBoard(size, winLength); this.players = players; this.currentPlayerIndex = 0; } public void start() { while (!board.isGameOver()) { Player currentPlayer = players[currentPlayerIndex]; board.print(); currentPlayer.makeMove(board); currentPlayerIndex = (currentPlayerIndex + 1) % players.length; } board.print(); int winner = getWinner(); if (winner == 0) { System.out.println("Game ended in a draw."); } else { System.out.println("Player " + winner + " wins!"); } } private int getWinner() { int score1 = board.getScore(players[0].getColor()); int score2 = board.getScore(players[1].getColor()); if (score1 > score2) { return players[0].getColor(); } else if (score2 > score1) { return players[1].getColor(); } else { return 0; } } } ``` 现在我们可以创建两个玩家并启动游戏了: ```java public static void main(String[] args) { Player player1 = new Player(1); Player player2 = new Player(2); Game game = new Game(15, 5, new Player[] { player1, player2 }); game.start(); } ``` 这是一个非常基本的五子棋游戏实现示例,您可以根据自己的需要和技术水平进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值