WPF版贪吃蛇(案例+代码)

一. 分析:

  • 1.在Window里添加事件loaded指加载完成后再执行
    • 2.先设置.xaml文件的画布Canvas,再起一个变量名
    • 3.设置界面this
    • 4.添加边框border
    • 5.创建一个方法用来写蛇CreatSnake();
    • 6.在创建一个计时器,先添加计时器的命名空间,用这个计时器来控制蛇移动
    • 7.在蛇移动之前,把蛇添加到泛型数组用来装蛇,给泛型添加for,并给每个泛型添的集合加tag的值,用这些tag值控制移动,一开始获取蛇本身添加tag值,获取一开始的移动 Canvas.SetLeft(sheJH[i],Canvas.GetLeft(sheJH[i])-size);蛇泛型每次调用都给蛇的Left或Top减或加一次
    • (1)先for循环,把创建的值添加给泛型
    • (2)每次事件调用都会获取tag的值改变top或left的tag值
    • (3)又因为上下左右要改变tag值,所以要使后面的tag值等于前一个tag值,就会陆续改变相应的tag值,蛇头后面的tag值会以次改变tag值
    • (4)又在外面创建一个方法用来储存food,然后if判断当蛇头和食物的位置一样时,就会添加一个食物,所以在if里面创建border的蛇身,在每次添加一个蛇身,添加蛇身时先把要添加蛇身位置设置好,就直接添加到蛇尾上,先添加到游戏界面 GM.Children.Add(tianjia);,在把添加的蛇身添加给蛇泛型集合sheJH.Add(tianjia);
    • 8.给全局添加按键事件,控制tag值,每次按下键时就改变tag值,按下键就会改变tag值
    • 9.添加附加游戏特点

二.案例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Media;

namespace WPF版贪吃蛇
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //设置边框样式
            this.WindowStyle = WindowStyle.None;
            //框架是否支持透明度
            this.AllowsTransparency = true;//在loaded里加透明时不让他计算机本身的颜色影响
        }
        //加音乐
        MediaPlayer yinyue1 = new MediaPlayer();
        MediaPlayer yinyue2 = new MediaPlayer();

    int size = 20;
    //泛型用来装蛇
    List sheJH = new List();
    //泛型装第二条蛇
    List sheJH2 = new List();

    //设置游戏界面格子数
    int rows=60,cols=35;
    //设置边框
    Border gMborder = new Border();
    //定义一个top和left,用来记录食物随机所在的范围
    double top = 0, left = 0;
   
    //随机食物
    Random sj = new Random();
    //开始按钮
    Button KS1 = new Button();
    //倒计时
    DispatcherTimer dao = new DispatcherTimer();
    //3、蛇的移动用一个timer控制蛇的移动
    DispatcherTimer moveTimer = new DispatcherTimer();
    //随机蛇身
    int s = 0;

    //倒数的盒子
    Label daoshu = new Label();
    //倒数记录的数字
    int num = 11;

    //记录按键的ture
    bool boo = true;
    //加速器
    Button JS = new Button();
    //中速器
    Button ZS = new Button();
    //慢速
    Button MS = new Button();

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        /*yinyue1.Open(new Uri("../../yin/BG音乐.wav", UriKind.Relative));
        yinyue1.Play();*/
        //1、设置窗口的最大化
        this.WindowState = WindowState.Maximized;
        //设置填充背景色
        this.Background = Brushes.Transparent;
        //设置渐变
        this.Background = new RadialGradientBrush(Colors.Yellow,Colors.Green);
        //设置不透明度
        this.Opacity = 0.5;

        //3、食物的创建
        SJFood();
        //2、第一条蛇:创建蛇的方法
        CreatSnake(1, 500, 400);
        //3、第一条蛇:创建蛇的方法
        CreatSnake(2, 300, 200);

        //3、蛇的移动用一个timer控制蛇的移动
        //DispatcherTimer moveTimer = new DispatcherTimer();
        /*moveTimer.Start();*/
        //moveTimer.Interval = TimeSpan.FromMilliseconds(100);
        moveTimer.Tick += MoveTimer_Tick;

        //设置游戏界面和窗口给一样的宽高
        GM.Width = this.Width;//1293
        GM.Height = this.Height;//733

       /* //设置边框
        Border gMborder = new Border();*/
        gMborder.Width = size * rows;//宽度用格子数乘以每个盒子具体的宽度20
        gMborder.Height = size * cols;//高度用格子数乘以每个盒子具体的高度20
        gMborder.BorderThickness = new Thickness(20);//边框的厚度
        //gMborder.BorderBrush = Brushes.Black;
        gMborder.BorderBrush = new LinearGradientBrush(Colors.Black, Colors.White, 0);
       // gMborder.CornerRadius = new CornerRadius(1);//弧度
        Canvas.SetLeft(gMborder,(GM.Width-gMborder.Width)/2);
        Canvas.SetTop(gMborder,(GM.Height-gMborder.Height)/2);
        GM.Children.Add(gMborder);

        //获取边框和游戏界面的那个宽度
        top = Canvas.GetTop(gMborder) + 20;
        left = Canvas.GetLeft(gMborder) + 20;

/*
//3、食物的创建
SJFood();
//2、第一条蛇:创建蛇的方法
CreatSnake(1, 500, 400);
//3、第一条蛇:创建蛇的方法
CreatSnake(2, 300, 200);*/

        //倒计时的时间
        //DispatcherTimer dao = new DispatcherTimer();
        dao.Interval = TimeSpan.FromMilliseconds(300);
        dao.Tick += Dao_Tick;//倒计时

        /*//3、第一条蛇:创建蛇的方法
        CreatSnake(2,300,200);*/
        //蛇左右上下按键
        this.KeyDown += MainWindow_KeyDown;

        //按键加速
        this.KeyUp += MainWindow_KeyUp;

        /* //2、第一条蛇:创建蛇的方法
         CreatSnake(1, 500, 400);
         //3、第一条蛇:创建蛇的方法
         CreatSnake(2, 300, 200);*/
        //创建末尾添加东西
        //TJ();

       /* //开始按钮
        Button KS1 = new Button();*/
        KS1.Content = "开始按钮";
        KS1.Width = 200;
        KS1.Height = 80;
        KS1.Tag = "ks";
        KS1.FontSize = 30;
       // KS1.FontStyle =FontStyles.
        Canvas.SetLeft(KS1,GM.Width/2-KS1.Width/2);
        Canvas.SetTop(KS1,170);
        KS1.Click += KS1_Click;
        GM.Children.Add(KS1);
        //加速器
        //Button JS = new Button();
        JS.Content = "加速按钮";
        JS.Width = 200;
        JS.Height = 80;
        JS.Tag = "js";
        JS.FontSize = 30;
        Canvas.SetLeft(JS, GM.Width / 2 - JS.Width / 2);
        Canvas.SetTop(JS, 270);
        JS.Click += JS_Click;
        GM.Children.Add(JS);
        //中速器
        //Button ZS = new Button();
        ZS.Content = "中速按钮";
        ZS.Width = 200;
        ZS.Height = 80;
        ZS.Tag = "js";
        ZS.FontSize = 30;
        Canvas.SetLeft(ZS, GM.Width / 2 - ZS.Width / 2);
        Canvas.SetTop(ZS,370);
        ZS.Click += ZS_Click;
        GM.Children.Add(ZS);
        //慢速
        //Button MS = new Button();
        MS.Content = "慢速按钮";
        MS.Width = 200;
        MS.Height = 80;
        MS.Tag = "js";
        MS.FontSize = 30;
        Canvas.SetLeft(MS, GM.Width / 2 - MS.Width / 2);
        Canvas.SetTop(MS, 470);
        MS.Click += MS_Click;
        GM.Children.Add(MS);

        //毒食物
        Dufood();
    }

    Border dufood;//每调用一次会从新复制,如果不加全局变量就会每创建一次从新添加一次
    private void Dufood()
    {
        dufood = new Border();
        dufood.Width = dufood.Height = size;
        dufood.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255))));
        Canvas.SetLeft(dufood,sj.Next(2,rows-3)*size);
        Canvas.SetTop(dufood,sj.Next(2,cols-3)*size);
        GM.Children.Add(dufood);
    }

    private void MainWindow_KeyUp(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.L:
                /* if (e.KeyStates == Keyboard.GetKeyStates(Key.RightCtrl))
                 {*/
                moveTimer.Interval = TimeSpan.FromMilliseconds(150);
                /*}*/
                break;
            default:
                break;
        }

      /*  //上下 左右键加快1111111111111111111
        switch (e.Key)
        {
            case Key.Left:
                moveTimer.Interval = TimeSpan.FromMilliseconds(150);
                break;
            case Key.Right:
                moveTimer.Interval = TimeSpan.FromMilliseconds(150);
                break;
            case Key.Up:
                moveTimer.Interval = TimeSpan.FromMilliseconds(150);
                break;
            case Key.Down:
                moveTimer.Interval = TimeSpan.FromMilliseconds(150);
                break;

            default:
                break;
        }*/
    }

    private void Dao_Tick(object sender, EventArgs e)
    {
        //倒数数字
        /*Label daoshu = new Label();*/
        num--;
        daoshu.Content = num;
        daoshu.FontSize = 30;
        Canvas.SetLeft(daoshu, GM.Width / 2 - KS1.Width / 2+85);
        Canvas.SetTop(daoshu, GM.Height / 2 - KS1.Height / 2);
        //GM.Children.Add(daoshu);
        if (num<0)//num的结束
        {
            num = 0;
            GM.Children.Remove(daoshu);
            //游戏开始游戏
           /* yinyue1.Open(new Uri("../../yin/BG音乐.wav", UriKind.Relative));
            yinyue1.Play();*/
            //蛇的移动
            moveTimer.Start();
        }
        return;
    }

    private void KS1_Click(object sender, RoutedEventArgs e)
    {
        /* Label daoshu = new Label();
         num--;
         daoshu.Content = num;
         daoshu.FontSize = 30;
         Canvas.SetLeft(daoshu, GM.Width / 2 - KS1.Width / 2);
         Canvas.SetTop(daoshu, GM.Height / 2 - KS1.Height / 2);*/
        //int num = 10;
        if (KS1.Content.ToString()== "开始按钮")
        {
            //点击按钮就会移除其他的
            GM.Children.Remove(KS1);
            GM.Children.Remove(JS);
            GM.Children.Remove(MS);
            GM.Children.Remove(ZS);
            //倒数数字
            dao.Start();
            GM.Children.Add(daoshu);
            moveTimer.Interval = TimeSpan.FromMilliseconds(100);
            /*if (num <= 1)
            {
                GM.Children.Remove(daoshu);
            }*/

        }
        yinyue1.Open(new Uri("../../yin/BG音乐.wav", UriKind.Relative));
        yinyue1.Play();
    }
    //中速
    private void ZS_Click(object sender, RoutedEventArgs e)
    {
        if (ZS.Content.ToString() == "中速按钮")
        {
            //点击按钮就会移除其他的
            GM.Children.Remove(JS);
            GM.Children.Remove(KS1);
            GM.Children.Remove(MS);
            GM.Children.Remove(ZS);
            //倒数数字
            dao.Start();
            GM.Children.Add(daoshu);
            moveTimer.Interval = TimeSpan.FromMilliseconds(150);
        }
    }

    //快速
    private void JS_Click(object sender, RoutedEventArgs e)
    {
        if (JS.Content.ToString() == "加速按钮")
        {
            //点击按钮就会移除其他的
            GM.Children.Remove(JS);
            GM.Children.Remove(KS1);
            GM.Children.Remove(MS);
            GM.Children.Remove(ZS);
            //倒数数字
            dao.Start();
            GM.Children.Add(daoshu);
            moveTimer.Interval = TimeSpan.FromMilliseconds(30);
        }
    }
    //慢速
    private void MS_Click(object sender, RoutedEventArgs e)
    {
        if (MS.Content.ToString() == "慢速按钮")
        {
            //点击按钮就会移除其他的
            GM.Children.Remove(MS);
            GM.Children.Remove(KS1);
            GM.Children.Remove(JS);
            GM.Children.Remove(ZS);
            //开始倒数数字
            dao.Start();
            //把倒数的文本加到页面
            GM.Children.Add(daoshu);
            moveTimer.Interval = TimeSpan.FromMilliseconds(300);
        }
    }

    Border food;//每次碰到食物会可以从新创建,原因是每次调用的时候回从新返回这里然后从新获取food,从新放值,不会创建多个,如果不在外面定义一个变量,则会每次从新生成一个,会有多个食物
    private void SJFood()
    {
        food = new Border();
        food.Width = food.Height = size;
        food.Background = new RadialGradientBrush(Colors.Black,Colors.Red);
        food.CornerRadius = new CornerRadius(10);
        //随机食物的范围
        Canvas.SetLeft(food,sj.Next(2,rows-3)*size);
        Canvas.SetTop(food,sj.Next(2,cols-3)*size);
        GM.Children.Add(food);
    }

    //按键
    private void MainWindow_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            //第一个蛇的按键
            case Key.Left:
                if (!(sheJH[0].Tag.ToString() == "Right")&&sheJH.Count>0)
                {
                  sheJH[0].Tag = "Left";
                }
                break;
            case Key.Right:
                if (!(sheJH[0].Tag.ToString() == "Left") && sheJH.Count > 0)
                {
                    sheJH[0].Tag = "Right";
                }
                break;
            case Key.Up:
                if (!(sheJH[0].Tag.ToString() == "Up" )&& sheJH.Count > 0)
                {
                    sheJH[0].Tag = "Top";
                }
                break;
            case Key.Down:
                if (!(sheJH[0].Tag.ToString() == "Top") && sheJH.Count > 0)
                {
                    sheJH[0].Tag = "Up";
                }
                break;

            //第二个蛇的按键

            case Key.W:
                if (!(sheJH2[0].Tag.ToString() == "S") && sheJH.Count > 0)
                {
                   sheJH2[0].Tag = "W";
                }
                break;
            case Key.A:
                if (!(sheJH2[0].Tag.ToString() == "D") && sheJH.Count > 0)
                {
                    sheJH2[0].Tag = "A";
                }
                break;
            case Key.D:
                if (!(sheJH2[0].Tag.ToString() == "A") && sheJH.Count > 0)
                {
                    sheJH2[0].Tag = "D";
                }
                break;
            case Key.S:
                if (!(sheJH2[0].Tag.ToString() == "W") && sheJH.Count > 0)
                {
                    sheJH2[0].Tag = "S";
                }
                break;


           /* //快速键
            case Key.LeftShift:
                if (boo == true)
                {
                    moveTimer.Stop();
                    boo = false;
                }
                else
                {
                    moveTimer.Start();
                    boo = true;
                }
                break;*/
            default:
                break;
        }
        if (e.KeyStates == Keyboard.GetKeyStates(Key.M))
        {
            if (boo == true)
            {
                moveTimer.Stop();
                boo = false;
            }
            else if(boo==false)
            {
                moveTimer.Start();
                boo = true;
            }
        }
        else if (e.KeyStates == Keyboard.GetKeyStates(Key.L))
        {
            moveTimer.Interval = TimeSpan.FromMilliseconds(20);
        }
        /*else if (e.KeyStates == Keyboard.GetKeyStates(Key.Left) || e.KeyStates == Keyboard.GetKeyStates(Key.Right) || e.KeyStates == Keyboard.GetKeyStates(Key.Up) || e.KeyStates == Keyboard.GetKeyStates(Key.Down)) ;
        {
            moveTimer.Interval = TimeSpan.FromMilliseconds(20);
        }*/
    }

    //蛇的移动//每隔多少分钟会自动调用这里面的tag值,一开始会给默认的tag让他进来,获取默认的值直接走
    private void MoveTimer_Tick(object sender, EventArgs e)
    {
        //**********************************************************************************************************
       //第一个泛型控制蛇tag的值,然后根据按键获取tag的值
        for (int i = 0; i < sheJH.Count; i++)
        {
            if (sheJH[i].Tag.ToString()== "Left")
            {
                Canvas.SetLeft(sheJH[i],Canvas.GetLeft(sheJH[i])-size);
            }
            else if (sheJH[i].Tag.ToString()== "Right")
            {
                Canvas.SetLeft(sheJH[i],Canvas.GetLeft(sheJH[i])+size);
            }
            else if (sheJH[i].Tag.ToString() == "Top")
            {
                Canvas.SetTop(sheJH[i],Canvas.GetTop(sheJH[i])-size);
            }
            else if (sheJH[i].Tag.ToString() == "Up")
            {
                Canvas.SetTop(sheJH[i],Canvas.GetTop(sheJH[i])+size);
            }
            //sheJH.Count > 0 && sheJH2.Count > 0不能为空
            if (sheJH.Count > 0 && sheJH2.Count > 0 && Canvas.GetLeft(sheJH2[0])==Canvas.GetLeft(sheJH[i])&&Canvas.GetTop(sheJH2[0])==Canvas.GetTop(sheJH[i]))
            {
               // MessageBox.Show("碰到身体了");
                //moveTimer.Stop();
                //GM.Children.Remove(sheJH[i]);
                //我碰到另一条,然后我消失
                for (int j = 0; j < sheJH2.Count; j++)
                {
                    GM.Children.Remove(sheJH2[j]);
                    
                }
                sheJH2.Clear();
                return;
            }

            /*if (Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(food) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(food))
            {
                Border tianjia = new Border();
                tianjia.Width = food.Height = 20;
                tianjia.Tag = " ";
                tianjia.Background = Brushes.AliceBlue;
                tianjia.CornerRadius = new CornerRadius(10);
                Canvas.SetLeft(tianjia,Canvas.GetLeft(sheJH[sheJH.Count-1]));
                Canvas.SetTop(tianjia,Canvas.GetTop(sheJH[sheJH.Count-1]));
                sheJH.Add(tianjia);
                GM.Children.Add(tianjia);
             

                *//*GM.Children.Remove(food);
                SJFood();*//*
                Canvas.SetLeft(food, sj.Next(rows) * size);
                Canvas.SetTop(food, sj.Next(cols) * size);
            }*/
        }

        //第二个蛇泛型遍历改变蛇的每一个位置
        for (int i = 0; i < sheJH2.Count; i++)
        {
            if (sheJH2[i].Tag.ToString()=="D")
            {
                Canvas.SetLeft(sheJH2[i], Canvas.GetLeft(sheJH2[i]) + size);
            }
            else if (sheJH2[i].Tag.ToString()=="A")
            {
                Canvas.SetLeft(sheJH2[i], Canvas.GetLeft(sheJH2[i]) - size);
            }
            else if (sheJH2[i].Tag.ToString()=="S")
            {
                Canvas.SetTop(sheJH2[i],Canvas.GetTop(sheJH2[i])+size);
            }
            else if (sheJH2[i].Tag.ToString()=="W")
            {
                Canvas.SetTop(sheJH2[i], Canvas.GetTop(sheJH2[i]) - size);
            }
            if (sheJH.Count>0&&sheJH2.Count>0&& Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(sheJH2[i]) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(sheJH2[i]))
            {
                // MessageBox.Show("碰到身体了");
                //moveTimer.Stop();
                //我碰到另一条,然后我消失
                for (int j= 0; j < sheJH.Count; j++)
                {
                    GM.Children.Remove(sheJH[j]);
                }
                sheJH.Clear();//只清除一次,把全部的清除,不能放在for循环里面,否则循环一次sheJH.Clear()会清除一次
                return;
            }
        }
        //********************************************************************************************************
        //1、第二个蛇:蛇头跟随身子,一定要放在添加食物之前,原因是先让tag的最后一个tag值等于前一个tag值,再添加新的蛇尾在赋给tag值,上下左右的值就会改变
        for (int i = sheJH2.Count - 1; i > 0; i--)
        {
            sheJH2[i].Tag = sheJH2[i - 1].Tag;
            //当蛇头碰到蛇身停止
            if (Canvas.GetLeft(sheJH2[0]) == Canvas.GetLeft(sheJH2[i]) && Canvas.GetTop(sheJH2[0]) == Canvas.GetTop(sheJH2[i]))
            {
                MessageBox.Show("蛇身碰到蛇头");//一下都不执行了
                moveTimer.Stop();
            }
        }

        //这个for的作用是让最后一个集合的值等于前一个
        for (int i = sheJH.Count - 1; i > 0; i--)
        {
            //表示最后一个tag的名字等于前一个tag名字
            sheJH[i].Tag = sheJH[i - 1].Tag;
            if (Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(sheJH[i]) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(sheJH[i]))
            {
                MessageBox.Show("碰到身体了");
                moveTimer.Stop();
                return;
            }
        }

        //*************************************************************************************************************
        //食物添加
        if (sheJH.Count > 0 && Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(food) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(food))
        {
            yinyue2.Open(new Uri("../../yin/吃食物.wav", UriKind.Relative));
            yinyue2.Play();
            //添加蛇身
            Border tianjia = new Border();
            tianjia.Width = tianjia.Height = size;
            tianjia.Tag = "TJ";
            //tianjia.Background = Brushes.Red;
            //this.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255))));
            s++;
            if (s * 2 == 0)
            {
                tianjia.Background = Brushes.Red;
            }
            else
            {
                tianjia.Background = Brushes.Yellow;
            }
            tianjia.CornerRadius = new CornerRadius(10);
            Canvas.SetLeft(tianjia, Canvas.GetLeft(sheJH[sheJH.Count - 1]));//添加到蛇集合的最后一个数
            Canvas.SetTop(tianjia, Canvas.GetTop(sheJH[sheJH.Count - 1]));
            GM.Children.Add(tianjia);
            sheJH.Add(tianjia);


            /*GM.Children.Remove(food);
            SJFood();*/
            Canvas.SetLeft(food, sj.Next(rows - 5) * size);
            Canvas.SetTop(food, sj.Next(cols - 5) * size);
        }
        //蛇头碰到食物,食物消失,并添加一个尾巴
        if (sheJH2.Count > 0 && Canvas.GetLeft(sheJH2[0]) == Canvas.GetLeft(food) && Canvas.GetTop(sheJH2[0]) == Canvas.GetTop(food))
        {
            //yinyue1.Pause();
            //碰到食物音乐
            yinyue2.Open(new Uri("../../yin/吃食物.wav", UriKind.Relative));
            yinyue2.Play();

            Border ERshe = new Border();
            ERshe.Tag = "er";//
            ERshe.Width = ERshe.Height = size;
            ERshe.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255)), Convert.ToByte(sj.Next(255))));
            Canvas.SetTop(ERshe, Canvas.GetTop(sheJH2[sheJH2.Count - 1]));
            Canvas.SetLeft(ERshe, Canvas.GetLeft(sheJH2[sheJH2.Count - 1]));
            GM.Children.Add(ERshe);
            sheJH2.Add(ERshe);

            //随机食物的位置
            Canvas.SetLeft(food, sj.Next(rows - 5) * size);
            Canvas.SetTop(food, sj.Next(cols - 5) * size);
        }
        //用if判断当蛇头碰到食物时,新创建一个食物
        /*if (Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(food) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(food))
        {
            GM.Children.Remove(food);
            SJFood();


            Border tianjia = new Border();
            tianjia.Width = food.Height = 20;
            tianjia.Background = Brushes.AliceBlue;
            tianjia.CornerRadius = new CornerRadius(10);
            Canvas.SetLeft(tianjia, 200);
            Canvas.SetLeft(tianjia, 200);
            sheJH.Add(tianjia);
            //GM.Children.Add(tianjia);
        }*/
        //*************************************************************************************************************
        //毒食物消除尾巴//蛇的头的距离等于等于毒食物的left距离//sheJH.Count>0表示清除sheJH的集合,清除后就没有sheJH集合索引就会报错,所以要判断sheJH的集合里面不能没东西,所以sheJH.Count>0,数组包含的元素
        if (sheJH.Count > 0 && Canvas.GetLeft(sheJH[0]) == Canvas.GetLeft(dufood) && Canvas.GetTop(sheJH[0]) == Canvas.GetTop(dufood))
        {
            /*for (int i = 0; i < sheJH.Count; i++)
            {
                GM.Children.Remove(sheJH[sheJH.Count]);
                sheJH.RemoveAt(sheJH.Count);
            }
            for (int i = sheJH.Count - 1; i > 0; i--)
            {
                sheJH.RemoveAt(i);
                GM.Children.Remove(sheJH[i]);
            }*/
            //不用for循环,因为直接可以获取最后一行
            GM.Children.Remove(sheJH[sheJH.Count - 1]);
            sheJH.RemoveAt(sheJH.Count - 1);

            Canvas.SetLeft(dufood, sj.Next(3, rows - 3) * size);
            Canvas.SetTop(dufood, sj.Next(3, cols - 3) * size);
        }
        if (sheJH2.Count > 0 && Canvas.GetLeft(sheJH2[0]) == Canvas.GetLeft(dufood) && Canvas.GetTop(sheJH2[0]) == Canvas.GetTop(dufood))
        {
            /*for (int i = 0; i < sheJH.Count; i++)
            {
                GM.Children.Remove(sheJH[sheJH.Count]);
                sheJH.RemoveAt(sheJH.Count);
            }
            for (int i = sheJH.Count - 1; i > 0; i--)
            {
                sheJH.RemoveAt(i);
                GM.Children.Remove(sheJH[i]);
            }*/
            //不用for循环,因为直接可以获取最后一行
            GM.Children.Remove(sheJH2[sheJH2.Count - 1]);
            sheJH2.RemoveAt(sheJH2.Count - 1);

            Canvas.SetLeft(dufood, sj.Next(3, rows - 3) * size);
            Canvas.SetTop(dufood, sj.Next(3, cols - 3) * size);
        }
        //***********************************************************************************************
        //头碰墙的代码跳出来就不往下执行了
        if (sheJH.Count > 0&&(Canvas.GetLeft(sheJH[0])>= gMborder.Width+20|| Canvas.GetLeft(sheJH[0])<=77|| Canvas.GetTop(sheJH[0]) >= gMborder.Height-20|| Canvas.GetTop(sheJH[0]) <=57))
        {
            MessageBoxResult xuankuang = MessageBox.Show("游戏结束,是否从新开始","结束", MessageBoxButton.YesNo, MessageBoxImage.Question);//MessageBoxImage.Question警示符合‘
            if (xuankuang== MessageBoxResult.Yes)
            {
                moveTimer.Stop();
                sheJH.Clear();
                GM.Children.Clear();
                //3、食物的创建
                SJFood();
                //2、第一条蛇:创建蛇的方法
                CreatSnake(1, 500, 400);
                //3、第一条蛇:创建蛇的方法
                CreatSnake(2, 300, 200);
                //return;
            }
            else
            {
                moveTimer.Stop();
                sheJH.Clear();
                GM.Children.Clear();
                MessageBox.Show("头碰墙,你的游戏结束");
                //return;
            }
            /*
           for (int j = 0; j < sheJH.Count; j++)
           {
               GM.Children.Remove(sheJH[j]);
           }
           moveTimer.Stop();
           sheJH.Clear();
          // GM.Children.Clear();全清除
           MessageBox.Show("头碰墙");//只要弹框出来下面的就不执行了
           //return;*/

        }
        //蛇头碰到墙停止
        if (sheJH2.Count > 0 && (Canvas.GetLeft(sheJH2[0])>= gMborder.Width||Canvas.GetTop(sheJH2[0])>=gMborder.Height||Canvas.GetLeft(sheJH2[0])<= 77 || Canvas.GetTop(sheJH2[0])<=57))
        {
            MessageBoxResult chongqi = MessageBox.Show("是否从新开始","重置", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (chongqi==MessageBoxResult.Yes)
            {
                moveTimer.Stop();
                sheJH.Clear();
                GM.Children.Clear();
                //3、食物的创建
                SJFood();
                //2、第一条蛇:创建蛇的方法
                CreatSnake(1, 500, 400);
                //3、第一条蛇:创建蛇的方法
                CreatSnake(2, 300, 200);
                //return;
            }
            else
            {
                moveTimer.Stop();
                sheJH.Clear();
                GM.Children.Clear();
                MessageBox.Show("头碰墙,你的游戏结束");
                //return;
            }
            /* for (int j = 0; j < sheJH2.Count; j++)
             {
                 GM.Children.Remove(sheJH2[j]);

             }
             moveTimer.Stop();
             sheJH2.Clear();
             MessageBox.Show("撞墙了");
             //return;
             */
        }

        
    }


    //创建一个蛇方法
    private void CreatSnake(int JL,int x,int y)
    {
        for (int i = 0; i < 4; i++)
        {
            //创建蛇
            Border Snake = new Border();
            Snake.Width=Snake.Height= size;
            if (i==0)
            {
                Snake.Background = Brushes.Black;
            }
            else
            {
                Snake.Background = Brushes.DarkBlue;
            }
            Snake.CornerRadius = new CornerRadius(10);
            //Snake.Tag = "Right";
            if (JL==1)
            {
                Snake.Tag = "Right";
               /* Canvas.SetLeft(Snake, x - i * size);
                Canvas.SetTop(Snake, y);*/
                sheJH.Add(Snake);//当参数==1把蛇添加到第二个泛型
            }
            else if(JL == 2)
            {
                Snake.Tag = "D";
               /* Canvas.SetLeft(Snake, x - i * size);
                Canvas.SetTop(Snake, y);*/
                sheJH2.Add(Snake);//当参数==2把蛇添加到第二个泛型
            }
            Canvas.SetLeft(Snake, x - i * size);
            Canvas.SetTop(Snake, y);
            //把创建好的蛇放到游戏界面
            GM.Children.Add(Snake);
            //用一个集合把创建的每个蛇创建出来
            //sheJH.Add(Snake);
        }
        /*Border tianjia;
        tianjia = new Border();
        tianjia.Tag = "tj";
        tianjia.Width = food.Height = size;
        tianjia.BorderBrush = Brushes.Black;
        tianjia.CornerRadius = new CornerRadius(10);
        sheJH.Add(tianjia);*/
    }
}

}

你可能感兴趣的:(WPF版贪吃蛇(案例+代码))