using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace GoBang
{
    public partial class FrMain : Form
    {
        #region 变量

        /// <summary>
        ///记录回合数 
        /// </summary>
        public int huihe = 0;

        //临时变量，（x，y）表示鼠标所指位置（像素表示）
        //（l1max_x, l1max_y）和（l2max_x, l2max_y）是加分算法用到的临时变量
        private int x, y, l1max_x, l1max_y, l2max_x, l2max_y;

        //[i,j]分别表示棋盘的横、纵坐标
        //lines2max表示当前查询的player2lines[x，y]中分数最大值
        //lines1max表示当前查询的player1lines[x，y]中分数最大值
        //[m, n]加分算法中电脑选取下棋的坐标
        private int lines2max, lines1max, m, k, n, i, j;

        //player1sum, player2sum表示下棋双方各走的总步数
        private int player1sum, player2sum;

        /// <summary>
        /// 可能获胜情况总和数，由于采用15*15棋盘，应有572种可能
        /// </summary>
        private int count;

        /// <summary>
        /// shifouxiazi[i,j]=2表示此处无子,shifouxiazi[i,j]=1表示此处为黑子,shifouxiazi[i,j]=0表示此处为白子
        /// </summary>
        private int[,] shifouxiazi = new int[15, 15];

        //player1lines[x，y]，player2lines[x，y]加分算法中[x，y]点分数总和
        private int[,] player2lines = new int[15, 15];
        private int[,] player1lines = new int[15, 15];

        //tableplayer[x,y,count]表示一方所有可能的获胜组合
        // 前两维表示下棋位置(x,y)，后一维表示获胜组合情况
        // 比如count=0时，即第一种获胜情况，对应有tableplayer[0，0，0]，tableplayer[1，0，0]，
        //                  tableplayer[2，0，0]，tableplayer[3，0，0]，tableplayer[4，0，0]
        //所以满足[0，0]，[1，0]，[2，0]，[3，0]，[4，0]时第一种获胜情况成立

        /// <summary>
        /// 白棋获胜表
        /// </summary>
        private bool[, ,] tableplayer1 = new bool[15, 15, 572];
        /// <summary>
        /// 黑棋获胜表
        /// </summary>
        private bool[, ,] tableplayer2 = new bool[15, 15, 572];

        //获胜判断参数，ifwin[0，i]表白棋，ifwin[1，i]表黑棋
        //i表获胜组合情况，即上文count
        //初始ifwin[0，i]=0，ifwin[0，i]=5表示已连成5子，ifwin[0，i]=7表示此种获胜组合情况i已不可能存在
        private int[,] ifwin = new int[2, 572];

        //游戏状态参数 默认为人机对战状态
        public bool
            //nplayers=false Wplayers=false 时表示人机对战
            //nplayers=true Wplayers=false 时表示双人对战
            //nplayers=false Wplayers=true 时表示网络对战
              nplayers = false, wplayers = false,

            //取胜标志
            //win1=true表示黑棋获胜
            //win0=true表示白棋获胜
            //nowin=true表示平局
              win0, win1, nowin,
            //结束标志 over=true表示一局棋结束
            //游戏开始标志 
            over, start;

        //下棋同步量，协调下子顺序，默认先手未定，游戏开始时随机分配先手
        public bool player1 = false, player2 = false;

        //记录网络对战时接受到的信息 （wpx,wpy）表示（X，Y），per=0表白棋，per=1表黑棋
        public int wpx, wpy, per = 2;


        //其他变量
        public FrServer frServer; //服务器窗体对象
        public FrClient frClient; //客户端窗体对象

         //<summary>
         //储存网络对战时发送信息字段
         //</summary>
        public string gin;

        //标记服务器与客户端 
        //hem=true pat=false 表示当前为服务器
        //hem=false pat=true 表示当前为客户端
        public Socket Sock1;
        public Socket Sock2;
        public bool hem, pat;

         //<summary>
         //网络对战时同步信号量 控制网络下棋顺序
         //</summary>
        public bool begin = false;

         //<summary>
         //是否连接完成，完成置contet=true
         //</summary>
        public bool contet = false;

         //<summary>
         //已打开服务器窗口，置contet0=true
         //</summary>
        public bool contet0 = false;

        // <summary>
        //已打开客户端窗口，置contet1=true 
        // </summary>
        public bool contet1 = false;

        //界面显示要素
        private Image map = Image.FromFile("3.jpg");  //棋盘图片 大小600*600像素
        private Image hei = Image.FromFile("black.gif");  //黑子图片 大小40*40像素
        private Image bai = Image.FromFile("white.gif");  //白子图片 大小40*40像素

        private int computertime = 0;//计算机时间

        /// <summary>
        /// 白棋分数
        /// </summary>
        private int score1 = 0;

        /// <summary>
        /// 黑棋分数
        /// </summary>
        private int score2 = 0;

        #endregion

        #region 私有方法

        /// <summary>
        /// 所有获胜组合的初始化
        /// </summary>
        private void WinMethod()
        {
            for (i = 0; i < 15; i++)
                for (j = 0; j < 11; j++)
                {
                    //横连的所有可能5连子情况
                    for (k = 0; k < 5; k++)
                    {
                        tableplayer1[j + k, i, count] = true;
                        tableplayer2[j + k, i, count] = true;
                    }
                    count++;
                }
            for (i = 0; i < 15; i++)
                for (j = 0; j < 11; j++)
                {
                    //竖连的所有可能5连子情况
                    for (k = 0; k < 5; k++)
                    {
                        tableplayer1[i, j + k, count] = true;
                        tableplayer2[i, j + k, count] = true;
                    }
                    count++;
                }
            for (i = 0; i < 11; i++)
                for (j = 0; j < 11; j++)
                {
                    //左上至右下所有斜连5子情况
                    for (k = 0; k < 5; k++)
                    {
                        tableplayer1[j + k, i + k, count] = true;
                        tableplayer2[j + k, i + k, count] = true;
                    }
                    count++;
                }
            for (i = 0; i < 11; i++)
                for (j = 14; j >= 4; j--)
                {
                    //右上至左下所有斜连5子情况
                    for (k = 0; k < 5; k++)
                    {
                        tableplayer1[j - k, i + k, count] = true;
                        tableplayer2[j - k, i + k, count] = true;
                    }
                    count++;
                }
        }

        /// <summary>
        /// 不是网络对战状态
        /// </summary>
        private void NotNetGame()
        {
            if (player1)
            {
                //该白棋走
                if (x < 600 && y < 600)
                {
                    //取下棋点
                    m = (int)Math.Floor((double)x / 40);
                    n = (int)Math.Floor((double)y / 40);

                    if (shifouxiazi[m, n] == 2)
                    {
                        //判断未下子情况下界面相应显示
                        lbPState2.Text = "X" + m + " Y" + n;
                        lbWait.Text = "等待黑棋";

                        this.tbRecord.Text = tbRecord.Text + "白棋:" + "X" + m + "Y" + n + "\r\n";
                        //加入历史信息

                        if (lbPlay1.Text == "待定")
                        {
                            lbPlay1.Text = "电脑";
                            lbPlay2.Text = "玩家";
                        }


                        if (lbFristName.Text == "白棋")
                        {
                            huihe++;
                            lbCountNum.Text = "" + huihe;
                        }
                        else
                            if (lbFristName.Text == "待定")
                            {
                                lbFristName.Text = "白棋";
                                huihe++;
                                lbCountNum.Text = "" + huihe;
                            }
                        //回合数调整，先手显示

                        shifouxiazi[m, n] = 0;
                        //表示该位已存白子
                        player1sum++;
                        //白子总数加1

                        if (((player2sum == 112) && (player1sum == 113)) || ((player2sum == 113) && (player1sum == 112)))
                        {
                            //如果出现平局
                            nowin = true;
                            over = true;
                        }
                        for (i = 0; i < 572; i++)
                        {
                            //对每种获胜情况的ifwin[0,i]进行计算，可能满足的情况ifwin[0,i]++
                            //不能满足的情况ifwin[0,i]置7（表无效）
                            if (tableplayer1[m, n, i] && ifwin[0, i] != 7)
                                ifwin[0, i]++;
                            if (tableplayer2[m, n, i])
                            {
                                tableplayer2[m, n, i] = false;
                                ifwin[1, i] = 7;
                            }
                        }

                        player1 = false;
                        player2 = true;
                        //交换下棋方
                    }
                }
            }
            if (nplayers)
            {
                //双人对战模式下
                if (player2)
                    if (x < 600 && y < 600)
                    {
                        //黑棋走
                        m = (int)Math.Floor((double)x / 40);
                        n = (int)Math.Floor((double)y / 40);
                        //取下棋点
                        if (shifouxiazi[m, n] == 2)
                        {
                            //判断未下子情况下界面相应显示
                            lbPState1.Text = "X" + m + " Y" + n;
                            lbWait.Text = "等待白棋";

                            this.tbRecord.Text = tbRecord.Text + "黑棋:" + "X" + m + "Y" + n + "\r\n";
                            //加入历史记录

                            if (lbFristName.Text == "黑棋")
                            {
                                huihe++;
                                lbCountNum.Text = "" + huihe;
                            }
                            else
                                if (lbFristName.Text == "待定")
                                {
                                    lbFristName.Text = "黑棋";
                                    huihe++;
                                    lbCountNum.Text = "" + huihe;
                                }
                            //回合数调整，先手显示

                            shifouxiazi[m, n] = 1;
                            //表示该位已存黑子
                            player2sum++;
                            //黑子总数加1
                            if (((player2sum == 112) && (player1sum == 113)) || ((player2sum == 113) && (player1sum == 112)))
                            {
                                nowin = true;
                                over = true;
                            }
                            for (i = 0; i < 572; i++)
                            {
                                //对每种获胜情况的ifwin[0,i]进行计算，可能满足的情况ifwin[0,i]++
                                //不能满足的情况ifwin[0,i]置7（表无效）
                                if (tableplayer2[m, n, i] && ifwin[1, i] != 7)
                                    ifwin[1, i]++;
                                if (tableplayer1[m, n, i])
                                {
                                    tableplayer1[m, n, i] = false;
                                    ifwin[0, i] = 7;
                                }
                            }

                            player1 = true;
                            player2 = false;
                            //交换下棋权利
                        }
                    }

            }
        }

        /// <summary>
        /// 网络对战状态
        /// </summary>
        private void NetGame()
        {
            if (begin)
            {
                //判断同步信号量是否满足
                if (player1)
                {
                    //白棋走
                    if (x < 600 && y < 600)
                    {
                        m = (int)Math.Floor((double)x / 40);
                        n = (int)Math.Floor((double)y / 40);

                        if (shifouxiazi[m, n] == 2)
                        {
                            //判断未下子情况下界面相应显示
                            lbPState2.Text = "X" + m + " Y" + n;
                            lbWait.Text = "等待黑棋";

                            begin = false;
                            //改变信号量

                            this.tbRecord.Text = tbRecord.Text + "白棋:" + "X" + m + "Y" + n + "\r\n";
                            //加入历史记录

                            //发送下棋信息，包括：棋子颜色、坐标（X，Y）
                            string gin = "bai;" + m + "," + n + ",";
                            if (hem) frServer.getin(gin);        //调用服务器发送
                            else frClient.getin1(gin);       //调用客户端发送

                            if (lbFristName.Text == "白棋")
                            {
                                huihe++;
                                lbCountNum.Text = "" + huihe;
                            }
                            else
                                if (lbFristName.Text == "待定")
                                {
                                    lbCountNum.Text = "" + huihe;
                                    string gin1 = "xia0";
                                    lbFristName.Text = "白棋";
                                    huihe++;
                                    lbCountNum.Text = "" + huihe;

                                    //发送先手信息
                                    if (hem) frServer.getin(gin1);     //调用服务器发送
                                    else frClient.getin1(gin1);     //调用客户端发送	
                                }
                            //回合数调整，先手显示

                            shifouxiazi[m, n] = 0;
                            //表示该位已存白子

                            player1sum++;
                            //白子总数加1
                            if (((player2sum == 112) && (player1sum == 113)) || ((player2sum == 113) && (player1sum == 112)))
                            {
                                //平局判断
                                nowin = true;
                                over = true;
                            }
                            for (i = 0; i < 572; i++)
                            {
                                //同上，获胜表处理
                                if (tableplayer1[m, n, i] && ifwin[0, i] != 7)
                                    ifwin[0, i]++;
                                if (tableplayer2[m, n, i])
                                {
                                    tableplayer2[m, n, i] = false;
                                    ifwin[1, i] = 7;
                                }
                            }
                        }
                    }
                }
                else
                    if (player2)
                        if (x < 600 && y < 600)
                        {
                            //黑棋走
                            m = (int)Math.Floor((double)x / 40);
                            n = (int)Math.Floor((double)y / 40);
                            if (shifouxiazi[m, n] == 2)
                            {
                                //判断未下子情况下界面相应显示
                                lbPState1.Text = "X" + m + " Y" + n;
                                lbWait.Text = "等待白棋";

                                this.tbRecord.Text = tbRecord.Text + "黑棋:" + "X" + m + "Y" + n + "\r\n";
                                begin = false;

                                string gin = "hei;" + m + "," + n + ",";
                                if (hem) frServer.getin(gin);
                                else frClient.getin1(gin);
                                //发送下棋信息，包括：棋子颜色、坐标（X，Y）

                                if (lbFristName.Text == "黑棋")
                                {
                                    huihe++;
                                    lbCountNum.Text = "" + huihe;
                                }
                                else
                                    if (lbFristName.Text == "待定")
                                    {
                                        string gin1 = "xia1";
                                        lbFristName.Text = "黑棋";
                                        huihe++;
                                        lbCountNum.Text = "" + huihe;
                                        if (hem) frServer.getin(gin1);
                                        else frClient.getin1(gin1);
                                        //发送先手信息
                                    }
                                //回合数调整，先手显示

                                shifouxiazi[m, n] = 1;
                                //表示该位已存黑子
                                player2sum++;
                                //黑子总数加1
                                if (((player2sum == 112) && (player1sum == 113)) || ((player2sum == 113) && (player1sum == 112)))
                                {
                                    //平局判断
                                    nowin = true;
                                    over = true;
                                }
                                for (i = 0; i < 572; i++)
                                {
                                    //同上，获胜表处理
                                    if (tableplayer2[m, n, i] && ifwin[1, i] != 7)
                                        ifwin[1, i]++;
                                    if (tableplayer1[m, n, i])
                                    {
                                        tableplayer1[m, n, i] = false;
                                        ifwin[0, i] = 7;
                                    }
                                }
                            }
                        }
            }
            else MessageBox.Show(this, "等待对方下棋！", "网络对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            //网络对战中暂未取得下棋权
        }

        Graphics oo;
        public void paint()
        {
            oo = this.CreateGraphics();
            oo.DrawImage(map, 0, 10, map.Width, map.Height);


            //对接收到的下棋信息进行处理
            if (per == 0)
                shifouxiazi[wpx, wpy] = 0;
            if (per == 1)
                shifouxiazi[wpx, wpy] = 1;


            lbCountNum.Text = "" + huihe;
            //回合数刷新
            if (!over)
            {
                if (!nplayers)
                    if (!wplayers)
                        if (player2)
                            computerdown();
                //人机对战状态下电脑下棋

                //判断是否有一方取胜
                for (i = 0; i <= 1; i++)
                    for (j = 0; j < 572; j++)
                    {
                        if (ifwin[i, j] == 5)
                            if (i == 0)
                            {
                                win0 = true;
                                over = true;
                                GetScore(player1lines, player2lines, ref  score1, ref  score2);
                                break;
                            }
                            else
                            {
                                win1 = true;
                                over = true;
                                GetScore(player1lines, player2lines, ref  score1, ref  score2);
                                break;
                            }
                        if (over)
                            break;
                    }
            }
        }

        /// <summary>
        /// 刷屏函数，重画棋子棋盘，专用于网络对战状态（防止延迟）
        /// </summary>
        public void paintdown1()
        {
            paint();

            //结果显示
            //白方取胜
            if (win0)
            {
                if (!wplayers)
                    if (!nplayers)
                    {
                        //单人模式下
                        lbWinner.Text = "玩家";
                        MessageBox.Show(this, "大侠厉害！F1重新开始，ESC离开游戏。", "获胜", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                    else
                    {
                        //双人对战模式下
                        lbWinner.Text = "玩家2";
                        MessageBox.Show(this, "白棋获胜！F1重新开始，ESC离开游戏。", "双人对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                else
                {
                    //网络对战模式下
                    //发送获胜信息，并显示
                    if (hem)
                    {
                        string gin = "in0;";
                        frServer.getin(gin);
                        lbWinner.Text = lbPlay2.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                    else
                    {
                        string gin = "in0;";
                        frClient.getin1(gin);
                        lbWinner.Text = lbPlay2.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }

                    MessageBox.Show(this, "白棋获胜！选择网络菜单重新开始，ESC离开游戏。", "网络对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                }
            }

              //黑方取胜
            else if (win1)
            {
                if (!wplayers)
                    if (!nplayers)
                    {
                        //单人模式下
                        lbWinner.Text = "电脑";
                        MessageBox.Show(this, "胜败乃兵家常事，大侠请重新再来！F1重新开始，ESC离开游戏。", "无尽的失败", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                    else
                    {
                        //双人对战模式下
                        lbWinner.Text = "玩家1";
                        lbWinScores.Text = GetWinScore(score1, score2);
                        MessageBox.Show(this, "黑棋获胜！F1重新开始，ESC离开游戏。", "双人对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    }
                else
                {
                    //网络对战模式下

                    //发送获胜信息，并显示      
                    if (hem)
                    {
                        string gin = "in1;";
                        frServer.getin(gin);
                        lbWinner.Text = lbPlay1.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                    else
                    {
                        string gin = "in1;";
                        frClient.getin1(gin);
                        lbWinner.Text = lbPlay1.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }

                    MessageBox.Show(this, "黑棋获胜！选择网络菜单重新开始，ESC离开游戏。", "网络对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);

                }
            }
            //平局情况下
            else if (nowin)
            {
                
                if (!wplayers)
                {
                    //非网络对战模式下
                    lbWinner.Text = "无";
                    lbWinScores.Text = GetWinScore(score1, score2);
                    MessageBox.Show(this, "不分胜负！F1重新开始，ESC离开游戏。", "平局", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                }
                else
                {
                    //网络对战模式下

                    //发送平局信息
                    if (hem)
                    {
                        string gin = "now;";
                        frServer.getin(gin);
                        lbWinner.Text = frServer.tbSName.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }
                    else
                    {
                        string gin = "now;";
                        frClient.getin1(gin);
                        lbWinner.Text = frClient.tbCName.Text;
                        lbWinScores.Text = GetWinScore(score1, score2);
                    }

                    MessageBox.Show(this, "不分胜负！选择网络菜单重新开始，ESC离开游戏。", "网络对战", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);

                }
            }
            else
                for (i = 0; i <= 14; i++)
                    for (j = 0; j <= 14; j++)
                    {
                        if (shifouxiazi[i, j] == 0)
                        {
                            oo.DrawImage(bai, i * 40, j * 40+10, 40, 40);
                        }
                        if (shifouxiazi[i, j] == 1)
                        {
                            oo.DrawImage(hei, i * 40, j * 40+10, 40, 40);
                        }

                        //全屏幕更新
                    }
        }

        /// <summary>
        /// 刷屏函数，重画棋子棋盘，用于一般状态
        /// </summary>
        public void paintdown()
        {
            paint();
            for (i = 0; i <= 14; i++)
                for (j = 0; j <= 14; j++)
                {
                    if (shifouxiazi[i, j] == 0)
                    {
                        oo.DrawImage(bai, i * 40, j * 40+10, 40, 40);
                    }
                    if (shifouxiazi[i, j] == 1)
                    {
                        oo.DrawImage(hei, i * 40, j * 40+10, 40, 40);
                    }

                    //全屏幕更新
                }
        }

        /// <summary>
        /// 电脑走棋程序，人机对战核心算法
        /// </summary>
        private void computerdown()
        {
            //回合数及先手显示
            if (lbPlay1.Text == "待定")
            {
                lbPlay1.Text = "电脑";
                lbPlay2.Text = "玩家";
            }

            if (lbFristName.Text == "黑棋")
            {
                huihe++;
                lbCountNum.Text = "" + huihe;
            }
            else
                if (lbFristName.Text == "待定")
                {
                    lbFristName.Text = "黑棋";
                    huihe++;
                    lbCountNum.Text = "" + huihe;
                }

            //加分算法
            //取棋盘每一个位置，算它与8各方向所有连子分数之和，取分数最大点下子
            //电脑固定取黑棋，所以这里在同等情况下保持黑棋分数约大于白棋，电脑侧重于进攻
            for (i = 0; i <= 14; i++)
                for (j = 0; j <= 14; j++)
                {
                    player1lines[i, j] = 0;
                    //总分数清零
                    if (shifouxiazi[i, j] == 2)
                        for (k = 0; k < 572; k++)
                            if (tableplayer1[i, j, k])
                            {
                                //该位置可能取胜（为自方棋子）
                                switch (ifwin[0, k])
                                {
                                    //白棋取连子情况
                                    case 1:
                                        player1lines[i, j] += 30;   //形成1连子时,加30分
                                        break;
                                    case 2:
                                        player1lines[i, j] += 120;   //形成2连子时,加120分
                                        break;
                                    case 3:
                                        player1lines[i, j] += 300;  //形成3连子时,加300分
                                        break;
                                    case 4:
                                        player1lines[i, j] += 720; //形成4连子时,加720分
                                        break;
                                }
                            }
                }

            for (i = 0; i <= 14; i++)
                for (j = 0; j <= 14; j++)
                {
                    player2lines[i, j] = 0;
                    //总分数清零
                    if (shifouxiazi[i, j] == 2)
                        for (k = 0; k < 572; k++)
                            if (tableplayer2[i, j, k])
                            {
                                //该位置可能取胜（为自方棋子） 
                                switch (ifwin[1, k])
                                {
                                    //黑棋取连子情况
                                    case 1:
                                        player2lines[i, j] += 35;  //形成1连子时,加35分
                                        break;
                                    case 2:
                                        player2lines[i, j] += 135;  //形成2连子时,加135分
                                        break;
                                    case 3:
                                        player2lines[i, j] += 350;  //形成3连子时,加350分
                                        break;
                                    case 4:
                                        player2lines[i, j] += 800;  //形成4连子时,加800分
                                        break;
                                }
                            }
                }

            if (start)
            {
                //电脑第一次下子
                if (shifouxiazi[7, 7] == 2)
                {
                    m = 7;
                    n = 7;
                }
                else
                {
                    m = 8;
                    n = 8;
                }
                start = false;
            }
            else
            {
                //选择分数最大位置，置为（M，N）
                for (i = 0; i < 15; i++)
                    for (j = 0; j < 15; j++)
                        if (shifouxiazi[i, j] == 2)
                        {
                            if (player2lines[i, j] >= lines2max)
                            {
                                lines2max = player2lines[i, j];
                                l1max_x = i;
                                l1max_y = j;
                            }
                            if (player1lines[i, j] >= lines1max)
                            {
                                lines1max = player1lines[i, j];
                                l2max_x = i;
                                l2max_y = j;
                            }
                        }

                if (lines2max >= lines1max)
                {
                    m = l1max_x;
                    n = l1max_y;
                }
                else
                {
                    m = l2max_x;
                    n = l2max_y;
                }
            }

            lbPState1.Text = "X" + m + " Y" + n;
            //显示电脑下棋位置

            if (!wplayers)
            {
                lbWait.Text = "等待白棋";
                this.tbRecord.Text = tbRecord.Text + "黑棋:" + "X" + m + "Y" + n + "\r\n";
            }
            //加入历史记录

            player2sum++;
            //总子数加1

            lines2max = 0;
            lines1max = 0;
            shifouxiazi[m, n] = 1;

            //平局判断
            if (((player2sum == 112) && (player1sum == 113)) || ((player2sum == 113) && (player1sum == 112)))
            {
                nowin = true;
                over = true;
            }

            //对取胜表着相关处理、
            for (i = 0; i < 572; i++)
            {
                if (tableplayer2[m, n, i] && ifwin[1, i] != 7)
                    ifwin[1, i]++;
                if (tableplayer1[m, n, i])
                {
                    tableplayer1[m, n, i] = false;
                    ifwin[0, i] = 7;
                }
            }

            player1 = true;
            player2 = false;
            //交换下棋权利
        }

        /// <summary>
        /// 单机模式下的初始化函数，重复开始时使用
        /// </summary>
        public void gamebegin()
        {
            for (i = 0; i < 15; i++)
                for (j = 0; j < 15; j++)
                {
                    //置棋盘为空，各点分数为零
                    player1lines[i, j] = 0;
                    player2lines[i, j] = 0;
                    shifouxiazi[i, j] = 2;
                }

            //所有获胜组合的初始化
            WinMethod();

            //连子数清零
            for (i = 0; i <= 1; i++)
                for (j = 0; j < 572; j++)
                    ifwin[i, j] = 0;

            //随机取先手
            if (!wplayers)
            {
                Random rdm1 = new Random(unchecked((int)DateTime.Now.Ticks));
                if (rdm1.Next() % 2 == 0)
                    player2 = true;
                else
                    player1 = true;
            }

            //相关变量初始化
            count = 0;
            player2sum = 0;
            player1sum = 0;
            start = true;
            over = false;
            win0 = false;
            win1 = false;
            nowin = false;
        }

        /// <summary>
        /// 屏幕显示要素的初始化
        /// </summary>
        public void KongJianName()
        {
            huihe = 0;
            lbFristName.Text = "待定";
            lbWinner.Text = "待定";
            gamebegin();
            lbPState1.Text = "待定";
            lbPState2.Text = "待定";
            lbCountNum.Text = "" + huihe;
            lbWait.Text = "先手未定";
            tbRecord.Text = "";
            lbWinScores.Text = "待定";
        }

        /// <summary>
        /// 获取赢家的分数
        /// </summary>
        /// <returns></returns>
        public string GetWinScore(int score1, int score2)
        {
            string winscore = "";
            if (score1 > score2)
                winscore = score1.ToString();
            else if (score1 < score2)
                winscore = score2.ToString();
            else winscore = score1.ToString();
            return winscore;
        }

        /// <summary>
        /// 算分数
        /// </summary>
        public void GetScore(int[,] player1lines, int[,] player2lines, ref int score1, ref int score2)
        {
            score1 = 0;
            score2 = 0;
            for (int ii = 0; ii <= 14; ii++)
            {
                for (int jj = 0; jj <= 14; jj++)
                {
                    score1 += player1lines[ii, jj];
                    score2 += player2lines[ii, jj];
                }
            }
        }

        #endregion


        #region 窗体方法

        public FrMain()
        {
            InitializeComponent();
        }

        //初始化函数,包括棋盘信息、所有获胜组合等的初始化
        private void FrMain_Load(object sender, EventArgs e)
        {
            start = true;
            this.Width = 756;
            this.Height = 730;

            //把棋盘所有位置置为空（未下子）
            for (i = 0; i < 15; i++)
                for (j = 0; j < 15; j++)
                    shifouxiazi[i, j] = 2;

            //所有获胜组合的初始化
            WinMethod();

            Random rdm1 = new Random(unchecked((int)DateTime.Now.Ticks));

            //新的一局棋开始时,随机选择是player1先开始还是player2先开始
            if (!wplayers)
            {
                if (rdm1.Next() % 2 == 0)
                {
                    player2 = true;
                }
                else
                {
                    player1 = true;
                }
                count = 0;
            }
            computertime = Environment.TickCount;
            string str = DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日 (" + DateTime.Now.DayOfWeek + ")";
            label2.Text = str;
            label3.Text = DateTime.Now.ToLongTimeString();
        }

        //游戏运行核心，分别完成人机对战、双人对战、网络对战相关调度和处理
        //完成下棋点的确定，界面信息的更新，发送网络对战信息
        private void FrMain_MouseDown(object sender, MouseEventArgs e)
        {
            if ((!win0) && (!win1) && (!nowin))
            {
                //当未有一方取胜时
                if (!over)
                    //尚未结束
                    if (!wplayers)
                    {
                        //不是网络对战状态
                        NotNetGame();
                    }
                    else
                    {
                        //网络对战状态
                        NetGame();
                    }
            }

            //判断是否有一方取胜
            if (!over)
            {
                for (i = 0; i <= 1; i++)
                    for (j = 0; j < 572; j++)
                    {
                        if (ifwin[i, j] == 5)
                            if (i == 0)
                            {
                                win0 = true;  //白方取胜
                                over = true;
                                break;
                            }
                            else
                            {
                                win1 = true;  //黑方取胜
                                over = true;
                                break;
                            }
                        if (over)
                            break;
                    }
            }
            paintdown1();
            //刷屏
        }

        //热键设定
        private void FrMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                this.Close();
            if (e.KeyCode == Keys.F1)
                gamebegin();
            paintdown();
        }

        //像素选取
        private void FrMain_MouseMove(object sender, MouseEventArgs e)
        {
            x = e.X;
            y = e.Y;

            m = (int)Math.Floor((double)x / 40);
            n = (int)Math.Floor((double)y / 40);
            label5.Text ="X" + m + " Y" + n;
        }

        //更新界面
        private void FrMain_Paint(object sender, PaintEventArgs e)
        {
            paintdown();
        }

        //单机游戏----开始
        //屏幕显示要素的初始化
        private void tsmiStart_Click(object sender, EventArgs e)
        {
            KongJianName();
            if (!nplayers)
            {
                lbPlay1.Text = "电脑";
                lbPlay2.Text = "玩家";
            }
            else
            {
                lbPlay1.Text = "玩家1";
                lbPlay2.Text = "玩家2";
            }
        }

        //退出游戏
        private void tsmiClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //单机模式----人机对战
        //屏幕显示要素的初始化，模式设置
        private void tsmiPvC_Click(object sender, EventArgs e)
        {
            KongJianName();
            nplayers = false;
            wplayers = false;
            lbPlay1.Text = "电脑";
            lbPlay2.Text = "玩家";
        }

        //单机模式----双人对战
        //屏幕显示要素的初始化，模式设置
        private void tsmiPvP_Click(object sender, EventArgs e)
        {
            KongJianName();
            wplayers = false;
            nplayers = true;
            lbPlay1.Text = "玩家1";
            lbPlay2.Text = "玩家2";
        }



        //网络对战----建立服务器
        private void tsmiServer_Click(object sender, EventArgs e)
        {
            if (!contet1)
            {
                if (!contet)
                {
                    //未连接情况下进行连接，否则屏蔽该操作，防止错误
                    //对网络连接所需信息及界面信息进行初始化
                    //模式切换
                    frServer = new FrServer(this);
                    frClient = new FrClient(this);
                    frServer.Show();
                    //窗体实例化
                    nplayers = false;
                    wplayers = true;
                    hem = true;
                    pat = false;
                    KongJianName();
                    paintdown();
                }
                else MessageBox.Show(this, "已经建立服务器，无法再次创建！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                contet0 = true;
            }
            else MessageBox.Show(this, "只能打开服务器与客户端之一，请退出重进！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            //已打开客户端窗口
        }

        //网络对战----请求连接
        private void tsmiClient_Click(object sender, EventArgs e)
        {
            if (!contet0)
            {
                if (!contet)
                {
                    //未连接情况下进行连接，否则屏蔽该操作，防止错误
                    //对网络连接所需信息及界面信息进行初始化
                    //模式切换
                    frClient = new FrClient(this);
                    frServer = new FrServer(this);
                    frClient.Show();
                    //窗体实例化
                    nplayers = false;
                    wplayers = true;
                    pat = true;
                    hem = false;
                    begin = true;
                    KongJianName();
                    paintdown();
                }
                else MessageBox.Show(this, "已经连接服务器，无法再次连接！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                contet1 = true;
            }
            //已打服务器窗口
            else MessageBox.Show(this, "只能打开服务器与客户端之一，请退出重进！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
        }

        //网络对战----重新开始
        private void tsmiRestart_Click(object sender, EventArgs e)
        {
            if (contet)
            {
                //已经连接
                nplayers = false;
                wplayers = true;

                //当前所处状态（服务器 OR 客户端）确定，并发送相关信息
                if (hem)
                {
                    string gin = "gin;hem";
                    frServer.getin(gin);
                }
                else
                {
                    begin = true;
                    string gin = "gin;pat";
                    frClient.getin1(gin);
                }

                //界面要素初始化
                KongJianName();
                paintdown();
            }
            else MessageBox.Show(this, "尚未连接成功！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            //连接断开            
        }

        #endregion


        #region 显示时间

        private void timer1_Tick(object sender, EventArgs e)
        {
            long currenttime = Environment.TickCount;
            long diffenence = currenttime - computertime;

            long applicationhour, applicationminute, applicationsecond;
            //将毫秒转换成为小时，分钟和秒
            applicationhour = (diffenence / (3600 * 999)) % 24;
            applicationminute = (diffenence / (60 * 999)) % 60;
            applicationsecond = (diffenence / (999)) % 60;

            //将求出信息进行显示
            label3.Text = DateTime.Now.ToLongTimeString();
            this.label4.Text = string.Format("程序已启动{0}小时，{1}分钟，{2}秒", applicationhour.ToString(), applicationminute.ToString(), applicationsecond.ToString());
        }

        #endregion
 
    }
}