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小程序:贪吃蛇,码迷,mamicode.com

时间: 2024-11-10 10:33:12

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

控制台小游戏-贪吃蛇,c++和c#版

说是c++版,其实只是用到了c++的cout和cin而已.这是我做的第二个控制台游戏,基本上每一行代码都加上了注释. 游戏嘛,我觉得重要的是了解他的思想,所以后期学了面向对象之后这个游戏的代码我也没有重新封装. 下面请看图 代码如下:我是用dev c++写的 1 //注释. ---星辰 2 3 #include <iostream> 4 #include<Windows.h> 5 #include<ctime> 6 #include<cstdlib> 7 #

Pascal小游戏 贪吃蛇

一段未完成的Pascal贪吃蛇 说这段代码未完成其实是没有源代码格式化,FP中一行最多只有255字符宽. uses crt; const screenwidth=50; screenheight=24; wallchar='#'; snakechar='*'; ; type point=record x,y:integer; end; var snake:array [0..500] of point; map:array [0..screenwidth,0..screenheight] of

java小游戏贪吃蛇大作战:来一起回顾童年回忆!

Java小项目之贪吃蛇 跪求关注,祝关注我的人都:身体健康,财源广进,福如东海,寿比南山,早上贵子,从不掉发! 贪吃蛇,绝对是很多朋友的童年记忆.几乎没有人会说没玩过这款小游戏,因为不管在小灵通手机,直板手机,还是半智能手机,甚至是现在的5G手机,都能看见这款游戏的身影.虽然游戏一直在进化,画面,风格,操作方式越来越精细,但是游戏本质的玩法是没变的,例如蛇不断变大,碰到墙壁会死亡等设定.这篇文章来分享java小游戏贪吃蛇:部分代码展示:这个贪吃蛇小游戏,玩法和操控,都是比较完善的,大家感兴趣的可

JS的小游戏&quot;贪吃蛇&quot;

贪吃蛇儿时的回忆,今天刚好学习到这了,就刚好做了一个,也是学习了吧,需要掌握的知识: 1,JS函数的熟练掌握, 2,JS数组的应用, 3,JS小部分AJAX的学习 4,JS中的splice.shift等一些函数的应用, 基本上就这些吧,下面提重点部分: 前端的页面,这里可自行布局,我这边提供一个我自己的布局: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org

小游戏●贪吃蛇1(利用二维数组制作)

利用二维数组编写简单贪吃蛇小游戏,由于是初学C#,用的是单线程,所以蛇不会自动前进 代码及简要分析如下: 1 //定义地图,0为空,1为墙,2为蛇,3为食物 2 int[,] map = new int[15, 15]{ 3 {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 4 {1,2,0,0,0,0,0,0,0,0,0,0,0,0,1}, 5 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, 6 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},

Java小游戏贪吃蛇

package snake; import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java.awt.Container;import java.awt.Graphics;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Arrays;import java.util.Itera

控制台小游戏——贪吃蛇

网上看到的一个贪吃蛇程序,修复了一些bug(如可以直接转反方向,苹果与蛇重叠,撞到自身不会死亡等),下面是源代码. -------------------------------------------------------------------------------------------------- 1 #include<iostream> 2 #include<windows.h> 3 #include<time.h> 4 #include<stdl

unity5 和UGUI的小Demo贪吃蛇

有时间学习Unity5练练手, 一个贪吃蛇小Demo 简单的2D场景, 对象都是Sprite,需要设置前后的显示层级,从蛇头到蛇尾的Order in Layer 的值是1000 递减1,所以显示的效果是具有鳞片的层叠. 蛇的每一节都有一个脚本 SnakePart.cs 记录这节的位置.方向包括计算值. 蛇没吃一个苹果,就会实例化产生一节, 其中新产生的这节上有一个新脚本 NewSnakePart.cs 主要的作用就是初始化把这节添加到蛇的末端包括初始化位置.方向. GameManager.cs

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

简单的小游戏制作,代码量只有两三百行.游戏可自行扩展延申. 源码已发布至github,喜欢的点个小星星,源码入口:game-snake 游戏已发布,游戏入口:http://snake.game.yanjd.top 第一步 - 制作想法 游戏如何实现是首要想的,这里我的想法如下: 利用canvas进行绘制地图(格子装). 利用canvas绘制蛇,就是占用地图格子.让蛇移动,即:更新蛇坐标,重新绘制. 创建四个方向按钮,控制蛇接下来的方向. 随机在地图上绘制出果子,蛇移动时"吃"到果子,增