java实现五子棋

java在初期就可以写一些简单的电脑小程序,使用GUI编程可以考验我们的代码能力

之后我会在出一个可能几万字的GUI编程入门,现在我们先看看五子棋,照片我放在最后

代码之后又详细解释

package 数字图像化处理AWT;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class Wu{

    //定义三个BufferedImage,分别代表棋盘图、黑子图、白子图
    private BufferedImage table;
    private BufferedImage black;
    private BufferedImage white;

    //定义一个BufferedImage,代表当鼠标移动时将要下子的选择框
    private BufferedImage selected;

    //定义棋盘的宽高,这里的定义尺寸和给定的board.jpg图片的尺寸一致因为棋盘背景是通过图片加载的
    private final int TABLE_WIDTH = 535;
    private final int TABLE_HEIGHT = 536;

    //定义棋盘中,每行和每列可下子的数目,这个数目跟给定的board.jpg中的数目是一致的,都为15
    private final int  BOARD_SIZE = 15;

    //定义每个棋子所占棋盘总宽度的大小比率;每个棋子所占宽度 535/15=35
    private final int RATE = TABLE_WIDTH/BOARD_SIZE;

    //定义棋盘有效区域与背景图坐标之间的偏移值,x坐标右移5个像素,y坐标下移6个像素
    private final int X_OFFSET = 5;
    private final int Y_OFFSET = 6;


    /*

        定义一个二维数组充当棋盘上每个位置处的棋子;
        该数组的索引与该棋子在棋盘上的坐标需要有一个对应关系:
            例如: 索引[2][3]处的棋子,对一个的真实绘制坐标应该是:

                xpos = 2*RATE+X_OFFSET=75;
                ypos = 3*RATE+Y_OFFSET=111;

     */
    private int[][] board = new int[BOARD_SIZE][BOARD_SIZE];//如果存储0,代表没有棋子,如果存储1,代表黑棋,如果存储2,代表白棋

    //定义五子棋游戏窗口
    private JFrame f = new JFrame("五子棋游戏");

    //定义五子棋游戏棋盘对应的Canvas组件
    private class ChessBoard extends JPanel{
        //重写paint方法,实现绘画
        @Override
        public void paint(Graphics g) {
            //绘制五子棋棋盘
            g.drawImage(table,0,0,null);
            //绘制选中点的红框
            if (selectX>0 && selectY>0){
                g.drawImage(selected,selectX*RATE+X_OFFSET,selectY*RATE+Y_OFFSET,null);
            }

            //遍历数组,绘制棋子
            for (int i = 0; i < BOARD_SIZE; i++) {
                for (int j = 0; j < BOARD_SIZE; j++) {
                    //绘制黑棋

                    if (board[i][j]==1){
                        g.drawImage(black,i*RATE+X_OFFSET,j*RATE+Y_OFFSET,null);
                    }

                    //绘制白棋
                    if (board[i][j]==2){
                        g.drawImage(white,i*RATE+X_OFFSET,j*RATE+Y_OFFSET,null);
                    }
                }
            }
        }
    }

    private ChessBoard chessBoard = new ChessBoard();

    //定义变量,记录当前选中的坐标点对应的boad数组中对应的棋子索引;
    private int selectX = -1;
    private int selectY = -1;

    //定义一个变量,记录当前用户选择下的是白棋还是黑棋还是清除,清除:0,黑棋:1,白棋:2;
    private int chessCategory = 1;

    //定义Panel,放置点击按钮
    Panel p = new Panel();
    private Button whiteBtn = new Button("while");
    private Button blackBtn = new Button("black");
    private Button clearBtn = new Button("clear");

    public void updateBtnColor(Color whiteBtnColor,Color blackBtnColor,Color clearBtnColor){
        whiteBtn.setBackground(whiteBtnColor);
        blackBtn.setBackground(blackBtnColor);
        clearBtn.setBackground(clearBtnColor);
    }

    public void init() throws Exception{

        //初始化按钮的颜色
        updateBtnColor(Color.LIGHT_GRAY,Color.GREEN,Color.LIGHT_GRAY);
        whiteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chessCategory = 2;
                updateBtnColor(Color.GREEN,Color.LIGHT_GRAY,Color.LIGHT_GRAY);
            }
        });
        blackBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chessCategory=1;
                updateBtnColor(Color.LIGHT_GRAY,Color.GREEN,Color.LIGHT_GRAY);
            }
        });
        clearBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chessCategory=0;
                updateBtnColor(Color.LIGHT_GRAY,Color.LIGHT_GRAY,Color.GREEN);
            }
        });

        p.add(whiteBtn);
        p.add(blackBtn);
        p.add(clearBtn);
        //把Panel放入到frame底部
        f.add(p,BorderLayout.SOUTH);



        //初始化黑棋,白棋,棋盘,选中框
        table = ImageIO.read(new File("img\\board.jpg"));
        black = ImageIO.read(new File("img\\black.gif"));
        white = ImageIO.read(new File("img\\white.gif"));
        selected = ImageIO.read(new File("img\\selected.gif"));
        //初始化board数组,默认情况下,所有位置处都没有棋子
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                board[i][j]=0;
            }
        }

        //设置chessBoard的最佳大小
        chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));

        //给chessBoard注册鼠标监听器
        chessBoard.addMouseListener(new MouseAdapter() {
            //鼠标单击会触发
            @Override
            public void mouseClicked(MouseEvent e) {
                //将用户鼠标的坐标,转换成棋子的坐标
                int xPos = (e.getX()-X_OFFSET)/RATE;
                int yPos = (e.getY()-Y_OFFSET)/RATE;

                board[xPos][yPos] = chessCategory;

                //重绘chessBoard
                chessBoard.repaint();
            }

            //当鼠标退出棋盘区域后,复位选中坐标,重绘chessBoard,要保证红色选中框显示正确
            @Override
            public void mouseExited(MouseEvent e) {
                selectX=-1;
                selectY=-1;
                chessBoard.repaint();
            }
        });

        //给chessBoard注册鼠标移动监听器
        chessBoard.addMouseMotionListener(new MouseMotionAdapter() {
            //当鼠标移动时,修正selectX和selectY,重绘chessBoard,要保证红色选中框显示正确
            @Override
            public void mouseMoved(MouseEvent e) {
                //将鼠标的坐标,转换成棋子的索引
                selectX = (e.getX()-X_OFFSET)/RATE;
                selectY = (e.getY()-Y_OFFSET)/RATE;
                chessBoard.repaint();
            }
        });

        //把chessBoard添加到Frame中
        f.add(chessBoard);



        //设置frame最佳大小并可见
        f.pack();
        f.setVisible(true);

    }

    public static void main(String[] args) throws Exception{
        new Wu().init();
    }

}

项目所需图片 

 

  • 24
    点赞
  • 97
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 27
    评论
简单 五子棋的客户端部分程序 //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(); } }
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

海绵hong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值