贪吃蛇案例

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;

namespace tcs
{
public partial class MainWindow : Window
{
DispatcherTimer timer1 = new DispatcherTimer();//设置计时器
Border food = new Border();//实例化border用来存储食物
//创建点击开始暂停按钮
Button btn = new Button();
//创建计分
Button fenshu = new Button();
//创建关闭按钮
Button close = new Button();
//创建障碍物
Image image = new Image();
MediaPlayer beijing = new MediaPlayer();

    public MainWindow()
    {
        InitializeComponent();
        continer.Background = Brushes.Yellow ;//设置外围控制区域的颜色
        continer.Background = new RadialGradientBrush(Colors.White, Colors.Black);//设置游戏区域颜色镜像渐变
        this.WindowStyle = WindowStyle.None;//取消窗口的边框样式
        this.WindowState = WindowState.Maximized;//设置窗口的大小为最大化
        //this.AllowsTransparency = true;//窗体支持透明
        //this.Opacity = 0.5;//不透明度为0.5
        this.KeyDown += MainWindow_KeyDown;//设置键盘点击事件
        timer1.Interval = TimeSpan.FromSeconds(0.05);//设置计时器的间隔
        //timer1.Start();//开启计时器
        timer1.Tick += Timer1_Tick;//添加计时器的事件

    }
    int size = 20;
    int X = 67;
    int Y = 39;
    int x = 0;
    //设置随机数用于设置食物随机的位置
    Random p = new Random();
    //窗体加载事件
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //定义界面的宽高
        continer.Width = this.Width - 200;
        continer.Height = this.Height;
        SetSnake();//调用创建蛇的这个方法
        SetFood();//调用食物这个方法
                  // Setobstalce();//调用障碍物这个方法
        button();//调用按钮这个方法
    }
    private void Close_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
    private void button()
    {
        btn.Background = new RadialGradientBrush(Colors.Azure, Colors.Red);//设置开始暂停控制按钮的背景渐变色
        btn.Content = "开始游戏";//设置按钮的标题
        btn.Width = 100;//设置按钮的宽度
        btn.Height = 50;//设置按钮的高度
        btn.Click += Btn_Click;//添加按钮点击事件
        Canvas.SetTop(btn, 10);
        Canvas.SetLeft(btn, 1400);
        continer.Children.Add(btn);//向容器中增加按钮
        fenshu.Content = "得分:" + x;
        fenshu.Width = 100;
        fenshu.Height = 50;
        fenshu.Background = new RadialGradientBrush(Colors.White, Colors.Tomato);
        Canvas.SetLeft(fenshu, 1400);
        Canvas.SetTop(fenshu, 100);
        continer.Children.Add(fenshu);
        close.Content = "关闭游戏";
        close.Width = 100;
        close.Height = 50;
        close.Background = new RadialGradientBrush(Colors.Red, Colors.Green);
        Canvas.SetLeft(close, 1400);
        Canvas.SetTop(close, 200);
        close.Click += Close_Click;
        continer.Children.Add(close);
    }
    private void Btn_Click(object sender, RoutedEventArgs e)
    {
        beijing.Open(new Uri("../../music/泠鸢yousa - 勾指起誓.mp3", UriKind.Relative));
  
        if (btn.Content.ToString() == "开始游戏")
        {
            timer1.Start();
            beijing.Play();
            btn.Content = "暂停游戏";
            beijing.Position = new TimeSpan();
        }
        else if (btn.Content.ToString() == "暂停游戏")
        {
            //Content.NaturalDuration = new Duration();
            timer1.Stop();
            beijing.Pause();
            btn.Content = "开始游戏";
        }
    }
    List<Border> snake = new List<Border>();//通过索引来访问蛇的数目
    private void MainWindow_KeyDown(object sender, KeyEventArgs e)//键盘的点击事件,蛇移动的方向
    {
        switch (e.Key)//按下的按键
        {
            case Key.Right://为向右的方向键
                snake[0].Tag = "Right";
                break;
            case Key.Left://为向左的方向键
                snake[0].Tag = "Left";
                break;
            case Key.Up://为向上的方向键
                snake[0].Tag = "Up";
                break;
            case Key.Down://为向下的方向键
                snake[0].Tag = "Down";
                break;
        }
    }
    //计时器用于控制蛇的移动
    private void Timer1_Tick(object sender, EventArgs e)
    {
        #region//第一种方案
        for (int i = 0; i < snake.Count; i++)//查找为蛇头的那个border,在wpf中数组长度为count
        {
            if (snake[i].Tag.ToString() == "Left")
            {
                Canvas.SetLeft(snake[i], Canvas.GetLeft(snake[i]) - size);//设置水平移动位置为第几个蛇减去本身的宽度
            }
            else if (snake[i].Tag.ToString() == "Right")
            {
                Canvas.SetLeft(snake[i], Canvas.GetLeft(snake[i]) + size);//设置水平移动位置为第几个蛇加上本身的宽度
            }
            else if (snake[i].Tag.ToString() == "Up")//向上的按键
            {
                Canvas.SetTop(snake[i], Canvas.GetTop(snake[i]) - size);//设置垂直移动位置为第几个蛇减去自身的高度
            }
            else if (snake[i].Tag.ToString() == "Down")//向下的按键
            {
                Canvas.SetTop(snake[i], Canvas.GetTop(snake[i]) + size);// 设置垂直移动位置为第几个蛇加上自身的高度
            }
        }
        for (int i = snake.Count - 1; i > 0; i--)//从最后一个开始进行寻找
        {
            snake[i].Tag = snake[i - 1].Tag;//每次都将下一个的tag赋给前一个
        }
        //判断蛇碰到食物食物的位置进行随机
        if (Canvas.GetLeft(snake[0]) == Canvas.GetLeft(food) && Canvas.GetTop(snake[0]) == Canvas.GetTop(food))//判断蛇的位置与蛇舞的位置是否相同
        {
            //第一种方法
            //重新定义食物的位置
            //Canvas.SetLeft(food,p.Next(X)*size);
            //Canvas.SetTop(food,p.Next(Y)*size);
            //第二种方法
            //删除食物然后重新生成食物也就是重新调用这个方法
            continer.Children.Remove(food);//删除第一次的食物
            continer.Children.Remove(image);//删除第一次创建的障碍物
            Eatmusic();//调用方法,播放吃到食物时的音效
            SetFood();//新创建食物
            Addshe();//吃到食物后蛇身体长度增加
            x++;//分数加一
            fenshu.Content = "得分:" + x;//button的内容分数的更新
        }
        //判断蛇是否撞到了四周边框
        if (Canvas.GetLeft(snake[0]) >= continer.Width || Canvas.GetTop(snake[0]) >= continer.Height || Canvas.GetLeft(snake[0]) + size <= 0 || Canvas.GetTop(snake[0]) + 2 * size <= 0)
        {
            
            
            Game();//引用方法,死亡后的操作
            //用于清空计分
            x = 0;
            fenshu.Content = "得分:" + x;
        }
        //判断蛇是否吃到了自己
        for (int i = 1; i < snake.Count; i++)
        {
            if (Canvas.GetLeft(snake[0]) == Canvas.GetLeft(snake[i]) && Canvas.GetTop(snake[0]) == Canvas.GetTop(snake[i]))
            {
                
                Eatbody();//调用吃到自身的方法
            }
        }
        #endregion
    }
    private void Eatmusic()
    {
        
        MediaPlayer eat = new MediaPlayer();
        eat.Open(new Uri("../../music/吃到食物.mp3", UriKind.Relative));
        eat.Play();
    }
   
    private void Eatbody()
    {
        timer1.Stop();//计时器关闭
        continer.Children.Clear();//清空容器里所有元素
        MessageBoxResult result = MessageBox.Show("自己不能吃自己哦!(是否重新开始?)'", "提示(游戏结束)!", MessageBoxButton.YesNo, MessageBoxImage.Hand);
        if (result == MessageBoxResult.Yes)
        {
            //重新播放音乐
            beijing.Open(new Uri("../../music/泠鸢yousa - 勾指起誓.mp3", UriKind.Relative));
            beijing.Play();
            timer1.Start();//开启计时器
            snake.Clear();//存储蛇清空
            SetSnake();//重新创建蛇
            SetFood();//重新创建食物
        }
        else
        {
            this.Close();
        }
    }
    private void Game()
    {
        timer1.Stop();
      
        {
            this.Close();
        }

    }
    private void SetSnake()
    {
        for (int i = 0; i < 5; i++)//开始创建蛇的长度为5
        {
            Border she = new Border();//实例化border
            she.Width = she.Height = size;//定义宽高
            if (i == 0)//蛇头颜色
            {
                //she.
                she.Background = new RadialGradientBrush(Colors.White, Colors.Orange);
            }
            else//蛇身颜色
            {
                she.Background = new RadialGradientBrush(Colors.SkyBlue, Colors.Purple);
            }
            //设置蛇的位置
            Canvas.SetLeft(she, X / 2 * size - i * size);
            Canvas.SetTop(she, Y / 2 * size);
            she.Tag = "Right";
            she.CornerRadius = new CornerRadius(size / 2);//进行border画圆
            continer.Children.Add(she);//添加控件
            snake.Add(she);//将蛇放进这个数组列表中进行查找
        }
    }
    private void SetFood()
    {

        food.Width = food.Height = size;//设置宽高
        food.CornerRadius = new CornerRadius(size / 2);//画圆操作
                                                       //设置食物位置随机
        Canvas.SetLeft(food, p.Next(X) * size);
        Canvas.SetTop(food, p.Next(Y) * size);
        food.Background = new RadialGradientBrush(Colors.Yellow, Colors.Green);//设置渐变色
        continer.Children.Add(food);//增加食物控件到容器中
                                //Setobstalce();//调用障碍物这个方法
    }
    private void Addshe()
    {
        Border zshe = new Border();
        zshe.Width = zshe.Height = size;//定义宽高
        zshe.Background = new RadialGradientBrush(Colors.Silver, Colors.Red);
        //设置蛇的位置
        Canvas.SetLeft(zshe, Canvas.GetLeft(snake[snake.Count - 1]));//设置在最后一个位置
        Canvas.SetTop(zshe, Canvas.GetTop(snake[snake.Count - 1]));
        zshe.Tag = " ";
        zshe.CornerRadius = new CornerRadius(size / 2);//进行border画圆
        continer.Children.Add(zshe);//添加控件
        snake.Add(zshe);//将蛇放进这个数组列表中进行查找
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值