新手学java-运用数组写一个五子棋小程序

package GoBang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GoBang {
    //定义棋盘大小
    private static int BOARD_SIZE=15;
    //定义一个二维数组来充当棋盘
    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++)
            {
                board[i][j]="+";
            }
        }
    }   
        //在控制台输出棋盘方法        
    public void printBoard(){

        //打印每组数组元素
        for(int i=0;i<BOARD_SIZE;i++){
            for (int j=0;j<BOARD_SIZE;j++)
            {//打印数组元素后不换行
                System.out.print(board[i][j]);
            }
            //每打印完一行数组后输出一个换行符
            System.out.print("\n");
        }   
    }       
    public static void main(String[] args) {
        GoBang gb=new GoBang();
        gb.initBoard();
        gb.printBoard();
        //这是用于获取键盘输入的方法
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String inputStr=null;
        //br.readLine();每当键盘输入一行内容后按回车键,刚输入的内容将会被br读取到
        try {
            while((inputStr=br.readLine())!=null){
                //将用户输入的字符串以逗号作为分隔符,分割成两个字符
                String[]posStrArr =inputStr.split(",");
                //将两个字符串转换为用户下棋的坐标
                int  xPos=Integer.parseInt(posStrArr[0]);
                int  yPos=Integer.parseInt(posStrArr[1]);
                //把对应的数组元素赋为"."
                gb.board[yPos-1][xPos-1]=".";
                gb.printBoard();
                System.out.println("请输入你的下棋坐标,应以x,y的格式");


            }
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }




    }

}

代码运行示例
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
1,5
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
.++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
请输入你的下棋坐标,应以x,y的格式
4,6
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
.++++++++++++++
+++.+++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
+++++++++++++++
请输入你的下棋坐标,应以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(); } }
java五子棋 五子棋 java 五子棋代码直接和电脑下对战 Public class FiveChessAI { public int data_a[][] = new int[5][3];// 用于储存进攻值 public int data_d[][] = new int[5][3];// 用于储存防守值 FiveChessAI() { // 进攻值的初始化 data_a[1][1] = 2; data_a[1][2] = 3; data_a[2][1] = 10; data_a[2][2] = 110; data_a[3][1] = 2500; data_a[3][2] = 3000; data_a[4][1] = 99999; data_a[4][2] = 99999; // 防守值的初始化 data_d[1][1] = 1; data_d[1][2] = 2; data_d[2][1] = 1; data_d[2][2] = 100; data_d[3][1] = 100; data_d[3][2] = 500; data_d[4][1] = 20000; data_d[4][2] = 50000; } public FiveChessMap g1 = new FiveChessMap(); public int x, y; void find()// 查找最大值 { int max = 0; for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (max < g1.data[i][j]) { max = g1.data[i][j]; } } } for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (max == g1.data[i][j]) { x = i; y = j; return; } } } } int getx()// 返回x坐标值 { return x; } int gety()// 返回y坐标值 { return y; } boolean judge_result(int x, int y, int who, FiveChessMap gm)// 判断胜负 { int m, n, i, lianzi = 0; for (m = -1; m <= 1; m++) for (n = -1; n <= 1; n++) { if (m != 0 || n != 0) { for (i = 1; i <= 4; i++) { if (x + i * m >= 0 && x + i * m < 15 && y + i * n >= 0 && y + i * n < 15 && gm.data[x + i * m][y + i * n] == who) { lianzi++; } else { break; } } for (i = -1; i >= -4; i--) { if (x + i * m >= 0 && x + i * m < 15 && y + i * n >= 0 && y + i * n < 15 && gm.data[x + i * m][y + i * n] == who) { lianzi++; } else { break; } } if (lianzi >= 4) { return true; } else { lianzi = 0; } } } return false; }
好的,下面是一个简单的五子棋人机对弈小程序的示例代码,基于 Java Swing 编。 ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Gobang extends JFrame implements ActionListener, MouseListener { private static final long serialVersionUID = 1L; private JPanel panel; private JButton button; private JLabel label1, label2; private int[][] chessBoard; private boolean isBlack = true; private boolean gameOver = false; private final int ROWS = 15; private final int COLS = 15; private final int SIZE = 30; private final int MARGIN = 30; public Gobang() { setTitle("五子棋"); setSize(600, 600); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); init(); setVisible(true); } private void init() { panel = new JPanel(); panel.setBackground(new Color(255, 204, 102)); panel.setLayout(null); panel.addMouseListener(this); button = new JButton("重新开始"); button.addActionListener(this); button.setBounds(450, 120, 100, 40); label1 = new JLabel("黑方先手"); label1.setFont(new Font("宋体", Font.BOLD, 20)); label1.setBounds(450, 200, 150, 40); label2 = new JLabel("轮到黑方"); label2.setFont(new Font("宋体", Font.BOLD, 20)); label2.setBounds(450, 250, 150, 40); panel.add(button); panel.add(label1); panel.add(label2); add(panel); chessBoard = new int[ROWS][COLS]; } private void drawChessBoard(Graphics g) { for (int i = 0; i <= ROWS; i++) { g.drawLine(MARGIN, MARGIN + i * SIZE, MARGIN + COLS * SIZE, MARGIN + i * SIZE); } for (int i = 0; i <= COLS; i++) { g.drawLine(MARGIN + i * SIZE, MARGIN, MARGIN + i * SIZE, MARGIN + ROWS * SIZE); } } private void drawChessPiece(Graphics g, int row, int col, boolean isBlack) { int x = MARGIN + col * SIZE; int y = MARGIN + row * SIZE; g.setColor(isBlack ? Color.BLACK : Color.WHITE); g.fillOval(x - SIZE / 2, y - SIZE / 2, SIZE, SIZE); } private boolean checkWin(int row, int col) { int count = 1; int color = chessBoard[row][col]; int r, c; // 检查水平方向 r = row; c = col - 1; while (c >= 0 && chessBoard[r][c] == color) { count++; c--; } c = col + 1; while (c < COLS && chessBoard[r][c] == color) { count++; c++; } if (count >= 5) { return true; } // 检查竖直方向 count = 1; r = row - 1; c = col; while (r >= 0 && chessBoard[r][c] == color) { count++; r--; } r = row + 1; while (r < ROWS && chessBoard[r][c] == color) { count++; r++; } if (count >= 5) { return true; } // 检查左斜方向 count = 1; r = row - 1; c = col - 1; while (r >= 0 && c >= 0 && chessBoard[r][c] == color) { count++; r--; c--; } r = row + 1; c = col + 1; while (r < ROWS && c < COLS && chessBoard[r][c] == color) { count++; r++; c++; } if (count >= 5) { return true; } // 检查右斜方向 count = 1; r = row - 1; c = col + 1; while (r >= 0 && c < COLS && chessBoard[r][c] == color) { count++; r--; c++; } r = row + 1; c = col - 1; while (r < ROWS && c >= 0 && chessBoard[r][c] == color) { count++; r++; c--; } if (count >= 5) { return true; } return false; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { chessBoard = new int[ROWS][COLS]; isBlack = true; gameOver = false; label1.setText("黑方先手"); label2.setText("轮到黑方"); panel.repaint(); } } @Override public void mouseClicked(MouseEvent e) { if (gameOver) { return; } int x = e.getX(); int y = e.getY(); if (x < MARGIN || x > MARGIN + COLS * SIZE || y < MARGIN || y > MARGIN + ROWS * SIZE) { return; } int row = Math.round((float) (y - MARGIN) / SIZE); int col = Math.round((float) (x - MARGIN) / SIZE); if (chessBoard[row][col] != 0) { return; } chessBoard[row][col] = isBlack ? 1 : 2; panel.repaint(); if (checkWin(row, col)) { gameOver = true; String winner = isBlack ? "黑方" : "白方"; JOptionPane.showMessageDialog(panel, winner + "获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return; } isBlack = !isBlack; label1.setText(isBlack ? "黑方先手" : "白方先手"); label2.setText(isBlack ? "轮到黑方" : "轮到白方"); if (!isBlack) { // AI 下棋 int[] pos = computeNextMove(); row = pos[0]; col = pos[1]; chessBoard[row][col] = 2; panel.repaint(); if (checkWin(row, col)) { gameOver = true; JOptionPane.showMessageDialog(panel, "白方获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return; } isBlack = !isBlack; label1.setText(isBlack ? "黑方先手" : "白方先手"); label2.setText(isBlack ? "轮到黑方" : "轮到白方"); } } private int[] computeNextMove() { int[] pos = new int[2]; // TODO: AI 算法 return pos; } @Override public void paint(Graphics g) { super.paint(g); drawChessBoard(g); for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { if (chessBoard[i][j] == 1) { drawChessPiece(g, i, j, true); } else if (chessBoard[i][j] == 2) { drawChessPiece(g, i, j, false); } } } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} public static void main(String[] args) { new Gobang(); } } ``` 这个程序由一个主窗口和一个 JPanel 组成。主窗口负责创建并显示 JPanel,JPanel 则绘制棋盘和棋子,并处理用户交互和游戏逻辑。 在 JPanel 的构造函数,我们初始化了棋盘数组 `chessBoard`,表示棋盘上每个格子的状态。1 表示黑子,2 表示白子,0 表示空格。我们还添加了一个按钮和两个标签,用于重新开始游戏和显示游戏状态。 在 `drawChessBoard` 方法,我们使用 Graphics 类的 `drawLine` 方法绘制棋盘的线条。 在 `drawChessPiece` 方法,我们使用 Graphics 类的 `fillOval` 方法绘制棋子。黑子用黑色填充,白子用白色填充。 在 `checkWin` 方法,我们检查棋盘上某个格子所处的行、列、左斜方向和右斜方向是否有连续五个相同颜色的棋子。如果有,则游戏结束。 在 `actionPerformed` 方法,我们对重新开始按钮的点击事件进行处理。重新初始化棋盘数组、重置游戏状态和标签,并调用 JPanel 的 `repaint` 方法刷新界面。 在 `mouseClicked` 方法,我们处理鼠标点击事件。如果游戏已经结束或点击了棋盘外部或已经有棋子存在,则不做任何处理。否则,我们根据鼠标点击坐标计算出所在的行和列,将这个位置设为当前玩家下的棋子。然后检查游戏是否结束,并切换当前玩家。如果当前玩家是电脑,则调用 `computeNextMove` 方法计算出下一个位置,并执行相同的操作。 在 `paint` 方法,我们使用 Graphics 类的 `paint` 方法绘制棋盘和棋子。 在 `computeNextMove` 方法,我们需要实现一个 AI 算法,来计算出电脑下一步应该走的位置。这里我们暂时留空,可以自己实现一个简单的算法,比如随机生成一个空白位置,作为电脑的下一步。 最后,在 `main` 方法,我们创建一个新的 Gobang 对象,启动程序。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值