五子棋设计与实现

前 言

   五子棋是起源于中国古代的传统黑白棋种之一。现代五子棋日文称之为“連珠”,英译为“Renju”,英文称之为“Gobang”或“FIR”(Five in a Row的缩写),亦有“连五子”、“五子连”、“串珠”、“五目”、“五目碰”、“五格”等多种称谓。

五子棋不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。五子棋既有现代休闲的明显特征“短、平、快”,又有古典哲学的高深学问“阴阳易理”;它既有简单易学的特性,为人民群众所喜闻乐见,又有深奥的技巧和高水平的国际性比赛;它的棋文化源渊流长,具有东方的神秘和西方的直观;既有“场”的概念,亦有“点”的连接。它是中西文化的交流点,是古今哲理的结晶。


目  录

  

Abstract

第1章 项目概述

1.1 项目背景

1.2 任务概述

第2章 界面设计

2.1 服务端

2.2 客户端

第3章 构造阶段

3.1 核心代码

第4章 论文小结

    

参考文献

摘  要

目前,以计算机技术和网络技术为核心的现代网络技术已在现实生活和生产中得以广泛的使用,休闲类网络游戏集趣味性,娱乐性,互动性和益智性于一体,已经成为多数人群的休闲方式。 本软件使用C#实现,通过对SCOKET技术的理解,在此基础上建立服务器与多客户端的连接,利用多线程处理多个客户端之间的信息。 通过对软件的编写,加深对以上技术的理解和掌握。大厅五子棋的开发能够是朋友们不见面也能下棋和聊天。

关 键 字

多线程;流套接字

Abstract

At present, computer technology and network technology as the core of modern network technology has been in real life and production to be widely used set of casual online games fun, entertaining, interactive and puzzle in one sex has become the majority population of leisure. The software uses the C # to achieve, through SCOKET understanding of technology, in this based on the server and multiple client connections, using multi-threaded processing of information between multiple clients. Through the preparation of the software to enhance the above techniques to understand and grasp. Hall Gobang development can not even meet with friends who can also play chess and chat.Keywords

Multithreading; Stream Sockets

  1.  项目概述
    1. 项目背景

当前网络上流传的五子棋游戏功能并不尽善尽美,其中最主要的问题就是人机对战和网络对战不能够一起实现,所以我决定开发一个既能够人机对战,又能够进行网络对战的五子棋系统。

    1.  任务概述
      1. 实现目标
  1. 实现在线下棋
  2. 实现多人在线互动交互.

  1.  界面设计
    1. 服务端
      1. 初始

如图2. 1 初始

图2. 1 初始

      1. 启动服务

如图2. 2 启动服务

图2. 2 启动服务

    1. 客户端
      1. 初始

如图2. 3 初始

图2. 3 初始

      1. 连接服务端

如图2. 4 连接服务器

图2. 4 连接服务器

      1. 会员登陆

如图2. 5 会员登陆

图2. 5 会员登陆

      1. 游戏界面

如图2. 6 游戏界面1

如图2. 7 游戏界面2

如图2. 8 游戏界面3

图2. 6 游戏界面1

图2. 7 游戏界面2

图2. 8 游戏界面3

  1.  构造阶段
    1. 核心代码
      1.   服务端  

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net.Sockets;

using System.Net;

using System.Threading;

using System.Collections;

using System.Data.SqlClient;

namespace FiveServer

{

    public partial class FiveServer : Form

    {

        private Socket mainSocket;

        public delegate void UpdateRichEditCallback(string text);

        public delegate void UpdateClientListCallback();

        public AsyncCallback pfnWorkerCallback;

        public string username;

        public int  userpicture;

        private ArrayList workerSocketList = ArrayList.Synchronized(new ArrayList());

        private int clientNum = 0;//客户的编号

        private string all_table;//所有房间座位信息

        static public string clientmsg="";

        public FiveServer()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            try

            {

                if (txtPort.Text == "")

                {

                    MessageBox.Show("请先填写服务器端口!", "提示");

                    return;

                }

                Int32 port = Int32.Parse(txtPort.Text);

                mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);

                mainSocket.Bind(localEP);//将socket绑定到本地终接点上

                mainSocket.Listen(5);

                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);//开始一个异步操作接受客户的连接请求

                UpdateControls(true);

            }

            catch (SocketException se)

            {

                MessageBox.Show(se.Message, "提示");

            }

        }

        private void FiveServer_Load(object sender, EventArgs e)

        {

            try

            {

                txtIP.Text = Dns.Resolve(Dns.GetHostName()).AddressList[0].ToString();

                UpdateControls(false);

            }

            catch (Exception exc)

            {

                MessageBox.Show(exc.Message, "提示");

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            CloseSockets();

            UpdateControls(false);

            UpdateClientListControl();//更新客户列表

        }

        private void button5_Click(object sender, EventArgs e)//发送

        {

            if (clientList.Items.Count != 0)

            {

                try

                {

                    string msg = txtSendMsg.Text;

                    msg = "####" + msg + "\n";

                    byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg);

                    Socket workerSocket = null;

                    for (int i = 0; i < workerSocketList.Count; i++)

                    {

                        workerSocket = (Socket)workerSocketList[i];

                        if (workerSocket != null)

                        {

                            if (workerSocket.Connected)

                            {

                                workerSocket.Send(byData);

                            }

                        }

                    }

                }

                catch (SocketException se)

                {

                    MessageBox.Show(se.Message, "提示!");

                }

            }

            else

            {

                MessageBox.Show("没有在线客户,不能发送信息", "提示");

            }

        }

        private void button4_Click(object sender, EventArgs e)

        {

            CloseSockets();

            Close();

        }

        private void button3_Click(object sender, EventArgs e)

        {

            txtRecvMsg.Clear();

        }

        //关闭socket

        void CloseSockets()

        {

            if (mainSocket != null)

            {

                mainSocket.Close();

            }

            Socket workerSocket = null;

            for (int i = 0; i < workerSocketList.Count; i++)

            {

                workerSocket = (Socket)workerSocketList[i];

                if (workerSocket != null)

                {

                    workerSocket.Close();

                    workerSocket = null;

                }

            }

        }

        //更新客户列表

        private void UpdateClientListControl()

        {

            if (InvokeRequired)

            {

                clientList.BeginInvoke(new UpdateClientListCallback(UpdateClientList), null);

            }

            else

            {

                UpdateClientList();

            }

        }

        void UpdateClientList()

        {

            clientList.Items.Clear();

            for (int i = 0; i < workerSocketList.Count; i++)

            {

                string clientkey = Convert.ToString(i + 1);

                Socket workerSocket = (Socket)workerSocketList[i];

                if (workerSocket != null)

                {

                    if (workerSocket.Connected)

                    {

                        clientList.Items.Add(clientkey);

                    }

                }

            }

        }

        //添加信息到txtRecvMsg中

        private void OnUpdateRichEdit(string msg)

        {

            txtRecvMsg.Text = txtRecvMsg.Text + msg;

        }

        private void AppendToRichEditControl(string msg)

        {

            if (InvokeRequired)

            {

                object[] pList ={ msg };

                txtRecvMsg.BeginInvoke(new UpdateRichEditCallback(OnUpdateRichEdit), pList);

            }

            else

            {

                OnUpdateRichEdit(msg);

            }

        }

        private void UpdateControls(bool onServer)

        {

            button1.Enabled = !onServer;

            button2.Enabled = onServer;

            if (onServer)

            {

                status.Text = "服务器启动";

            }

            else

            {

                status.Text = "服务器断开";

            }

        }

        //回调函数

        public void OnClientConnect(IAsyncResult asyn)

        {

            try

            {

                Socket workerSocket = mainSocket.EndAccept(asyn);//调用EndAccept完成BeginAccept异步调用,返回一个新的Socket的处理与客户的通信

                Interlocked.Increment(ref clientNum);//增加客户数目

                workerSocketList.Add(workerSocket);//将workersocket socket加入到ArrayList中              

                

                string msg1 = "客户" + clientNum + "连接上服务器\n";

                AppendToRichEditControl(msg1);//客户登陆信息

                //*********************

                string msg = clientNum.ToString();

                SendWelcomeToClient(msg, clientNum);//发送客户编号信息给该客户

                UpdateClientListControl();

                WaitForData(workerSocket, clientNum);//连接上的客户接收数据

                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);//主Socket返回,继续接收其他的连接请求

            }

            catch (ObjectDisposedException)

            {

                System.Diagnostics.Debugger.Log(0, "1", "\n OnclientConnection:Socket 已经关闭!\n");

            }

            catch (SocketException se)

            {

                MessageBox.Show(se.Message, "提示");

            }

        }

        private void SendWelcomeToClient(string msg, int clientNumber)

        {

            Byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg);

            Socket workerSocket = (Socket)workerSocketList[clientNumber - 1];

            //将数据发给客户           

            workerSocket.Send(byData);

           // MessageBox.Show("返回客户参数:" + clientNumber+"  "+msg);

            /*

            Socket workerSocket = (Socket)workerSocketList[clientNumber - 1];

            NetworkStream networkstream = new NetworkStream(workerSocket);

            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkstream);

            streamWriter.WriteLine(msg);

            streamWriter.Flush();

             */

        }

        private void SendToClient(string msg, int clientNumber)

        {

            Byte[] byData = System.Text.Encoding.UTF8.GetBytes(msg);                    

            Socket workerSocket = (Socket)workerSocketList[clientNumber - 1];

            NetworkStream networkstream = new NetworkStream(workerSocket);

            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkstream);

            streamWriter.WriteLine(msg);

            streamWriter.Flush();

           

        }

        public class SocketPacket

        {

            public System.Net.Sockets.Socket currentSocket;

            public int clientNumber;

            public byte[] dataBuffer = new byte[1024];//发给服务器的数据

            public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)

            {

                currentSocket = socket;

                this.clientNumber = clientNumber;

            }

        }

        public void WaitForData(System.Net.Sockets.Socket socket, int clientNumber)

        {

            try

            {

                if (pfnWorkerCallback == null)

                {

                    pfnWorkerCallback = new AsyncCallback(OnDataReceived);

                }

                SocketPacket socketpacket = new SocketPacket(socket, clientNumber);

                socket.BeginReceive(socketpacket.dataBuffer, 0, socketpacket.dataBuffer.Length, SocketFlags.None, pfnWorkerCallback, socketpacket);

            }

            catch (SocketException se)

            {

                MessageBox.Show(se.Message, "提示");

            }

        }

        public void OnDataReceived(IAsyncResult asyn)

        {

            SocketPacket socketData = (SocketPacket)asyn.AsyncState;

            try

            {

                int iRx = socketData.currentSocket.EndReceive(asyn);

                char[] chars = new char[iRx + 1];

                System.Text.Decoder decoder = System.Text.Encoding.UTF8.GetDecoder();

                int charLen = decoder.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);

                System.String receivemsg = new System.String(chars);

                String substr;

                substr = "";

                if (receivemsg.Length > 4)

                {

                    substr = receivemsg.Substring(0, 4);

                }

                if (substr == "####")//聊天信息

                {

                    MessageBox.Show("sfdsdfdf");

                    String tmp1 = "";

                    tmp1 = receivemsg.Substring(4);

                    string[] s = tmp1.Split(new Char[] { ',' });

                    string clientmsg = "客户" + socketData.clientNumber + " " + s[0] + "说:" + s[1];

                    AppendToRichEditControl(clientmsg);

                }

                if (substr == "%%%%")//退出信息

                {

                    String tmp1 = "";

                    tmp1 = receivemsg.Substring(4);

                    SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=123;database=Login_user");

                    conn.Open();

                    string ke_name = tmp1.ToString().Substring(0,tmp1.ToString().Length-3)  ;//tmp1.ToString()含回车换行\r\n\0符需去掉

                    string updata11 = "update userinfo set userinserver=0,userhouseid=0 where username='" + ke_name + "'";

                    

                    SqlCommand comm11 = new SqlCommand(updata11, conn);

                    comm11.ExecuteNonQuery();

                    conn.Close();

                    string outmsg = "客户" + socketData.clientNumber + "已经断开连接!\n";

                    AppendToRichEditControl(outmsg);

                    workerSocketList[socketData.clientNumber - 1] = null;

                    UpdateClientListControl();

                    // disconnect();

                }

                if (substr == ")()(")//房间信息

                {

                    String tmp1 = "";

                    tmp1 = receivemsg.Substring(4);

                    string[] s = tmp1.Split(new Char[] { ',' });

                    all_table = all_table + "," + s[0] + "," + s[1] + "," + s[2] + "," + Convert.ToInt16(s[3]).ToString();

                     //********************向所有用户的客户端大厅发送座位信息

                    for (int i = 1; i <= clientNum; i++)

                    {

                        SendToClient(")()(" + all_table, i);

                    }                     

                                     

                    SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=123;database=Login_user");

                    conn.Open();

                    string house_id = Convert.ToInt16(s[1]).ToString();//用户选择的房间号

                    string updatehouseid = "update userinfo set userhouseid=" + house_id + " where username='" + s[0].ToString() + "'";

                    SqlCommand comm11 = new SqlCommand(updatehouseid, conn);

                    comm11.ExecuteNonQuery();

                    //*******************判断一个房间同桌是否已经两人

                    string selectstr = "select * from userinfo where userhouseid=" + house_id;

                    SqlCommand da = new SqlCommand(selectstr, conn);                    

                    SqlDataReader myread = da.ExecuteReader();

                    int n = 0;

                    String [ ,]a=new String[2,2] ;

                    int online=0;

                    while (myread.Read())

                    {

                        online = Convert.ToInt32(myread.GetValue(5).ToString());//在线

                        if (online == 1)

                        {

                            a[n,0] = myread.GetValue(4).ToString();//IP

                            a[n,1] = myread.GetValue(2).ToString();//客户号

                            n++;

                        }

                    }

                    if (n == 2)

                    {

                        SendToClient("!!!!" + a[0,0], Convert.ToInt16(a[1,1]));//向一个房间的用户发对方IP

                        SendToClient("!!!!" + a[1, 0], Convert.ToInt16(a[0, 1]));//向一个房间的用户发对方IP

                    }

                    //********************

                    conn.Close();

                }

                if (substr == "@@@@")//注册信息

                {

                    String tmp1 = "";

                    tmp1 = receivemsg.Substring(4);

                    string[] s = tmp1.Split(new Char[] { ',' });

                    String strsql;

                    strsql = "insert into userinfo (username,userpwd,useremail,userpicture) values ('" + s[0].ToString() + "','" + s[1].ToString() + "','" + s[2].ToString() + "','" + s[3].ToString() + "')";

                    string us = null;

                    us = s[0];

                    string selectstr = "select * from userinfo where username='" + us.ToString() + "' ";

                    SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=123;database=Login_user");

                    conn.Open();

                    SqlCommand da = new SqlCommand(selectstr, conn);

                    SqlDataReader myread = da.ExecuteReader();

                    if (myread.Read())

                    {

                        MessageBox.Show(s[0] + " 帐号已经被注册");

                    }

                    else

                    {

                        try

                        {

                            myread.Close();

                            SqlCommand updatauser = new SqlCommand(strsql, conn);

                            updatauser.ExecuteNonQuery();

                            // MessageBox.Show("成功" + "4@" + us.ToString()+ "。");

                            string clientmsg3 = "@@@@" + us.ToString();

                            SendToClient(clientmsg3, clientNum);

                        }

                        catch

                        {

                            // MessageBox.Show("帐号创建失败");

                            string clientmsg0 = "@@";

                           SendToClient(clientmsg0, clientNum);

                        }

                    }

                    conn.Close();

                }

                if (substr == "****")//验证信息

                //****用户名,密码,本机IP,客户编号

                {

                    String tmp1 = "";

                    tmp1 = receivemsg.Substring(4);

                    string[] s = tmp1.Split(new Char[] { ',' });

                    String strsql;

                    strsql = "select * from userinfo where username='" + s[0].ToString() + "' and userpwd= '" + s[1].ToString() + "' ";

                    SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=123;database=Login_user");

                    conn.Open();

                    SqlCommand da = new SqlCommand(strsql, conn);

                    SqlDataReader myread = da.ExecuteReader();

                    if(myread.Read())

                    {

                        // MessageBox.Show(s[0] + " 帐号通过");                            

                        username = myread.GetString(0);

                        userpicture = Convert.ToInt32(myread.GetValue(3).ToString());

                        myread.Close();

                        string updata11 = "update userinfo set userinip= '" + s[2].ToString() + "', id=" + s[3].ToString() + ",  userinserver='1' where username='" + s[0].ToString() + "'";

                        SqlCommand comm11 = new SqlCommand(updata11, conn);

                        comm11.ExecuteNonQuery();

                        clientmsg = "****" + username + "," + userpicture;                                          

                    }

                    else

                    {

                        clientmsg = "**";              

                    }

                    SendToClient(clientmsg, clientNum);

                    //*********向该用户的客户端大厅发送座位信息

                    SendToClient(")()(" + all_table, clientNum);

                    //******

                    clientmsg = "";

                    conn.Close();

                }

                

                //System.String szData = new System.String(chars);

                //string msg = "客户" + socketData.clientNumber + "发的信息" + szData;

                //AppendToRichEditControl(msg);

                WaitForData(socketData.currentSocket, socketData.clientNumber);

            }

            catch (ObjectDisposedException)

            {

                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived:Socket 已经关闭\n");

            }

            catch (SocketException se)

            {

                if (se.ErrorCode == 10054)

                {

                    string msg = "客户" + socketData.clientNumber + "已经断开连接!\n";

                    AppendToRichEditControl(msg);

                    workerSocketList[socketData.clientNumber - 1] = null;

                    UpdateClientListControl();

                }

                else

                {

                    MessageBox.Show(se.Message, "提示");

                }

            }

        }

    }

 }

      1.  客户端
  1. 会员登陆

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

using System.Net.Sockets;

namespace Fiveclient

{

    public partial class FiveStart : Form

    {

        static public bool isgoon=false;//没进行验证

        static public string passmsg;//验证内容

        public FiveStart()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {            

            passmsg = "";

            passmsg = "****" + textBox1.Text + "," + textBox2.Text;

            isgoon = true;           

            this.Close();            

        }

        private void button3_Click(object sender, EventArgs e)

        {

            

        }

        private void button2_Click(object sender, EventArgs e)

        {

            this.Dispose();

            isgoon = false;

        }

        private void FiveStart_Load(object sender, EventArgs e)

        {

            isgoon = false;

        }

    }

}

  1. 设置连接服务器

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace Fiveclient

{

    public partial class FiveSetconnect : Form

    {

        

        public FiveSetconnect()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

           Fivehouse.portNum = System.Convert.ToInt32(textBox2.Text, 10);

           Fivehouse.serverip = textBox1.Text;

           try

           {

               Fivehouse.myclient = new System.Net.Sockets.TcpClient(Fivehouse.serverip, Fivehouse.portNum);

           }

           catch

           {

               MessageBox.Show("服务器拒绝连接请求","信息");

               return;

           }

           Fivehouse.networkClient = Fivehouse.myclient.GetStream();//获取网络流

           byte[] read = new byte[2];

           int bytes = Fivehouse.networkClient.Read(read, 0, read.Length);//读取的字节数

           if (bytes >0)

           {

               

               Fivehouse.isConnecting = true;

               Fivehouse.startthreads();

               Fivehouse.in_id = Convert.ToInt16( System.Text.Encoding.Unicode.GetString(read));

               MessageBox.Show("建立连接成功", System.Text.Encoding.Unicode.GetString(read));

               this.Close();

           }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            this.Dispose();

        }

    }

}

  1. 用户注册

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace Fiveclient

{

    public partial class FiveLogin : Form

    {

        static public string regmsg;//注册内容

        public FiveLogin()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            if (username.Text == "")

            {

                MessageBox.Show("用户不能为空");

                username.Text = "";               

                return;

            }

            if (userpwd1.Text == "" || userpwd2.Text == "")

            {

                MessageBox.Show("密码不能为空");

                userpwd1.Text = "";

                userpwd1.Text = "";

                return;

            }

            if (userpwd1.Text != userpwd2.Text)

            {

                MessageBox.Show("前后密码不对");

                return;

            }

            if (useremail.Text == "")

            {

                MessageBox.Show("Email不能为空");

                useremail.Text = "";

                return;

            }

            if (comboBox1.Text == "")

            {

                MessageBox.Show("请选择头像");

                comboBox1.Text = "";

                return;

            }

            regmsg="";

            regmsg = "@@@@" + username.Text + "," + userpwd1.Text + "," + useremail.Text + "," + comboBox1.Text;

            this.Close();

        }

        private void button2_Click(object sender, EventArgs e)

        {

            this.Dispose();

        }

        private void pictureBox1_Click(object sender, EventArgs e)

        {

        }

        private void label5_Click(object sender, EventArgs e)

        {

        }

        private void FiveLogin_Load(object sender, EventArgs e)

        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

        {

            string filename = @"..\..\newface\" + (comboBox1.SelectedIndex + 1) + ".bmp";

            pictureBox1.Image = Image.FromFile(filename);

        }

    }

}

  1. 游戏大厅

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Configuration;

using System.Net.Sockets;

using System.IO;

using System.Net;

using System.Threading;

namespace Fiveclient

{

    public partial class Fivehouse : Form

    {

        

        private FiveSetconnect setcon;

        static public bool isreguser=false; //判断是否注册用户  

        static public bool isConnecting = false;

        static public int portNum;

        static public string serverip;

        static public string message="";

        public string speakmessage = "";

        static public string inreguser="用户名";//登陆用户名

        static public string inregpicture ="1";//登陆用户照片信息

        static public bool inregposition = false;//登陆用户是否坐上桌子

        static public int in_id ;//登陆用户编号

        static public string other_ip;//对方IP

        static public int table;//用户座位号

        static string all_table;//服务器转发的登陆用户座位信息

        static public string myserveraddress;  

        static public int[]islable ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};  //lable设置        

         

        //网络数据

        private const string infDisconnect = "######DISCONNECT######";//断开标志

        static public NetworkStream networkClient;

        static public Thread recvThread;

        static public TcpClient myclient;

        static public StreamWriter streamWriter;

        static public StreamReader streamReader;        

        public Fivehouse()

        {

            InitializeComponent();

        }

       

        static public void startthreads()

        {

            if (recvThread == null)

            {

                recvThread = new Thread(new ThreadStart(ReceiveMsg));

                recvThread.Start();

            }

        }

        static public void ReceiveMsg()

        {

            while (isConnecting)

            {                  

             ReceiveMsg(myclient, networkClient);

            }

           // MessageBox.Show("与服务器断开了连接");

        }

        public void getmessage(string message)

        {

          listBox1.Items.Add(message);

        }

        static public void ReceiveMsg(TcpClient tcpc, NetworkStream ns)

        {            

            try

            {

                String strout;//接收数据               

                String substr = "";

                String tmp1 = "";

                ns = tcpc.GetStream();

                streamReader = new StreamReader(ns);

                strout = streamReader.ReadLine();

                if (strout.Length >= 4)

                {

                    substr = strout.Substring(0, 4);

                    tmp1 = strout.Substring(4);

                }

                if (string.Compare(strout, infDisconnect) == 0)

                {

                    string strdcnt = "连接被中断.\n";

                    MessageBox.Show(strdcnt);

                    ns.Close();

                    tcpc.Close();

                    isConnecting = false;

                }

                if (substr == "####")//获取聊天信息

                {

                    // MessageBox.Show("受到服务器信息");

                    string[] s = tmp1.Split(new Char[] { ',' });                   

                    message = "服务器说:" + s[0].ToString() +" 。";                   

                }

                if (substr == "!!!!")//获取同桌对方IP

                {

                    //MessageBox.Show("获取对方IP", tmp1);

                    other_ip = tmp1;

                }

                if (substr == ")()(")//获取服务器发送的房间座位信息

                {

                    all_table = tmp1;

                    string message2="获取服务器发送的房间座位信息"+ tmp1;

                }

                if (substr == "****")

                {

                    //MessageBox.Show(strout);

                    string[] s = tmp1.Split(new Char[] { ',' });

                    message = "登陆成功...欢迎" + s[0].ToString() + "登陆本系统";                    

                    inreguser = s[0].ToString();

                    inregpicture = s[1].ToString();                    

                    isreguser = true;

                }

                if (strout == "**")

                {

                    

                    message="验证失败!";

                   

                }

                if (substr == "@@@@")

                {

                    

                    message="恭喜您,帐号注册成功" ;

                }

                if (strout == "@@")

                {

                  message="抱歉,注册失败...";

                }

                if (strout == "%$%$")//获取在线信息

                {

                  

                }

                //else

                //{

                //    MessageBox.Show(strout);

                //}

            }

            catch 

            {

                MessageBox.Show("安全退出","提示");

            }

        }

        public void disconnect(TcpClient tcpc, NetworkStream ns)

        {

            byte[] write = new byte[64];

            write = Encoding.Unicode.GetBytes(infDisconnect.ToCharArray());

            ns.Write(write, 0, write.Length);

            ns.Close();

            tcpc.Close();

            disconnect();

        }

        public void disconnect()

        {               

            if (isConnecting)

            {

                recvThread.Abort();

            }

            isConnecting = false;//断开标志      

           

        }

        private void Fivehouse_Load(object sender, EventArgs e)

        {

            if (message != "")

            {

                getmessage(message);

                message = "";

            }

            if (isConnecting) //判断是否连接

            {

                if (isreguser)//判断是否登陆

                {

                    speakout.Enabled = true;

                    show_inuser.Text = Convert.ToString(inreguser);

                    if (all_table != null&&all_table!="")

                    {

                        string[] s = all_table.Split(new Char[] { ',' });

                        string new_picture, new_table;

                        for (int i = 1; i < s.Length; i = i + 4)

                        {

                            new_picture = s[i + 3].ToString();//头像

                            new_table = s[i + 2].ToString();//座位信息

                            if (new_table == "1")

                            { islable[1] = 1; label1.Image = Image.FromFile(@"..\..\newface\" + new_picture + ".bmp"); }

                            if (new_table == "2")

                            { islable[2] = 1;    label2.Image = Image.FromFile(@"..\..\newface\" + new_picture + ".bmp");}

                            if (new_table == "3")

                            { islable[3] = 1;    label3.Image = Image.FromFile(@"..\..\newface\" + new_picture + ".bmp");}

                            if (new_table == "4")

                            { islable[4] = 1; label4.Image = Image.FromFile(@"..\..\newface\" + new_picture + ".bmp"); }

                        }

                    }

                    this.Text = other_ip;

                }

                else

                {

                    this.Text = "游戏大厅" + "当前时间" + DateTime.Now.ToString() + " " + DateTime.Now.DayOfWeek.ToString();

                    show_ip.Text = Convert.ToString(NetWork.getmyIP());                    

                    button10.Enabled = true;

                    button11.Enabled = true;

                    stop_return.Enabled = true;

                    con_server.Enabled = false;

                }

            }           

            else

            {

                button10.Enabled = false;

                button11.Enabled = false;

                speakout.Enabled = false;

                stop_return.Enabled = false;

            }

            

        }

        private void button11_Click(object sender, EventArgs e)

        {

             

            FiveLogin reg = new FiveLogin();

            reg.ShowDialog();

              listBox1.Items.Add("连接注册服务器...");              

              SendMsg(networkClient, FiveLogin.regmsg);//发送注册信息

              FiveLogin.regmsg = "";

        }

        static public void SendMsg(NetworkStream ns, string tmp)

        {           

            streamWriter = new StreamWriter(ns);            

            streamWriter.WriteLine(tmp);

            streamWriter.Flush();            

        }

        private void button10_Click(object sender, EventArgs e)

        {

           

            FiveStart go = new FiveStart();

            go.ShowDialog();           

            if (FiveStart.isgoon)

            {

                if (isConnecting)

                {

                    string msg11 = FiveStart.passmsg + ',' + Convert.ToString(NetWork.getmyIP())+','+in_id.ToString() ;

                    listBox1.Items.Add("用户验证中...");

                    SendMsg(networkClient, msg11);//发送验证请求                

                    FiveStart.passmsg = "";

                }

            }

           

        }

        private void con_server_Click(object sender, EventArgs e)

        {

            listBox1.Items.Add("准备连接服务器");

            setcon = new FiveSetconnect();

            setcon.ShowDialog();

            if (isConnecting)

            {

                listBox1.Items.Add("连接成功!" + DateTime.Now.ToString());

              //  Fivehouse.startthreads();

            }

            else

            {

                listBox1.Items.Add("连接失败!");

            }

           

        }

        public void stop_return_Click(object sender, EventArgs e)

        {

            isreguser = false;            

            for (int i = 0; i <18; i++)

            {

                islable[i] = 0;

            }

           label12=new Label();

           label13.Invalidate();

           label14.Invalidate();

           this.pictureBox1.Invalidate();

           this.listBox1.Items.Add("用户"+inreguser+"已经退出!");

           inreguser = "";

           show_inuser.Text = "";

           this.Invalidate();

           

        }

        private void button1_Click(object sender, EventArgs e)

        {

            string tmp = ")()(" + Convert.ToString(inreguser) + "," + "1," + table.ToString() +","+ inregpicture;

            SendMsg(networkClient, tmp);

            FiveGame five = new FiveGame();

            five.ShowDialog();

   

        }

        private void button2_Click(object sender, EventArgs e)

        {

            string tmp = ")()(" + Convert.ToString(inreguser) + "," + "2," + table.ToString() + "," + inregpicture;

            SendMsg(networkClient, tmp);

            FiveGame five = new FiveGame();

            five.ShowDialog();

        }

        private void button3_Click(object sender, EventArgs e)

        {

            string tmp = ")()(" + Convert.ToString(inreguser) + "," + "3," + table.ToString() + "," + inregpicture;

            SendMsg(networkClient, tmp);

            FiveGame five = new FiveGame();

            five.ShowDialog();

        }

        //button4---button9略

        private void label1_Click(object sender, EventArgs e)

        {

            if (islable[1] == 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label1.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[1] = 1;

                    table = 1;

                    button1.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

        }

        private void label2_Click(object sender, EventArgs e)

        {

            if (islable[2] == 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label2.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[2] = 1;

                    table = 2;

                    this.button1.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

            

        }

        private void label3_Click(object sender, EventArgs e)

        {

            if (islable[3]== 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label3.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[3] = 1;

                    table = 3;

                    this.button2.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

        }

        private void label4_Click(object sender, EventArgs e)

        {

            if (islable[4] == 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label5.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[4] = 1;

                    table = 4;

                    this.button2.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

        }

        private void label5_Click(object sender, EventArgs e)

        {

            if (islable[5] == 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label4.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[5] = 1;

                    table = 5;

                    this.button3.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

        }

        private void label6_Click(object sender, EventArgs e)

        {

            if (islable[6] == 0)

            {

                if (inregposition)

                {

                    MessageBox.Show("你已经坐进了其他位子");

                }

                else

                {

                    label8.Image = Image.FromFile(@"..\..\newface\" + inregpicture + ".bmp");

                    inregposition = true;

                    islable[6] = 1;

                    table = 6;

                    this.button3.Enabled = true;

                }

            }

            else

            {

                MessageBox.Show("已经有人坐在这里了!请换位");

            }

        }

        //label7---label18略

        private void speakout_Click(object sender, EventArgs e)

        {

            if (textBox1.Text != "")

            {

                speakmessage = "####" + inreguser +","+ textBox1.Text;

                listBox1.Items.Add(inreguser + "说:" + textBox1.Text);

                SendMsg(networkClient, speakmessage);

                speakmessage="";

            }

        }

        private void Fivehouse_FormClosed(object sender, FormClosedEventArgs e)

        {

            if (isConnecting)

            {    

               

                //listBox1.Items.Add("退出服务器...");

                string msgoutserver = "%%%%" + Convert.ToString(inreguser);

                SendMsg(networkClient, msgoutserver);

                myclient.Close();           

                networkClient.Close();

            }

            isConnecting = false;

        }

    }

}

  1. 五子棋对战

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace Fiveclient

{

    public partial class FiveGame : Form

    {

        /// <summary>

        /// 是否轮到我

        /// </summary>

        private bool Myturn;

        Bitmap oldbmp, usingbmp; IsWin iswin; gobang five;

        private bool onebodyin = false;

        static public bool isplaying = false;

        static public string speakmessage = "";

        static public string returnid = "";

        static public string reip = "";

        static public string relevel = "";

        NetWork network = new NetWork();

        string infor, oldinfor;        

        public FiveGame()

        {

            InitializeComponent();

        }

        private void FiveGame_Load(object sender, EventArgs e)

        {

            //if(speakmessage != "")

            //{

            //    getmessage(speakmessage);

            //    speakmessage = "";

            //}

            listBox1.Items.Add(Fivehouse.inreguser+"进入了游戏!");

            usingbmp = oldbmp = new Bitmap(this.pictureBox1.Image);

            listView1.Items.Add(Fivehouse.inreguser, 0);

            listView1.Items[0].SubItems.Add("1");

            listView1.Items[0].SubItems.Add(Convert.ToString(NetWork.getmyIP()));

            

        }

        private void UpdateControls(bool onServer)

        {

                       

            buildGamebutton.Enabled = !onServer;

            Joinbutton.Enabled = !onServer;

            Rebuildbutton.Enabled = onServer;

            overgame.Enabled = onServer;

            StopNetbutton.Enabled = onServer;

            if (onServer)

            {

                status.Text = "连接中...";

            }

            else

            {

                status.Text = "断开连接";

            }

        }

        private void sendmsg_Click(object sender, EventArgs e)

        {

            listBox1.Items.Add(Fivehouse.inreguser+"说:"+ userspeak.Text);

            string speakout=userspeak.Text.ToString();

            string userid=Fivehouse.inreguser.ToString();

            network.Send(speakout, userid);

           // getmessage(speakmessage);

            

        }

        public void getmessage(string msg,string id)

        {

           

            listBox1.Items.Add(id + "说:"+msg);            

          

        }

       

        private void Rebuildbutton_Click(object sender, EventArgs e)

        {

            

            usingbmp = oldbmp = new Bitmap(this.pictureBox1.Image);

            pictureBox1.Enabled = true;

            this.pictureBox1.Invalidate();            

            this.pictureBox1.Refresh();            

            //this.panel1.Invalidate();

            

        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)

        {

                if (onebodyin)

                try

                {

                    five.pointx = e.X - 21;

                    five.pointy = e.Y - 24;

                    five.cheesemove(this.pictureBox1, this.Myturn);

                }

                catch

                {

                }

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)

        {

            if(this.Myturn)

{

if(five.CanDown())

{

try

{

string sendinfor=five.cellx.ToString()+"."+five.celly.ToString()+"."+(five.myturn);

network.Send(sendinfor);

string t1,t2;

this.pictureBox1.Image=five.DownthePoint(out t1,out t2);

this.label1.Text=t1;

this.label2.Text=t2;

Myturn=false;

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

                

}

try

{

if(iswin.Win(five.cellx,five.celly)==5)

{

MessageBox.Show("游戏结束,白方胜利");

//this.pictureBox1.Enabled=false;

                    this.pictureBox1.Invalidate();

this.st.Text="游戏结束,白方胜利";

//this.timer1.Stop();

//this.network.StopListen();

}

if(iswin.Win(five.cellx,five.celly)==-5)

{

MessageBox.Show("游戏结束,黑方胜利");

//this.pictureBox1.Enabled=false;

                    this.pictureBox1.Invalidate();

//this.timer1.Stop();

//this.network.StopListen();

}

}

catch

{

this.st.Text="游戏还没有开始,无法下棋";

}

}

        private void NewGamebutton_Click(object sender, EventArgs e)

        {

            IPtextBox.Text = Convert.ToString(NetWork.getmyIP());

            listBox1.Items.Add(Fivehouse.inreguser + "建立游戏,等待玩家进入");

            UpdateControls(true);

            five=new gobang();

five.AddBmp(usingbmp,new Bitmap(this.pictureBox4.Image),new Bitmap(this.pictureBox5.Image));

iswin=new IsWin(five.down);

this.pictureBox1.Enabled=true;

this.pictureBox1.Image=oldbmp;

this.pictureBox1.Refresh();

network.Listen();

this.timer1.Start();

this.Myturn=true;

this.onebodyin=false;

            

        }

        private void startchess()

        {

            IPtextBox.Text = Convert.ToString(NetWork.getmyIP());

            //listBox1.Items.Add(Fivehouse.inreguser + "建立游戏,等待玩家进入");

            UpdateControls(true);

            five = new gobang();

            five.AddBmp(usingbmp, new Bitmap(this.pictureBox4.Image), new Bitmap(this.pictureBox5.Image));

            iswin = new IsWin(five.down);

            this.pictureBox1.Enabled = true;

            this.pictureBox1.Image = oldbmp;

            this.pictureBox1.Refresh();

            network.Listen();

            this.timer1.Start();

            this.Myturn = true;

            this.onebodyin = false;

        }

        private void Joinbutton_Click(object sender, EventArgs e)

        {

            if(this.IPtextBox.Text=="")

{

MessageBox.Show("对方IP还没有配置,请点击配置");

return;

}

network.IP=IPtextBox.Text;

string sta="";

network.Send(ref sta,NetWork.getmyIP()+"加入游戏!");

if(sta=="")

{

startchess();

listBox1.Items.Add("加入对方主机成功!游戏建立");

                string userid = Fivehouse.inreguser.ToString();

                string userip=Convert.ToString(NetWork.getmyIP());

                network.Send(userid,userip,"1");

this.onebodyin=true;

this.Joinbutton.Enabled=false;

this.buildGamebutton.Enabled=false;

                isplaying = true;

}

else

{

this.st.Text=sta;

}

this.Myturn=false;

        }

        private void timer1_Tick(object sender, EventArgs e)

        {

            this.st.Text = this.network.sta;

            string nowinfor;

            infor = this.network.infor;

            if (oldinfor != infor)//有新消息

            {

             //   this.netinforlable.Text = infor;

                try

                {

                    int dot = infor.IndexOf(".");

                    five.cellx = Convert.ToInt32(infor.Substring(0, dot));

                    nowinfor = infor.Substring(dot + 1);

                    dot = nowinfor.IndexOf(".");

                    five.celly = Convert.ToInt32(nowinfor.Substring(0, dot));

                    nowinfor = nowinfor.Substring(dot + 1);

                    five.myturn = Convert.ToBoolean(nowinfor);

                    string t1, t2;

                    this.pictureBox1.Image = five.DownthePoint(out t1, out t2); //对方下棋

                    this.label1.Text = t1;

                    this.label2.Text = t2;

                    if (iswin.Win(five.cellx, five.celly) == 5)

                    {

                        this.st.Text = "游戏结束,白方胜利";

                        this.timer1.Stop();

                        //this.network.StopListen();

                        this.pictureBox1.Enabled = false;

                    }

                    if (iswin.Win(five.cellx, five.celly) == -5)

                    {

                        this.st.Text = "游戏结束,黑方胜利";

                        this.timer1.Stop();

                       // this.network.StopListen();

                        this.pictureBox1.Enabled = false;

                    }

                    this.Myturn = true;

                }

                catch

                {

                    this.st.Text = infor;

                    try

                    {

                        if (infor.IndexOf("加") > 0) onebodyin = true;

                        string joinedip = infor.Substring(0, infor.IndexOf("加"));

                        IPtextBox.Text = network.IP = joinedip;

                    }

                    catch

                    {

                    }

                }

            }

            oldinfor = infor;

        }

        private void IPtextBox_TextChanged(object sender, EventArgs e)

        {

        }

        private void userspeak_TextChanged(object sender, EventArgs e)

        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)

        {

        }

        private void StopNetbutton_Click(object sender, EventArgs e)

        {

            network.StopListen();

            UpdateControls(false);

        }

        private void overgame_Click(object sender, EventArgs e)

        {

        }

        private void timer2_Tick(object sender, EventArgs e)

        {

            

            IPtextBox.Text = Fivehouse.other_ip;  //对方IP *********        

            if (speakmessage != "" && returnid!="")

            {

                getmessage(speakmessage,returnid);

                speakmessage = "";

                returnid = "";

            }

            if (returnid != "" && reip != "" & relevel != "")

            {

                setuser(returnid, reip, relevel);

                reip = "";

                returnid = "";

                relevel ="";

            }

        }

        private void setuser(string uid,string uip,string ulevel)

        {

            //string ll=Convert.

            listView1.Items.Add(uid, 0);

            listView1.Items[0].SubItems.Add(ulevel);

            listView1.Items[0].SubItems.Add(uip);

        }

        private void FiveGame_FormClosed(object sender, FormClosedEventArgs e)

        {

            timer2.Enabled = false;

        }       

        }        

    }

using System;

using System.Collections.Generic;

using System.Text;

using System.Drawing;

namespace Fiveclient

{

    public class gobang

    {

        public gobang()

        {

            //

            // TODO: 在此处添加构造函数逻辑

            //

        }

        ~gobang()

        {

        }

        public int[,] down = new int[25, 25];

        public int cellx, celly, oldcellx, oldcelly;

        public bool myturn = true;

        private int r = 35;

        public int whitenum = 0, blacknum = 0, pointx, pointy;

        public Bitmap bmp, bmpb, bmpw;

        public void AddBmp(Bitmap map, Bitmap white, Bitmap black)

        {

            this.bmp = map;

            this.bmpw = white;

            this.bmpb = black;

        }

        /// <summary>

        /// 返回是否可以在此处下子

        /// </summary>

        /// <returns></returns>

        public bool CanDown()

        {

            if (down[cellx, celly] == 0) return true;

            else return false;

        }

        private Bitmap Down()

        {

            int x = cellx * r + 5;

            int y = celly * r + 8;

            if (myturn)

                for (int w = 0; w < bmpw.Width; w++)

                {

                    for (int h = 0; h < bmpw.Height; h++)

                    {

                        Color color = bmpw.GetPixel(w, h);

                        if (color.R == 0 && color.G == 0 && color.B == 255)

                            continue;

                        bmp.SetPixel(w + x, h + y, color);

                    }

                }

            else

                for (int w = 0; w < bmpw.Width; w++)

                {

                    for (int h = 0; h < bmpw.Height; h++)

                    {

                        Color color = bmpb.GetPixel(w, h);

                        if (color.R == 0 && color.G == 0 && color.B == 255)

                            continue;

                        bmp.SetPixel(w + x, h + y, color);

                    }

                }

            return bmp;

            // this.pictureBox1.Image=bmp;

        }

        /// <summary>

        /// 图片棋子

        /// </summary>

        private void BmpPiece()

        {

            // if(CanDown())

            // {

             this.pictureBox1.Cursor=this.pictureBox3.Cursor;

             this.pictureBox1.Refresh();

            // if(myturn)

            // {

            // this.pictureBox4.Location=new Point(cellx*r-r/2+21,celly*r+24-r/2);

            // this.pictureBox4.Visible=true;

            // this.pictureBox5.Visible=false;

            // }

            // else

            // {

            // this.pictureBox5.Location=new Point(cellx*r-r/2+21,celly*r+24-r/2);

            // this.pictureBox4.Visible=false;

            // this.pictureBox5.Visible=true;

            // }

            // oldcellx=cellx;

            // oldcelly=celly;

            // }

            // else

            // {

            // this.pictureBox1.Cursor=this.pictureBox2.Cursor;

            // }

        }

        /// <summary>

        /// 在棋盘上下一个棋子

        /// </summary>

        public Bitmap DownthePoint(out string txt1, out string txt2)

        {

            if (myturn)

            {

                whitenum++; down[cellx, celly] = 1;

            }

            else

            {

                blacknum++; down[cellx, celly] = -1;

            }

            txt1 = whitenum.ToString();

            txt2 = blacknum.ToString();

            Bitmap newmap = Down();

            myturn = (!myturn);

            return newmap;

        }

        private void DrawPiece(System.Windows.Forms.PictureBox p1)

        {

            p1.Refresh();

            if (CanDown())

            {

                Graphics g = p1.CreateGraphics();

                if (myturn)

                {

                    Brush br = new SolidBrush(Color.White);

                    g.FillEllipse(br, cellx * r - r / 2 + 21, celly * r + 24 - r / 2, r, r);

                    br.Dispose();

                }

                else

                {

                    Brush br = new SolidBrush(Color.Black);

                    g.FillEllipse(br, cellx * r - r / 2 + 21, celly * r + 24 - r / 2, r, r);

                    br.Dispose();

                }

                oldcellx = cellx;

                oldcelly = celly;

                p1.Cursor = System.Windows.Forms.Cursors.Hand;

            }

            else

            {

                p1.Cursor = System.Windows.Forms.Cursors.No;

            }

        }

        /// <summary>

        /// 画出的棋子移动

        /// </summary>

        public void cheesemove(System.Windows.Forms.PictureBox p1, bool myturn)

        {

            if (!myturn) return;

            cellx = pointx / r;

            celly = pointy / r;

            int x = pointx % r;

            int y = pointy % r;

            if (x > r / 2) cellx++;

            if (y > r / 2) celly++;

            if (oldcellx == cellx && oldcelly == celly || cellx > 14 || celly > 14)

            {

                return;

            }

           // DrawPiece(p1);

        }

    }

}

using System;

using System.Collections.Generic;

using System.Text;

namespace Fiveclient

{

    public class IsWin

    {

        int[,] down;

        public IsWin(int[,] p)

        {

            down = p;

        }

        public int Win(int cellx, int celly)

        {

            for (int i = 0; i < 5; i++)

            {

                int xall = Wfive(cellx - i, celly);

                if (Math.Abs(xall) == 5) return xall;

                int yall = Hfive(cellx, celly - i);

                if (Math.Abs(yall) == 5) return yall;

                int xyall = Piefive(cellx + i, celly - i);

                if (Math.Abs(xyall) == 5) return xyall;

                xyall = Lafive(cellx - i, celly - i);

                if (Math.Abs(xyall) == 5) return xyall;

            }

            return 0;

        }

        private int Wfive(int xbegin, int y)

        {

            int all = 0;

            for (int i = 0; i < 5; i++)

            {

                try

                {

                    all = all + down[xbegin + i, y];

                }

                catch

                {

                    return 0;

                }

            }

            return all;

        }

        private int Hfive(int x, int ybegin)

        {

            int all = 0;

            for (int i = 0; i < 5; i++)

            {

                try

                {

                    all = all + down[x, ybegin + i];

                }

                catch

                {

                    return 0;

                }

            }

            return all;

        }

        private int Piefive(int x, int y)

        {

            int all = 0;

            for (int i = 0; i < 5; i++)

            {

                try

                {

                    all = all + down[x - i, y + i];

                }

                catch

                {

                    return 0;

                }

            }

            return all;

        }

        private int Lafive(int x, int y)

        {

            int all = 0;

            for (int i = 0; i < 5; i++)

            {

                try

                {

                    all = all + down[x + i, y + i];

                }

                catch

                {

                    return 0;

                }

            }

            return all;

        }

    }

}

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Threading;

namespace Fiveclient

{

        public class NetWork

        {

           public NetWork()

   {

   }

           public string sta, infor;

           public string speakmsg;

           private string ip;

           public Thread thread;

           System.Net.Sockets.TcpListener tcpl;

           bool listenerRun = true;

           //FiveGame fivegame = new FiveGame();

           public string IP

           {

               get { return ip; }

               set { ip = value; }

           }

           public static string getmyIP()

           {

               String name = Dns.GetHostName();

               IPHostEntry ips = Dns.GetHostByName(name);

               return ips.AddressList[0].ToString();

           }

           public string getHostIP()

           {

               String name = Dns.GetHostName();

               IPHostEntry ips = Dns.GetHostByName(name);

               return ips.AddressList[0].ToString();

           }

           /// <summary>

           /// 开一个线程监听网络

           /// </summary>

           public void Listen()

           {

               thread = new Thread(new ThreadStart(listen));

               thread.Start();

           }

           private void listen()

           {

               string ip = getHostIP();

               try

               {

                   tcpl = new TcpListener(IPAddress.Parse(ip),7100);

                   tcpl.Start();

                   sta = "正在监听...";

                   FiveGame.isplaying = true;

                   while (listenerRun)

                   {

                       Socket s = tcpl.AcceptSocket();

                       Byte[] stream = new Byte[80];

                       int i = s.Receive(stream);

                       String substr = "";

                       String tmp1 = "";

                       string message = System.Text.Encoding.UTF8.GetString(stream);

                       infor = message;

                       if (infor.Length >= 4)

                       {

                           substr = infor.Substring(0, 4);

                           tmp1 = infor.Substring(4);                      

                       }

                       if (substr == "####")

                       {

                           string[] ss = tmp1.Split(new Char[] { ',' });

                           FiveGame.returnid = ss[0].ToString();

                           FiveGame.speakmessage = ss[1].ToString(); ;

                       }

                       if (substr == "%%$$")

                       {

                           string[] ss = tmp1.Split(new Char[] { ',' });

                           FiveGame.returnid = ss[0].ToString();

                           FiveGame.reip = ss[1].ToString();

                           FiveGame.relevel = ss[2].ToString();

                       }

                   }

               }

               catch (System.Security.SecurityException)

               {

                   sta = "防火墙安全错误!";

               }

               catch (Exception ex)

               {

                   sta = "已停止监听!" + ex.Message;

               }

           }

           /// <summary>

           /// 停止监听

           /// </summary>

           public void StopListen()

           {

               listenerRun = false;

               tcpl.Stop();

           }

           public void Send(ref string sta, string infor)

           {

               try

               {

                   string msg = infor;

                   TcpClient tcpc = new TcpClient(ip, 7100);

                   NetworkStream tcpStream = tcpc.GetStream();

                   StreamWriter reqStreamW = new StreamWriter(tcpStream);

                   reqStreamW.Write(msg);

                   reqStreamW.Flush();

                   tcpStream.Close();

                   tcpc.Close();

               }

               catch

               {

                   sta = "目标计算机拒绝连接请求!";

               }

           }

           public void Send(string infor)

           {

               string msg = infor;

               TcpClient tcpc = new TcpClient(ip, 7100);

               NetworkStream tcpStream = tcpc.GetStream();

               StreamWriter reqStreamW = new StreamWriter(tcpStream);

               reqStreamW.Write(msg);

               reqStreamW.Flush();

               tcpStream.Close();

               tcpc.Close();

           }

            public void Send(string msg,string id)

            {

                string spkmessage = msg;

                TcpClient tcpc = new TcpClient(ip, 7100);

                NetworkStream tcpStream = tcpc.GetStream();

                StreamWriter reqStreamW = new StreamWriter(tcpStream);

                reqStreamW.Write("####"+id+","+spkmessage);                

                reqStreamW.Flush();

                tcpStream.Close();

                tcpc.Close();

            }

            public void Send(string id ,string userip ,string level)

            {

                //string spkmessage = msg;

                TcpClient tcpc = new TcpClient(ip, 7100);

                NetworkStream tcpStream = tcpc.GetStream();

                StreamWriter reqStreamW = new StreamWriter(tcpStream);

                reqStreamW.Write("%%$$" + id + "," + Convert.ToString(getmyIP())+","+level);

                reqStreamW.Flush();

                tcpStream.Close();

                tcpc.Close();

            }

        }

        

}

  1.  论文小结

此次论文是我们从大学毕业生走向未来重要的一步。从最初的选题,开题到分析,设计,代码编写直到完成设计。其间,查找资料,老师指导,与同学交流,,每一个过程都是对自己能力的一次检验和充实。

通过这次实践,我们了解了“大厅五子棋”的用途及工作原理,熟悉了“大厅五子棋”的设计步骤,锻炼了工程设计实践能力,培养了自己独立设计能力。此次毕业设计是对我专业知识和专业基础知识一次实际检验和巩固,同时也是走向工作岗位前的一次热身。

毕业设计收获很多,比如学会了查找相关资料相关标准,分析数据,提高了自己的绘图能力,懂得了许多经验公式的获得是前人不懈努力的结果。同时,仍有很多课题需要后辈去努力去完善。  

但是此次也暴露出自己专业基础的很多不足之处。比如缺乏综合应用专业知识的能力,对材料的不了解,等等。这次实践是对自己大学三年所学的一次大检阅,使我明白自己知识还很浅薄,虽然马上要毕业了,但是自己的求学之路还很长,以后更应该在工作中学习,努力使自己 成为一个对社会有所贡献的人,为中国软件业添上自己的微薄之力。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

等天晴i

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

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

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

打赏作者

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

抵扣说明:

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

余额充值