WPF小程序:贪吃蛇
原文地址: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小程序:贪吃蛇的更多相关文章
- JavaScript面向对象编程小游戏---贪吃蛇
1 面向对象编程思想在程序项目中有着非常明显的优势: 1- 1 代码可读性高.由于继承的存在,即使改变需求,那么维护也只是在局部模块 1- 2 维护非常方便并且成本较低. 2 这个demo是采用了 ...
- 第一个windows 小游戏 贪吃蛇
最近用dx尝试做了一个小的贪吃蛇游戏,代码放到github上面:https://github.com/nightwolf-chen/MyFreakout 说一下自己实现的过程: 首先,我把蛇这个抽象成 ...
- 使用JavaScript实现简单的小游戏-贪吃蛇
最近初学JavaScript,在这里分享贪吃蛇小游戏的实现过程, 希望能看到的前辈们能指出这个程序的不足之处. 大致思路 首先要解决的问题 随着蛇头的前进,尾巴也要前进. 用键盘控制蛇的运动方向. 初 ...
- Java_GUI小游戏--贪吃蛇
贪吃蛇游戏:是一条蛇在封闭围墙里,围墙里随机出现一个食物,通过按键盘四个光标键控制蛇向上下左右四个方向移动,蛇头撞倒食物,则食物被吃掉,蛇身体长一节,接着又出现食物,等待蛇来吃,如果蛇在移动中撞到墙或 ...
- Java小游戏贪吃蛇
package snake; import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java ...
- 用Canvas制作小游戏——贪吃蛇
今天呢,主要和小伙伴们分享一下一个贪吃蛇游戏从构思到实现的过程~因为我不是很喜欢直接PO代码,所以只copy代码的童鞋们请出门左转不谢. 按理说canvas与其应用是老生常谈了,可我在准备阶段却搜索不 ...
- JavaScript 小游戏 贪吃蛇
贪吃蛇 代码: <!DOCTYPE html><html><head> <meta charset="UTF-8"> <met ...
- python【控制台】小游戏--贪吃蛇
传统贪吃蛇相信大家都玩过,也是一款很老很经典的游戏,今天我们用python控制台实现 项目有很多bug没有解决,因为本人一时兴起写的一个小游戏,所以只是实现可玩部分功能,并没有花较多的时间和精力去维护 ...
- 手把手教学h5小游戏 - 贪吃蛇
简单的小游戏制作,代码量只有两三百行.游戏可自行扩展延申. 源码已发布至github,喜欢的点个小星星,源码入口:game-snake 游戏已发布,游戏入口:http://snake.game.yan ...
- Win32小游戏--贪吃蛇
近日里学习了关于win32编程的相关知识,利用这些知识制作了一款贪吃蛇小游戏,具体细节还是分模块来叙述 前期准备:在网上找到一些贪吃蛇的游戏素材图片,以及具体的逻辑框图 在正式写功能之前,先把一系列环 ...
随机推荐
- ICSharpCode.SharpZipLib压缩解压
一.使用ICSharpCode.SharpZipLib.dll: 下载地址 http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.asp ...
- 关于PHP定时执行任务的实现(转)
PHP在这方面应该说是比较弱,如果只用php去实现可以如下: <?php ignore_user_abort();//关闭浏览器后,继续执行php代码 set_time_limit(0);//程 ...
- 常用Content-type汇总
Content-Type,内容类型,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式.什么编码读取这个文件.这里汇总一下常用的,所有资料来源于网络,未经测试: 文件后缀 处理方式 .* ...
- Some code changes cannot be hot swapped into a running virtual machine,
翻译一下:不能热交换到运行虚拟机,一些代码变化不能热交换到运行虚拟机,如更改名称或介绍的方法错误运行代码.解决方法:增加.删除类文件或者在一个类中增加.删除方法时,是不能够热部署到服务上的.这时候需要 ...
- js request
比如你要获取aaa.aspx?id=2 使用方法为:var id= request('id');
- RSA签名验签
import android.util.Base64; import java.security.KeyFactory; import java.security.PrivateKey; import ...
- DOM - nodeType 的取值
DOM 中,共有 12 中不同类型的节点,nodeType 的取值以数值表示. 节点类型 描述 子节点 1 Element 表示元素. Element, Text, Comment, Proce ...
- 表达式:使用API创建表达式树(5)
一.ConditionalExpression:表达式 生成如 IIF((a == b), "a和b相等", "a与b不相等") 式子. 使用: Paramet ...
- 硬编码写RadioGroup的时候要注意设置RadioButton的Id
硬编码写RadioGroup的时候要注意RadioButton的id重复问题,导致选择的时候出现能够多选的情况发生,如下代码,注意Id的设置,这样避免Radiobutton的id重复. /** * 生 ...
- Array,ArrayList 和 List<T>的选择和性能比较.
Array Class Provides methods for creating, manipulating, searching, and sorting arrays, thereby serv ...