贪吃蛇总结:
1. 创建WPF应用程序
2. 添加Canvas标签。Name=back;
3. 添加loaded事件
4. 在loaded事件中创建蛇(设置蛇的位置,大小,颜色)
this.Left = 0;
this.Top = 0;
this.Width = 800;
this.Height = 600;
for (int i = 0; i < 5; i++)
{
bd = new Border();
bd.Width = bd.Height = 10;
bd.CornerRadius = new CornerRadius(5);
if (i == 0)
bd.Background = Brushes.Red;
else
bd.Background = Brushes.Black;
Canvas.SetTop(bd,200+i*bd.Height);
Canvas.SetLeft(bd,200);
back.Children.Add(bd);
snake.Add(bd);
5. 添加一个timer,(问题:添加timer和winform程序中不一样
Winform 程序中直接添加。
WPF应用程序中不能直接添加,需要引入命名空间:
Using System.Thearing
)
DispatcherTimer tm1 = new DispatcherTimer();
tm1.Interval =TimeSpan.FromMilliseconds(200);
tm1.Tick += Tm1_Tick;
tm1.Start();
this.KeyDown += MainWindow_KeyDown;
6. 添加键盘事件,读取键盘敲下的字符
if (e.Key==Key.Up&&str!="d" )
{
str = "up";
}
if (e.Key==Key.Down&&str!="up")
{
str = "d";
{
str = "l";
}
if (e.Key == Key.Right&&str!="l")
{
str = "r";
}
7.在timer事件中实现蛇的移动(问题:在实现向左移动时出现错误
解决:添加一个集合,来存储蛇的位置信息,与此同时添加一个border