Java五子棋控制台小程序

本文详细介绍了如何利用二维数组在控制台上实现五子棋游戏,包括棋盘初始化、输入坐标、下棋规则、胜负判断等关键步骤。通过编程实例,展示了五子棋游戏的基本开发流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在浏览李刚那本疯狂Java讲义时看到上面有个五子棋的小程序例题练习,书上面已经实现了一部分功能,正好没什么事就自己在书上例题的基础上进行丰富完善,修改。

对于写一个五子棋游戏,肯定第一件事就是建立一个棋盘,而这个棋盘是个平面图形所以使用二维函数来作为棋盘的载体。
棋盘的初始化代码如下:

    private static int BOARD_SIZE = 16;   //定义棋盘的大小
    private String[][] board;             //定义一个二维数组来充当棋盘
    public void initBoard()
    {
        board = new String[BOARD_SIZE][BOARD_SIZE]; //初始化棋盘数组
        //把每个元素赋为"╋",用于在控制台画出棋盘
        for(int i = 0; i < BOARD_SIZE; i++)
        {
            for(int j = 0; j < BOARD_SIZE; j++)
            {
                if(i == 0)
                {
                    if(j==0)
                        board[i][j] = " 0"; 
                    if(j >= 10)
                        board[i][j] = String.valueOf(j) ;
                    else
                        board[i][j] =" " + String.valueOf(j) ;
                }
                else if(j == 0 && i != 0)
                {
                    if(i>=10)
                        board[i][j] = String.valueOf(i);
                    else
                        board[i][j] = " " + String.valueOf(i) ;
                }
                else
                    board[i][j] = "╋";
            }
        }
    }

    public void printBoard()    //在控制台上输出棋盘的方法
    {
        for(int j = 0; j < BOARD_SIZE; j++)   //打印每个数组元素
        {
            for(int i = 0; i < BOARD_SIZE; i++)
                System.out.print(board[i][j]);
            System.out.print("\n");
        }
    }

其中 public void initBoard() 方法就是对棋盘进行初始化,生成一个15*15大小的棋盘,其中还有一行和一竖则是用于对棋盘的行数和列数进行标记。
public void printBoard() 方法就是使用循环输出该棋盘。

建立棋盘后接下来我们就应该输入我们下棋的坐标,但是如何接受从键盘输入的信息呢?

    //这是用于获取键盘输入的方法
    BufferedReader  br =newBufferedReader(newInputStreamReader(System.in));
    String inputStr = null;
    //br.readLine():每当在键盘上输入一行内容按回车,用户刚输入的内容将被br读取到。

在接收到键盘的信息后就可以对信息进行分析从而得到我们想要下棋的坐标位置,再把相应的坐标的二维数组元素的值替换成我们的“棋子”然后在通过public void printBoard() 方法输出,则完成下棋的步骤。

但如何完成两个人互相下棋棋子的相互交换呢?
我这里使用了 int flag = -1; 作为标记 每次循环 flag = flag*(-1); 以判断正负来控制两个棋手的交替下棋。

最后的重点就是如何判断输赢:我之前想的是遍历整个棋盘来判断是否出现五个连续相同的棋子,但是工程量太大了,时间复杂度也很大,所以不宜采用这种方法。
但是应该通过什么方式判别输赢呢,如果仔细考虑你可以发现,我们是每下一步棋后才会出现输赢的判断,而之前没有;可以判定的是这最后的一个动作导致了棋盘上出现了五个连续的棋子。所以我们只需要判断该棋子的上下,左右,左斜,右斜是否出现了五个相同棋子即可判定出是否赢了!!

该方法如下:

public boolean  judge( String sign, int xPos, int yPos)
    {
        int i = 0, j = 0, add = 0;     //i,j用来标记有没有遍历完棋子四周与该棋子相同的棋子;
                                       //add移动变量表示每次循环加1,使要比较的棋子向固定的方向逐渐移动。
        int count1 = 0, count2 = 0;    //count1,count2用来记录在一个方向上有多少相同的棋子
        int up = 0, down = 0, left = 0, right = 0;   //用来标记是否在一个方向上遍历完毕

        while( i != 4 )
        {
            add++;     //移动变量每循环一次加1

            if(up == 0){
                if(board[xPos][yPos-add].equals(sign))     //判断是否与刚输入的棋子相同
                    count1++;                              //相同则计数加1
                else
                    up = 1;                                //不相同则标记up=1,表示结束在该方向上的遍历
            }
            if(down == 0){
                if(board[xPos][yPos+add].equals(sign))     //以下的语句同上
                    count1++;
                else
                    down = 1;
            }
            if(left == 0){
                if(board[xPos-add][yPos].equals(sign))
                    count2++;
                else
                    left = 1;
            }
            if(right == 0){
                if(board[xPos-add][yPos].equals(sign))
                    count2++;
                else
                    right = 1;
            }
            if(count1 == 4 || count2 == 4)      //如果检测到count==4,包括刚输入的棋子,棋子数达到5个,返回true。
                return true;
            i = up + down + left + down;
        }
        add=0;
        count1 = 0; count2 = 0;
        int leftUp = 0, leftDown = 0, rightUp = 0, rightDown = 0;

        while( j != 4 )
        {
            add++;

            if(leftUp == 0){
                if(board[xPos-add][yPos-add].equals(sign))
                    count1++;
                else
                    leftUp = 1;
            }
            if(leftDown == 0){
                if(board[xPos+add][yPos+add].equals(sign))
                    count1++;
                else
                    leftDown = 1;
            }
            if(rightUp == 0){
                if(board[xPos+add][yPos-add].equals(sign))
                    count2++;
                else
                    rightUp = 1;
            }
            if(rightDown == 0){
                if(board[xPos-add][yPos+add].equals(sign))
                    count2++;
                else
                    rightDown = 1;
            }
            if(count1 == 4 || count2 == 4)
                return true;
            j = leftUp + leftDown + rightUp + rightDown;
        }
        return false;   
    }

该程序在控制台上的运行效果如下:

最后贴上整个程序的源代码~~~

/*
需求:利用二维数组在控制台上实现五子棋。
*/

import java.io.*;
import  java.util.Arrays;

class  Gobang
{
    private static int BOARD_SIZE = 16;   //定义棋盘的大小
    private String[][] board;             //定义一个二维数组来充当棋盘

    public void initBoard()
    {
        board = new String[BOARD_SIZE][BOARD_SIZE]; //初始化棋盘数组

        //把每个元素赋为"╋",用于在控制台画出棋盘
        for(int i = 0; i < BOARD_SIZE; i++)
        {
            for(int j = 0; j < BOARD_SIZE; j++)
            {
                if(i == 0)
                {
                    if(j==0)
                        board[i][j] = " 0"; 
                    if(j >= 10)
                        board[i][j] = String.valueOf(j) ;
                    else
                        board[i][j] =" " + String.valueOf(j) ;
                }
                else if(j == 0 && i != 0)
                {
                    if(i>=10)
                        board[i][j] = String.valueOf(i);
                    else
                        board[i][j] = " " + String.valueOf(i) ;
                }

                else
                    board[i][j] = "╋";
            }
        }
    }

    public void printBoard()    //在控制台上输出棋盘的方法
    {
        for(int j = 0; j < BOARD_SIZE; j++)   //打印每个数组元素
        {
            for(int i = 0; i < BOARD_SIZE; i++)
                System.out.print(board[i][j]);
            System.out.print("\n");
        }
    }

    //通过判断刚刚输入的棋子在棋盘上有没有产生5个连续的同样棋子来输出输赢。
    public boolean  judge( String sign, int xPos, int yPos)
    {
        int i = 0, j = 0, add = 0;     //i,j用来标记有没有遍历完棋子四周与该棋子相同的棋子;
                                       //add移动变量表示每次循环加1,使要比较的棋子向固定的方向逐渐移动。
        int count1 = 0, count2 = 0;    //count1,count2用来记录在一个方向上有多少相同的棋子
        int up = 0, down = 0, left = 0, right = 0;   //用来标记是否在一个方向上遍历完毕

        while( i != 4 )
        {
            add++;     //移动变量每循环一次加1

            if(up == 0){
                if(board[xPos][yPos-add].equals(sign))     //判断是否与刚输入的棋子相同
                    count1++;                              //相同则计数加1
                else
                    up = 1;                                //不相同则标记up=1,表示结束在该方向上的遍历
            }
            if(down == 0){
                if(board[xPos][yPos+add].equals(sign))     //以下的语句同上
                    count1++;
                else
                    down = 1;
            }
            if(left == 0){
                if(board[xPos-add][yPos].equals(sign))
                    count2++;
                else
                    left = 1;
            }
            if(right == 0){
                if(board[xPos-add][yPos].equals(sign))
                    count2++;
                else
                    right = 1;
            }
            if(count1 == 4 || count2 == 4)                     //如果检测到count==4,包括刚输入的棋子,棋子数达到5个,返回true。
                return true;
            i = up + down + left + down;
        }

        add=0;
        count1 = 0; count2 = 0;
        int leftUp = 0, leftDown = 0, rightUp = 0, rightDown = 0;

        while( j != 4 )
        {
            add++;

            if(leftUp == 0){
                if(board[xPos-add][yPos-add].equals(sign))
                    count1++;
                else
                    leftUp = 1;
            }
            if(leftDown == 0){
                if(board[xPos+add][yPos+add].equals(sign))
                    count1++;
                else
                    leftDown = 1;
            }
            if(rightUp == 0){
                if(board[xPos+add][yPos-add].equals(sign))
                    count2++;
                else
                    rightUp = 1;
            }
            if(rightDown == 0){
                if(board[xPos-add][yPos+add].equals(sign))
                    count2++;
                else
                    rightDown = 1;
            }
            if(count1 == 4 || count2 == 4)
                return true;
            j = leftUp + leftDown + rightUp + rightDown;
        }
        return false;   
    }

    public static void main(String[] args)  throws  Exception 
    {
        Gobang gb = new Gobang();
        gb.initBoard();
        gb.printBoard();
        System.out.print("请*小欢*输入您下棋的坐标,以 x,y 的格式:");

        //这是用于获取键盘输入的方法
        BufferedReader  br = new BufferedReader(new InputStreamReader(System.in));
        String inputStr = null;

        int flag = -1;
        //br.readLine():每当在键盘上输入一行内容按回车,用户刚输入的内容将被br读取到。
        while((inputStr = br.readLine()) != null)
        {
            String[] posStrArr = inputStr.split(","); //将用户输入的字符串以逗号(,)作为分隔符,分割成两个字符串。

            //将两个字符串转换成用户下棋的坐标
            int xPos = Integer.parseInt(posStrArr[0]);
            int yPos = Integer.parseInt(posStrArr[1]);


            if(xPos > 16 || yPos > 16 || xPos < 1 || yPos < 1)
            {
                if(flag < 0 )
                    System.out.print("你个傻欢,输错了(超出边界了)!!!  请重新输入: ");
                else
                    System.out.print("你个傻丹,输错了(超出边界了)!!!  请重新输入:");

                continue;
            }
            if(gb.board[xPos][yPos].equals("●") || gb.board[xPos][yPos].equals("○"))
            {
                if(flag < 0 )
                    System.out.print("你个傻欢,输错了(已经这个地方已经有棋子了)!!!  请重新输入: ");
                else
                    System.out.print("你个傻丹,输错了(已经这个地方已经有棋子了)!!!  请重新输入:");

                continue;
            }

            if(flag < 0)
            {
                gb.board[xPos][yPos] = "●";     //把对应的数组元素赋为"●".
                gb.printBoard();
                if(gb.judge( "●", xPos, yPos)){
                    System.out.println("***恭喜你,哈哈,逗欢你赢了!!!***");
                    break;
                }
            }       
            else
            {
                gb.board[xPos][yPos] = "○";
                gb.printBoard();
                if(gb.judge( "○", xPos, yPos)){
                    System.out.println("***恭喜你,哈哈,逗丹你赢了!!!***");
                    break;
                }
            }

            flag = flag*(-1);

            if(flag < 0)
                System.out.print("请*小欢*输入您下棋的坐标,以 x,y 的格式:");
            else
                System.out.print("请*小丹*输入您下棋的坐标,以 x,y 的格式:");
        }
    }
}
简单 五子棋的客户端部分程序 //chessClient.java:客户端主程序。 //userPad.java:客户端的界面。 //chessPad.java:棋盘的绘制。 //chessServer.java:服务器端。 //可同时容纳50个人同时在线下棋,聊天。 import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class clientThread extends Thread{ chessClient chessclient; clientThread(chessClient chessclient){ this.chessclient=chessclient; } public void acceptMessage(String recMessage){ if(recMessage.startsWith("/userlist ")){ StringTokenizer userToken=new StringTokenizer(recMessage," "); int userNumber=0; chessclient.userpad.userList.removeAll(); chessclient.inputpad.userChoice.removeAll(); chessclient.inputpad.userChoice.addItem("所有人"); while(userToken.hasMoreTokens()){ String user=(String)userToken.nextToken(" "); if(userNumber>0 && !user.startsWith("[inchess]")){ chessclient.userpad.userList.add(user); chessclient.inputpad.userChoice.addItem(user); } userNumber++; } chessclient.inputpad.userChoice.select("所有人"); } else if(recMessage.startsWith("/yourname ")){ chessclient.chessClientName=recMessage.substring(10); chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName); } else if(recMessage.equals("/reject")){ try{ chessclient.chesspad.statusText.setText("不能加入游戏"); chessclient.controlpad.cancelGameButton.setEnabled(false); chessclient.controlpad.joinGameButton.setEnabled(true); chessclient.controlpad.creatGameButton.setEnabled(true); } catch(Exception ef){ chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭"); } chessclient.controlpad.joinGameButton.setEnabled(true); } else if(recMessage.startsWith("/peer ")){ chessclient.chesspad.chessPeerName=recMessage.substring(6); if(chessclient.isServer){ chessclient.chesspad.chessColor=1; chessclient.chesspad.isMouseEnabled=true; chessclient.chesspad.statusText.setText("请黑棋下子"); } else if(chessclient.isClient){ chessclient.chesspad.chessColor=-1; chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子..."); } } else if(recMessage.equals("/youwin")){ chessclient.isOnChess=false; chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor); chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接"); chessclient.chesspad.isMouseEnabled=false; } else if(recMessage.equals("/OK")){ chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入..."); } else if(recMessage.equals("/error")){ chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n"); } else{ chessclient.chatpad.chatLineArea.append(recMessage+"\n"); chessclient.chatpad.chatLineArea.setCaretPosition( chessclient.chatpad.chatLineArea.getText().length()); } } public void run(){ String message=""; try{ while(true){ message=chessclient.in.readUTF(); acceptMessage(message); } } catch(IOException es){ } } } public class chessClient extends Frame implements ActionListener,KeyListener{ userPad userpad=new userPad(); chatPad chatpad=new chatPad(); controlPad controlpad=new controlPad(); chessPad chesspad=new chessPad(); inputPad inputpad=new inputPad(); Socket chatSocket; DataInputStream in; DataOutputStream out; String chessClientName=null; String host=null; int port=4331; boolean isOnChat=false; //在聊天? boolean isOnChess=false; //在下棋? boolean isGameConnected=false; //下棋的客户端连接? boolean isServer=false; //如果是下棋的主机 boolean isClient=false; //如果是下棋的客户端 Panel southPanel=new Panel(); Panel northPanel=new Panel(); Panel centerPanel=new Panel(); Panel westPanel=new Panel(); Panel eastPanel=new Panel(); chessClient( ){ super("Java五子棋客户端"); setLayout(new BorderLayout()); host=controlpad.inputIP.getText(); westPanel.setLayout(new BorderLayout()); westPanel.add(userpad,BorderLayout.NORTH); westPanel.add(chatpad,BorderLayout.CENTER); westPanel.setBackground(Color.pink); inputpad.inputwords.addKeyListener(this); chesspad.host=controlpad.inputIP.getText(); centerPanel.add(chesspad,BorderLayout.CENTER); centerPanel.add(inputpad,BorderLayout.SOUTH); centerPanel.setBackground(Color.pink); controlpad.connectButton.addActionListener(this); controlpad.creatGameButton.addActionListener(this); controlpad.joinGameButton.addActionListener(this); controlpad.cancelGameButton.addActionListener(this); controlpad.exitGameButton.addActionListener(this); controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(false); southPanel.add(controlpad,BorderLayout.CENTER); southPanel.setBackground(Color.pink); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ if(isOnChat){ try{ chatSocket.close(); }catch(Exception ed){ } } if(isOnChess || isGameConnected){ try{ chesspad.chessSocket.close(); }catch(Exception ee){ } } System.exit(0); } public void windowActivated(WindowEvent ea){ } }); add(westPanel,BorderLayout.WEST); add(centerPanel,BorderLayout.CENTER); add(southPanel,BorderLayout.SOUTH); pack(); setSize(670,548); setVisible(true); setResizable(false); validate(); } public boolean connectServer(String serverIP,int serverPort) throws Exception{ try{ chatSocket=new Socket(serverIP,serverPort); in=new DataInputStream(chatSocket.getInputStream()); out=new DataOutputStream(chatSocket.getOutputStream()); clientThread clientthread=new clientThread(this); clientthread.start(); isOnChat=true; return true; } catch(IOException ex){ chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n"); } return false; } public void actionPerformed(ActionEvent e){ if(e.getSource()==controlpad.connectButton){ host=chesspad.host=controlpad.inputIP.getText(); try{ if(connectServer(host,port)){ chatpad.chatLineArea.setText(""); controlpad.connectButton.setEnabled(false); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); chesspad.statusText.setText("连接成功,请创建游戏或加入游戏"); } } catch(Exception ei){ chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n"); } } if(e.getSource()==controlpad.exitGameButton){ if(isOnChat){ try{ chatSocket.close(); } catch(Exception ed){ } } if(isOnChess || isGameConnected){ try{ chesspad.chessSocket.close(); } catch(Exception ee){ } } System.exit(0); } if(e.getSource()==controlpad.joinGameButton){ String selectedUser=userpad.userList.getSelectedItem(); if(selectedUser==null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)){ chesspad.statusText.setText("必须先选定一个有效用户"); } else{ try{ if(!isGameConnected){ if(chesspad.connectServer(chesspad.host,chesspad.port)){ isGameConnected=true; isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } }else{ isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } } catch(Exception ee){ isGameConnected=false; isOnChess=false; isClient=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee); } } } if(e.getSource()==controlpad.creatGameButton){ try{ if(!isGameConnected){ if(chesspad.connectServer(chesspad.host,chesspad.port)){ isGameConnected=true; isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } }else{ isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } } catch(Exception ec){ isGameConnected=false; isOnChess=false; isServer=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); ec.printStackTrace(); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec); } } if(e.getSource()==controlpad.cancelGameButton){ if(isOnChess){ chesspad.chessthread.sendMessage("/giveup "+chessClientName); chesspad.chessVictory(-1*chesspad.chessColor); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } if(!isOnChess){ controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } isClient=isServer=false; } } public void keyPressed(KeyEvent e){ TextField inputwords=(TextField)e.getSource(); if(e.getKeyCode()==KeyEvent.VK_ENTER){ if(inputpad.userChoice.getSelectedItem().equals("所有人")){ try{ out.writeUTF(inputwords.getText()); inputwords.setText(""); } catch(Exception ea){ chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputwords.setText(""); controlpad.connectButton.setEnabled(true); } } else{ try{ out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputwords.getText()); inputwords.setText(""); } catch(Exception ea){ chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputwords.setText(""); controlpad.connectButton.setEnabled(true); } } } } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} public static void main(String args[]){ chessClient chessClient=new chessClient(); } }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值