原文地址:http://hankjin.blog.163.com/blog/static/337319372009535108234/

一共两个文件:EasterEgg.xaml + EasterEgg.xaml.cs

EasterEgg.xaml
<Window
x:Class="Inspect.UI.EasterEgg"
   
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Easter Egg"
Loaded="Window_Loaded" Width="650" Height="450"
       
KeyDown="Window_KeyDown" SizeChanged="Window_SizeChanged"
       
WindowStartupLocation="CenterScreen">
    <Grid>
       
<Grid.RowDefinitions>
            <RowDefinition
Height="40"/>
            <RowDefinition/>
       
</Grid.RowDefinitions>
        <StackPanel Grid.Row="0"
Orientation="Horizontal">
            <Label
FontSize="20">等级:</Label>
            <Label FontSize="20"
Name="lblGrade" Width="50" Content="{Binding
Path=Grade}"></Label>
            <Label
FontSize="20">分数:</Label>
            <Label FontSize="20"
Name="lblScore" Width="90" Content="{Binding
Path=Score}"></Label>
            <Label FontSize="20">说明:
上下左右键调整方向,空格键暂停</Label>
        </StackPanel>       
       
<Border Grid.Row="1" BorderThickness="5" BorderBrush="Red"
Name="border">
            <Canvas Name="cavas"
Background="#CBE9CE"></Canvas>
        </Border>
   
</Grid>
</Window>

EasterEgg.xaml.cs
using
System;
using System.Collections.Generic;
using System.Linq;
using
System.Text;
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.Shapes;
using
System.Timers;
using System.Windows.Threading;

namespace
Inspect.UI
{
    /// <summary>
    /// Interaction logic for
EasterEgg.xaml
    /// </summary>
    public partial class EasterEgg
: Window
    {
        enum Direction { UP, DOWN, LEFT, RIGHT
};
        private Brush oldBrush = new SolidColorBrush(Color.FromArgb(100,
0, 255, 0));//brush for snake
        private Brush newBrush = new
SolidColorBrush(Color.FromArgb(100, 255, 0, 0));//brush for
destination
        private Direction direct;//current
direction

private DispatcherTimer timer = new
DispatcherTimer();

private List<Rectangle> snake = new
List<Rectangle>();
        private int snakeTail;
        private
Rectangle dest;
        private double destTop, destLeft;
        private
double W, H;

private int speed;
        public static readonly
DependencyProperty GradeProperty = DependencyProperty.Register("Grade",
typeof(int), typeof(EasterEgg));
        public static readonly
DependencyProperty ScoreProperty = DependencyProperty.Register("Score",
typeof(int), typeof(EasterEgg));
        public int Grade
       
{
            get { return Convert.ToInt32(GetValue(GradeProperty));
}
            set { SetValue(GradeProperty, value); }
        }
       
public int Score
        {
            get { return
Convert.ToInt32(GetValue(ScoreProperty)); }
            set {
SetValue(ScoreProperty, value); }   
        }

public
EasterEgg()
        {
            InitializeComponent();
           
this.DataContext = this;//数据绑定
        }
        private void
Window_Loaded(object sender, RoutedEventArgs e)
        {
           
this.InitSnake();

//start timer
            timer.Tick +=
new EventHandler(timer_Elapsed);
            timer.Start();
       
}

/// <summary>
        /// 时钟相应
        ///
</summary>
        /// <param
name="sender"></param>
        /// <param
name="e"></param>
        private void timer_Elapsed(object sender,
EventArgs e)
        {
            Walk();
        }
        private
void Walk()
        {
            //尾变头
            Rectangle tail =
snake[snakeTail];
            Rectangle head = snake[(snakeTail + snake.Count
- 1) % snake.Count];
            double top =
Convert.ToDouble(head.GetValue(Canvas.TopProperty));
            double left
= Convert.ToDouble(head.GetValue(Canvas.LeftProperty));
            switch
(direct)
            {
                case
Direction.LEFT:
                    left -= 10;
                   
break;
                case Direction.RIGHT:
                    left +=
10;
                    break;
                case
Direction.UP:
                    top -= 10;
                   
break;
                case Direction.DOWN:
                    top +=
10;
                    break;
            }          
           
//判断是否吃到目标
            if (top != destTop || left !=
destLeft)//如果没有吃到目标
            {
               
tail.SetValue(Canvas.TopProperty, top);
               
tail.SetValue(Canvas.LeftProperty, left);
            }
            else

{
                //snake变长
                dest.Fill =
oldBrush;//目标变色,成为snake的一部分
               
this.snake.Insert(snakeTail,dest);
                //分数增加
               
this.Score = this.Score + 100;
                if (this.Score % 2000 ==
0)//过关
                {
                    this.Grade = this.Grade +
1;
                    this.timer.Interval = new TimeSpan(0, 0, 0, 0, speed -
20 * Grade);
                }
                //产生新目标
               
Rand();
            }

//判断是否失败
            if (top <
0 || left < 0 || top > this.H - 10.0 || left > this.W -
10.0)//如果跑出边界
            {
                GameOver();
           
}
            else//判断是否咬到自己
            {
                for (int i =
0; i < snake.Count; i++)
                {
                    if (i ==
snakeTail)
                        continue;
                    if
((double)snake[i].GetValue(Canvas.TopProperty) == top &&
(double)snake[i].GetValue(Canvas.LeftProperty) ==
left)
                        GameOver();
               
}
            }
            snakeTail = (snakeTail + 1) %
snake.Count;
        }
        /// <summary>
        ///
违反规则,GameOver
        /// </summary>
        private void
GameOver()
        {
            this.timer.Stop();
            if
(MessageBox.Show("再来一盘?", "游戏结束", MessageBoxButton.YesNo) ==
MessageBoxResult.Yes)
            {
               
this.InitSnake();
                this.timer.Start();
           
}
            else
            {
               
this.Close();
            }
        }
        ///
<summary>
        /// 产生一个随机的目标
        ///
</summary>
        private void Rand()
        {
            dest
= Rect(newBrush);
            this.cavas.Children.Add(dest);
           
Random rand = new Random(System.DateTime.Now.Millisecond);
           
destTop = rand.Next(Convert.ToInt32(this.H)/10) * 10.0;
            destLeft
= rand.Next(Convert.ToInt32(this.W)/10) * 10.0;
           
dest.SetValue(Canvas.TopProperty, destTop);
           
dest.SetValue(Canvas.LeftProperty, destLeft);
        }
        Rectangle
Rect(Brush brush)
        {
            Rectangle rect = new
Rectangle();
            rect.Height = 10;
            rect.Width =
10;
            rect.Fill = brush;
            return rect;
       
}
        /// <summary>
        /// 初始化Snake
        ///
</summary>
        private void InitSnake()
        {
           
this.snake.Clear();
           
this.cavas.Children.Clear();

//init
destination
            Rand();

//init
snake
            Rectangle beginer = Rect(oldBrush);//the first part of
snake
            this.cavas.Children.Add(beginer);
           
this.snake.Add(beginer);
            beginer.SetValue(Canvas.TopProperty,
0.0);
            beginer.SetValue(Canvas.LeftProperty, 0.0);
           
this.direct = Direction.RIGHT;//initial direction
            this.snakeTail
= 0;

this.Score = 0;
            this.Grade =
1;
            this.speed = 200;
            this.timer.Interval = new
TimeSpan(0, 0, 0, 0, speed);
        }
        ///
<summary>
        /// 相应上下左右控制键, 空格暂停
        ///
</summary>
        /// <param
name="sender"></param>
        /// <param
name="e"></param>
        private void Window_KeyDown(object sender,
KeyEventArgs e)
        {
            if (e.Key ==
Key.Right)//→
                direct = (direct != Direction.LEFT ?
Direction.RIGHT : direct);
            else if (e.Key ==
Key.Left)//←
                direct = (direct != Direction.RIGHT ?
Direction.LEFT : direct);
            else if (e.Key ==
Key.Up)//↑
                direct = (direct != Direction.DOWN ? Direction.UP
: direct);
            else if (e.Key == Key.Down)//↓
               
direct = (direct != Direction.UP ? Direction.DOWN : direct);
            else
if(e.Key == Key.Space && timer.IsEnabled)//空格键暂停
           
{
                timer.Stop();
                return;
           
}
           
            if(!timer.IsEnabled)//任意键继续
               
timer.Start();
            else
                Walk();
       
}
        /// <summary>
        /// 窗口的大小改变时,改变两个边界变量W H
       
/// </summary>
        /// <param
name="sender"></param>
        /// <param
name="e"></param>
        private void Window_SizeChanged(object
sender, SizeChangedEventArgs e)
        {
            this.W =
Convert.ToInt32(this.cavas.ActualWidth) / 10 * 10.0;
            this.H =
Convert.ToInt32(this.cavas.ActualHeight) / 10 * 10.0;
        }
   
}
}

WPF小程序:贪吃蛇的更多相关文章

  1. JavaScript面向对象编程小游戏---贪吃蛇

    1 面向对象编程思想在程序项目中有着非常明显的优势: 1- 1 代码可读性高.由于继承的存在,即使改变需求,那么维护也只是在局部模块 1- 2 维护非常方便并且成本较低. ​ 2 这个demo是采用了 ...

  2. 第一个windows 小游戏 贪吃蛇

    最近用dx尝试做了一个小的贪吃蛇游戏,代码放到github上面:https://github.com/nightwolf-chen/MyFreakout 说一下自己实现的过程: 首先,我把蛇这个抽象成 ...

  3. 使用JavaScript实现简单的小游戏-贪吃蛇

    最近初学JavaScript,在这里分享贪吃蛇小游戏的实现过程, 希望能看到的前辈们能指出这个程序的不足之处. 大致思路 首先要解决的问题 随着蛇头的前进,尾巴也要前进. 用键盘控制蛇的运动方向. 初 ...

  4. Java_GUI小游戏--贪吃蛇

    贪吃蛇游戏:是一条蛇在封闭围墙里,围墙里随机出现一个食物,通过按键盘四个光标键控制蛇向上下左右四个方向移动,蛇头撞倒食物,则食物被吃掉,蛇身体长一节,接着又出现食物,等待蛇来吃,如果蛇在移动中撞到墙或 ...

  5. Java小游戏贪吃蛇

    package snake; import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java ...

  6. 用Canvas制作小游戏——贪吃蛇

    今天呢,主要和小伙伴们分享一下一个贪吃蛇游戏从构思到实现的过程~因为我不是很喜欢直接PO代码,所以只copy代码的童鞋们请出门左转不谢. 按理说canvas与其应用是老生常谈了,可我在准备阶段却搜索不 ...

  7. JavaScript 小游戏 贪吃蛇

    贪吃蛇 代码: <!DOCTYPE html><html><head> <meta charset="UTF-8"> <met ...

  8. python【控制台】小游戏--贪吃蛇

    传统贪吃蛇相信大家都玩过,也是一款很老很经典的游戏,今天我们用python控制台实现 项目有很多bug没有解决,因为本人一时兴起写的一个小游戏,所以只是实现可玩部分功能,并没有花较多的时间和精力去维护 ...

  9. 手把手教学h5小游戏 - 贪吃蛇

    简单的小游戏制作,代码量只有两三百行.游戏可自行扩展延申. 源码已发布至github,喜欢的点个小星星,源码入口:game-snake 游戏已发布,游戏入口:http://snake.game.yan ...

  10. Win32小游戏--贪吃蛇

    近日里学习了关于win32编程的相关知识,利用这些知识制作了一款贪吃蛇小游戏,具体细节还是分模块来叙述 前期准备:在网上找到一些贪吃蛇的游戏素材图片,以及具体的逻辑框图 在正式写功能之前,先把一系列环 ...

随机推荐

  1. (使用步骤)ThinkPHP3.1.2中如何配置Ckeditor_4.1.1和Ckfindtor(转)

    ThinkPHP3.1.2中如何配置Ckeditor_4.1.1和Ckfindtor  一.下载Ckeditor和Ckfinder Ckeditor官网 http://ckeditor.com/dow ...

  2. jquery 手机 图片切换 例子 网址

    http://m.swdhy.com/page/ShowCompany.aspx?cid=388481&name=山东潍坊金城服装有限公司

  3. dispatch_get_current_queue 废弃

    由于iOS7以后 dispatch_get_current_queue 被废弃,所以需要寻找一个替代的方案. 发现 dispatch_get_current_queue 并没有字面上那么简单. 这个函 ...

  4. Delphi 颜色转换

    http://files.cnblogs.com/xe2011/StringToColor.rar unit Unit1; interface uses Windows, Messages, SysU ...

  5. [Reactive Programming] RxJS dynamic behavior

    This lesson helps you think in Reactive programming by explaining why it is a beneficial paradigm fo ...

  6. XZ压缩

    XZ压缩最新压缩率之王 xz这个压缩可能很多都很陌生,不过您可知道xz是绝大数linux默认就带的一个压缩工具. 之前xz使用一直很少,所以几乎没有什么提起. 我是在下载phpmyadmin的时候看到 ...

  7. FastJson解析对象及对象数组--项目经验

    第一次使用json,解析工具为FastJson,使用语言为java 常见的json解析实例,以map为例: Map<String,String> map=new HashMap<St ...

  8. 2 - SQL Server 2008 之 使用SQL语句为现有表添加约束条件

    上一节讲的是直接在创建表的时候添加条件约束,但是有时候是在表格创建完毕之后,再添加条件约束的,那么这个又该如何实现? 其实,跟上一节所写的SQL代码,很多是相同的,只是使用了修改表的ALTER关键字及 ...

  9. AndroidManifest.xml中的application中的name属性 分类: android 学习笔记 2015-07-17 16:51 116人阅读 评论(0) 收藏

    被这个不起眼的属性折磨了一天,终于解决了. 由于项目需要,要合并两个android应用,于是拷代码,拷布局文件,拷values,所有的都搞定之后程序还是频频崩溃,一直没有找到原因,学android时间 ...

  10. weex APIs

    1.通过这个$vm()上下文访问这些api在脚本的方法 <script> module.exports = { methods: { somemethod: function() { th ...