原文地址: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. 【Android - V】之ViewPager的使用

    ViewPager是Android V4包中的一个控件,常常用来作为首页的滚动广告,也常常结合Fragment来实现页面的切换效果. ViewPager和ListView有很多相似的地方,都是适配器控 ...

  2. asp.net 动态添加多附件上传.

    最近有人问起动态多文件上传,想要做到类似于邮箱添加附件的效果,这个功能其实比较简单,就是往form中添加file元素.在用户选择完文件后,再添加一个file控件,由于file控件过多,视觉上不好看,所 ...

  3. boost------asio库的使用1(Boost程序库完全开发指南)读书笔记

    asio库基于操作系统提供的异步机制,采用前摄器设计模式(Proactor)实现了可移植的异步(或者同步)IO操作,而且并不要求多线程和锁定,有效地避免了多线程编程带来的诸多有害副作用. 目前asio ...

  4. java数组使用技巧

    参考网上文章,总结了一下java数组使用技巧,如下: package com.beijing.array; import java.nio.ByteBuffer; import java.util.A ...

  5. 动态设置布局LayoutInflater

    LayoutInflater作用是将layout的xml布局文件实例化为View类对象.LayoutInflater 的作用类似于 findViewById(),不同点是LayoutInflater是 ...

  6. win主机用web.config和httpd.ini实现301重定向

    当你准备好好看这篇文章的时候,你应该已经知道了301重定向的作用与意义了,那么这里就不多加解释了. 那么我唯一想提的就是关于域名带与不带www的区别,并且301重定在其中的意义,详情:域名带与不带ww ...

  7. myeclipse配置svn亲测

    1.安装目录更改为myeclipse install 目录:E:\MyEclipse85\MyEclipse 8.5common 目录:           E:\MyEclipse85\Common ...

  8. iOS 使用Charts框架 折线,柱状,K线,饼状,雷达全攻略

    我是前言: 大约几个月前我在某平台写了一篇文章, 文中简单地介绍了Charts两种图表的样式的使用, 不过有种意犹未尽的感觉, 利用周末的空闲时间再次看了看, 有了新的收获, 今天发出来,分享给大家, ...

  9. Android(java)学习笔记213:开源框架post和get方式提交数据(qq登录案例)

    1.前面提到Http的get/post方式  . HttpClient方式,实际工作的时候不常用到,因为这些方式编写代码是很麻烦的 2.Android应用会经常使用http协议进行传输,网上会有很完善 ...

  10. maven占位符

    maven占位符默认是${} 也可以自己指定. pom.xml配置如下: <plugin> <groupId>org.apache.maven.plugins</grou ...