C# WPF贪吃蛇源码分享,C#贪吃蛇教程分享

分为有毒食物和加分食物,有毒食物吃掉后减对方一个长度,
空格键为加速键,撞墙检测,吃自己检测

代码奉上,不足之处请大佬指正

CS程序代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
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;


namespace 贪吃蛇
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        #region 本项目用到的全局变量
        public MainWindow()
        {
            InitializeComponent();
            // 无边框
            this.WindowStyle = WindowStyle.None;
            // 是否支持透明
            this.AllowsTransparency = true; 
            // 窗体最大化
            this.WindowState = WindowState.Maximized;            
        }
        Canvas Game = new Canvas();     // 游戏区域
        const int row = 30, col = 40;   //划分游戏区域,row 行,col列
        Image food,dufood;        // 食物
        Random ran = new Random();     // 随机数类
        DispatcherTimer SankMOve = new DispatcherTimer(); // 蛇移动计时器
        const double Sk_size = 20;     // 蛇的大小
        List<Image> SnakeList = new List<Image>();   // 装蛇的集合
        Label Score = new Label();
        SoundPlayer foodmic = new SoundPlayer("../../mic/吃食物.wav");
        SoundPlayer over = new SoundPlayer("../../mic/死亡.wav");
        SoundPlayer dufoodmic = new SoundPlayer("../../mic/毒食物.wav");
        SoundPlayer zhuang = new SoundPlayer("../../mic/死亡.wav");
        List<Image> snaksTwolist = new List<Image>();



        #endregion
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
            MessageBox.Show("按下回车键(Enter)键开始游戏,再次按下暂停游戏","友情提示",MessageBoxButton.OK,MessageBoxImage.Information);

            // 透明度
            this.Opacity = 0.8;
            // 渐变
            BG.Background = new LinearGradientBrush(Colors.White, Colors.Aqua,90);
            // 初始化蛇
            Snakes(SnakeList,300);
            Snakes(snaksTwolist, 500);
            BG.Width = this.Width;
            BG.Height = this.Height;
            // 蛇移动计时器
            SankMOve.Interval = new TimeSpan(0,0,0,0,100);
            SankMOve.Tick += SankMOve_Tick;
            this.KeyDown += 键盘控制蛇移动;
            this.KeyUp += 键盘抬起时事件处理;
            Food();
            DuFood();

           


            // 游戏区域
            Game.Width = Sk_size * col;
            Game.Height = Sk_size * row;        
            // Game背景图片的添加
            Image baimg = new Image();
            baimg.Source = new BitmapImage(new Uri("../../img/埃及背景.jpg", UriKind.RelativeOrAbsolute)); 
            ImageBrush backimg = new ImageBrush();
            backimg.ImageSource = baimg.Source;
            Game.Background = backimg;
            Canvas.SetLeft(Game, (BG.Width - Game.Width) / 2);
            Canvas.SetTop(Game, (BG.Height - Game.Height) / 2);
            BG.Children.Add(Game);
            // 得分板
            Image scoreImg = new Image();
            scoreImg.Source = new BitmapImage(new Uri("/img/得分.png", UriKind.RelativeOrAbsolute));
            scoreImg.Stretch = Stretch.Fill;
            scoreImg.Width = 200;
            scoreImg.Height = 100;
            Canvas.SetLeft(scoreImg, 20);
            Canvas.SetTop(scoreImg, 100);
            BG.Children.Add(scoreImg);
            Score.FontSize = 35;
            Canvas.SetLeft(Score, scoreImg.Width/2);
            Canvas.SetTop(Score,130);
            BG.Children.Add(Score);
        }

        private void 键盘抬起时事件处理(object sender, KeyEventArgs e)
        {
            if (e.Key==Key.Space)
            {
                SankMOve.Interval = new TimeSpan(0, 0, 0, 0, 100);
               
            }
        }
        MediaPlayer play = new MediaPlayer();

        // 食物生成方法↓
        private void Food()
        {
            // 创建一颗食物
            food = new Image();
            // 设置食物大小
            food.Width = food.Height = Sk_size;
            int isfood=ran.Next(0,2);
            // 设置食物图片
            if (isfood==0)
            {
            food.Source = new BitmapImage(new Uri("/img/食物"+ran.Next(0,5)+".png", UriKind.RelativeOrAbsolute));
                food.Tag = "食物";
            }
            else
            {
                food.Source = new BitmapImage(new Uri("/img/毒.png", UriKind.RelativeOrAbsolute));
                food.Tag = "毒";
            }
            food.Stretch = Stretch.Fill;
            // 设置食物位置
            Canvas.SetLeft(food,ran.Next(1,40)*Sk_size);
            Canvas.SetTop(food,ran.Next(1,30)*Sk_size);
            Game.Children.Add(food);
        }
        private void DuFood()
        {
            // 创建一颗食物
            dufood = new Image();
            // 设置食物大小
            dufood.Width = food.Height = Sk_size;
            int isfood = ran.Next(0, 5);
            // 设置食物图片
            if (isfood == 0)
            {
                dufood.Source = new BitmapImage(new Uri("/img/毒.png", UriKind.RelativeOrAbsolute));
                dufood.Tag = "毒";
            }
            else
            {
                dufood.Source = new BitmapImage(new Uri("/img/食物" + ran.Next(0, 5) + ".png", UriKind.RelativeOrAbsolute));
                dufood.Tag = "食物";
            }
            dufood.Stretch = Stretch.Fill;
            // 设置食物位置
            Canvas.SetLeft(dufood, ran.Next(1, 40) * Sk_size);
            Canvas.SetTop(dufood, ran.Next(1, 30) * Sk_size);
            Game.Children.Add(dufood);
        }
        int defen = 0;
        private void 键盘控制蛇移动(object sender, KeyEventArgs e)
        {
            #region 按键盘设置蛇头的Tag
            switch (e.Key)
            {
                #region 回车键开始游戏
                case Key.Space:
                    SankMOve.Interval = new TimeSpan(0, 0, 0, 0, 30);
                    break;
                // 控制开始游戏
                case Key.Enter:
                    if (SankMOve.IsEnabled == true)
                    {
                        SankMOve.Stop();
                    }
                    else
                    {
                        SankMOve.Start();
                        play.Open(new Uri(@"../../mic/BG音乐.wav", UriKind.Relative));
                        play.MediaEnded += Play_MediaEnded;
                        play.Play();
                    }
                    break;
                #endregion
                #region 第一条蛇的移动
                case Key.Left:
                    if (SnakeList[0].Tag.ToString()!="Right")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(270,Sk_size/2,Sk_size/2);
                        SnakeList[0].RenderTransform = transform;
                        SnakeList[0].Tag = "Left";
                    }
                    break;
                case Key.Right:
                    if (SnakeList[0].Tag.ToString() != "Left")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(90, Sk_size / 2, Sk_size / 2);
                        SnakeList[0].RenderTransform = transform;
                        SnakeList[0].Tag = "Right";
                    }
                    break; 
                case Key.Up:
                    if (SnakeList[0].Tag.ToString()!="Down")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(-360, Sk_size / 2, Sk_size / 2);
                        SnakeList[0].RenderTransform = transform;
                        SnakeList[0].Tag = "Up";
                    }
                    break;
                case Key.Down:
                    if (SnakeList[0].Tag.ToString() != "Up")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(180, Sk_size / 2, Sk_size / 2);
                        SnakeList[0].RenderTransform = transform;
                        SnakeList[0].Tag = "Down";
                    }
                    break;
                #endregion
                #region 第二条蛇的移动
                case Key.A:
                    if (snaksTwolist[0].Tag.ToString() != "Right")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(270, Sk_size / 2, Sk_size / 2);
                        snaksTwolist[0].RenderTransform = transform;
                        snaksTwolist[0].Tag = "Left";
                    }
                    break;
                case Key.D:
                    if (snaksTwolist[0].Tag.ToString() != "Left")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(90, Sk_size / 2, Sk_size / 2);
                        snaksTwolist[0].RenderTransform = transform;
                        snaksTwolist[0].Tag = "Right";
                    }
                    break;
                case Key.W:
                    if (snaksTwolist[0].Tag.ToString() != "Down")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(-360, Sk_size / 2, Sk_size / 2);
                        snaksTwolist[0].RenderTransform = transform;
                        snaksTwolist[0].Tag = "Up";
                    }
                    break;
                case Key.S:
                    if (SnakeList[0].Tag.ToString() != "Up")
                    {
                        // 旋转蛇头
                        RotateTransform transform = new RotateTransform(180, Sk_size / 2, Sk_size / 2);
                        snaksTwolist[0].RenderTransform = transform;
                        snaksTwolist[0].Tag = "Down";
                    }
                    break;
                #endregion
                default:
                    break;
            }
            #endregion
        }
        // 背景音乐循环播放
        private void Play_MediaEnded(object sender, EventArgs e)
        {
            play.Position = new TimeSpan(0);
        }
        // 蛇移动计时器
        private void SankMOve_Tick(object sender, EventArgs e)
        {
            SnakesMove();
            SnakesTwoMover();

        }
        // 蛇移动事务逻辑↓第一条
        private void SnakesMove()
        {
            // 第一条蛇
            for (int i = 0; i < SnakeList.Count; i++)
            {
                #region 根据Tag值判断蛇的移动方向
                switch (SnakeList[i].Tag.ToString())
                {
                    case "Left":
                        Canvas.SetLeft(SnakeList[i], Canvas.GetLeft(SnakeList[i]) - Sk_size);
                        break;
                    case "Right":
                        Canvas.SetLeft(SnakeList[i], Canvas.GetLeft(SnakeList[i]) + Sk_size);
                        break;
                    case "Up":
                        Canvas.SetTop(SnakeList[i], Canvas.GetTop(SnakeList[i]) - Sk_size);
                        break;
                    case "Down":
                        Canvas.SetTop(SnakeList[i], Canvas.GetTop(SnakeList[i]) + Sk_size);
                        break;
                    default:
                        break;
                }
                #endregion
            }
            // 循环蛇身体,让前一截位置的蛇身体的Tag值,给此时那截位置的蛇身体
            for (int i = SnakeList.Count - 1; i > 0; i--)
            {
                SnakeList[i].Tag = SnakeList[i - 1].Tag;
            }
            Eatfood(SnakeList, snaksTwolist);
            ZhuangQiang(SnakeList);
            #region  For循环判断蛇是否吃到自己
            for (int i = 1; i < SnakeList.Count - 1; i++)
            {
                if (Canvas.GetLeft(SnakeList[0
                    ]) == Canvas.GetLeft(SnakeList[i]) && Canvas.GetTop(SnakeList[0]) == Canvas.GetTop(SnakeList[i]))
                {
                    // 吃到自己后之后做的决定
                    MessageBoxResult result = MessageBox.Show("你吃到自己了,是否继重新开始游戏?", "GAME OVER", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.OK)
                    {
                        SnakeList.Clear();
                        Game.Children.Clear();
                        Snakes(SnakeList, 300);
                        Food();
                    }
                    else
                    {
                        SankMOve.Stop();
                        MessageBox.Show("好吧,你选择了结束游戏,BYBY");
                        this.Close();
                    }
                }
            }
            #endregion
        }
        // 判断是否撞墙
        string name = null;
        private void ZhuangQiang(List<Image> SnakeList)
        {
            if (Canvas.GetLeft(SnakeList[0]) > Game.Width - 20 || Canvas.GetTop(SnakeList[0]) > Game.Height - 20 || Canvas.GetLeft(SnakeList[0]) < 10 || Canvas.GetTop(SnakeList[0]) < 10)
            {
                zhuang.Play();
                
                // 撞墙之后做的决定
                if (SnakeList==snaksTwolist)
                {
                    name = "第二条蛇";
                }
                else
                {
                    name = "第一条蛇";
                }
                string msg = string.Format("【{0}】撞墙了,【{0}】输掉本局游戏,是否重新开始游戏呢?", name);
                MessageBoxResult result = MessageBox.Show(msg, "GAME OVER", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    SnakeList.Clear();
                    snaksTwolist.Clear();
                    Game.Children.Clear();
                    Snakes(SnakeList, 300);
                    Snakes(snaksTwolist, 500);
                    Food();
                    DuFood();
                    defen = 0;
                    Score.Content = defen;
                }
                else
                {
                    SankMOve.Stop();
                    MessageBox.Show("好吧,你选择了结束游戏,BYBY");
                    this.Close();
                }
            }
        }

        // 第二条蛇移动方法
        private void SnakesTwoMover()
        {
            // 第二条蛇↓
            for (int i = 0; i < snaksTwolist.Count; i++)
            {
                #region 根据Tag值判断蛇的移动方向
                switch (snaksTwolist[i].Tag.ToString())
                {
                    case "Left":
                        Canvas.SetLeft(snaksTwolist[i], Canvas.GetLeft(snaksTwolist[i]) - Sk_size);
                        break;
                    case "Right":
                        Canvas.SetLeft(snaksTwolist[i], Canvas.GetLeft(snaksTwolist[i]) + Sk_size);
                        break;
                    case "Up":
                        Canvas.SetTop(snaksTwolist[i], Canvas.GetTop(snaksTwolist[i]) - Sk_size);
                        break;
                    case "Down":
                        Canvas.SetTop(snaksTwolist[i], Canvas.GetTop(snaksTwolist[i]) + Sk_size);
                        break;
                    default:
                        break;
                }
                #endregion
            }
            // 循环蛇身体,让前一截位置的蛇身体的Tag值,给此时那截位置的蛇身体
            for (int i = snaksTwolist.Count - 1; i > 0; i--)
            {
                snaksTwolist[i].Tag = snaksTwolist[i - 1].Tag;
            }
            Eatfood(snaksTwolist,SnakeList);
            ZhuangQiang(snaksTwolist);
        }
        // 吃食物方法
        private void Eatfood(List<Image> SnakeList,List<Image> SnakeListTwo)
        {
            if (Canvas.GetLeft(SnakeList[0]) == Canvas.GetLeft(food) && Canvas.GetTop(SnakeList[0]) == Canvas.GetTop(food))
            {
                if (food.Tag.ToString() == "毒")
                {
                    dufoodmic.Play();

                    defen--;
                    if (SnakeListTwo.Count!=0)
                    {
                        Score.Content = defen;
                        Game.Children.Remove(SnakeListTwo[SnakeListTwo.Count - 1]);
                        SnakeListTwo.Remove(SnakeListTwo[SnakeListTwo.Count - 1]);
                        Game.Children.Remove(food);
                        Food();
                    }
                    else
                    {
                        string msg = string.Format("【{0}】被对方干掉,【{0}】输掉本局游戏,是否重新开始游戏呢?", name);
                        MessageBoxResult result = MessageBox.Show(msg, "GAME OVER", MessageBoxButton.OKCancel);
                        if (result == MessageBoxResult.OK)
                        {
                            SnakeList.Clear();
                            snaksTwolist.Clear();
                            Game.Children.Clear();
                            Snakes(SnakeList, 300);
                            Snakes(snaksTwolist, 500);
                            Food();
                            DuFood();
                            defen = 0;
                            Score.Content = defen;
                        }
                        else
                        {
                            SankMOve.Stop();
                            MessageBox.Show("好吧,你选择了结束游戏,BYBY");
                            this.Close();
                        }
                    }

                }
                else
                {
                    foodmic.Play();
                    defen++;
                    Score.Content = defen;
                    Game.Children.Remove(food);
                    // 新建一节身体添加到后面
                    Image sks = new Image();
                    sks.Tag = " ";
                    sks.Width = sks.Height = Sk_size;
                    // 新身体的那节的left就跟着蛇集合最后的那节身体的11left
                    sks.Source = new BitmapImage(new Uri("/img/食物4.png", UriKind.RelativeOrAbsolute));
                    sks.Stretch = Stretch.Fill;
                    Canvas.SetLeft(sks, Canvas.GetLeft(SnakeList[SnakeList.Count - 1]));
                    Canvas.SetTop(sks, Canvas.GetTop(SnakeList[SnakeList.Count - 1]));
                    SnakeList.Add(sks);
                    Game.Children.Add(sks);
                    Food();
                }
            }
            if (Canvas.GetLeft(SnakeList[0]) == Canvas.GetLeft(dufood) && Canvas.GetTop(SnakeList[0]) == Canvas.GetTop(dufood))
            {
                if (dufood.Tag.ToString() == "毒")
                {
                    dufoodmic.Play();
                    defen--;
                    Score.Content = defen;
                    Game.Children.Remove(SnakeList[SnakeList.Count - 1]);
                    SnakeList.Remove(SnakeList[SnakeList.Count - 1]);
                    Game.Children.Remove(dufood);
                    DuFood();

                }
                else
                {
                    foodmic.Play();
                    defen++;
                    Score.Content = defen;
                    Game.Children.Remove(dufood);
                    // 新建一节身体添加到后面
                    Image sks = new Image();
                    sks.Tag = " ";
                    sks.Width = sks.Height = Sk_size;
                    // 新身体的那节的left就跟着蛇集合最后的那节身体的11left
                    sks.Source = new BitmapImage(new Uri("/img/食物4.png", UriKind.RelativeOrAbsolute));
                    sks.Stretch = Stretch.Fill;
                    Canvas.SetLeft(sks, Canvas.GetLeft(SnakeList[SnakeList.Count - 1]));
                    Canvas.SetTop(sks, Canvas.GetTop(SnakeList[SnakeList.Count - 1]));
                    SnakeList.Add(sks);
                    Game.Children.Add(sks);
                    DuFood();
                }
            }
        }

        // 初始化蛇方法↓
        private void Snakes(List<Image> SnakeList,int Top)
        {
            #region 循环初始化蛇
            for (int i = 0; i < 4; i++)
            {
                Image sks = new Image();
                Canvas.SetLeft(sks,500-Sk_size*i);
                Canvas.SetTop(sks,Top);
                sks.Width = sks.Height = Sk_size;
                if (i==0)
                {
                    sks.Source = new BitmapImage(new Uri("/img/头.png", UriKind.RelativeOrAbsolute));
                        sks.Stretch = Stretch.Fill;
                }
                else
                {
                    sks.Source = new BitmapImage(new Uri("/img/食物4.png", UriKind.RelativeOrAbsolute));
                    sks.Stretch = Stretch.Fill;
                }
                sks.Tag = "Right";
                Game.Children.Add(sks);
                SnakeList.Add(sks);
            }
            #endregion
        }
      
    }
}

xaml程序代码

<Window x:Class="贪吃蛇.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:贪吃蛇"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded" >
    <Canvas x:Name="BG">
       
    </Canvas>
</Window>

你可能感兴趣的:(WPF动画编程)