运行效果如下:
xaml文件代码如下:
<Window x:Class="贪吃蛇.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:贪吃蛇"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Canvas x:Name="BG">
</Canvas>
</Window>
CS代码如下:
实现蛇能够吃食物/毒食物/撞墙/撞自己/声音/加分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace 贪吃蛇
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//去掉边框
this.WindowStyle = WindowStyle.None;
//支持透明度
this.AllowsTransparency = true;
}
//创建蛇
Border br;
//创建泛型把蛇装进去
List<Border> snake = new List<Border>();
//食物和蛇尺寸
double size = 20;
//添加一个边框作为蛇的游戏区域
Border brd = new Border();
//设置行与列
int rows = 30,cols=40;
//随机对象
Random r = new Random();
//创建食物
Border food;
//游戏区
Canvas game = new Canvas();
//设置一个开始按钮
Button startbtn = new Button();
//设置蛇的移动的计时器
DispatcherTimer moveTimer = new DispatcherTimer();
//得分板
Label defen = new Label();
//得分
int count = 0;
//吃到食物声音
MediaPlayer sy = new MediaPlayer();
//开始游戏背景音乐
MediaPlayer bgsound = new MediaPlayer();
//吃到毒食物声音
MediaPlayer dfood1 = new MediaPlayer();
//死亡音效
MediaPlayer die = new MediaPlayer();
//创建毒食物
Border dfood;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//窗口最大化
this.WindowState = WindowState.Maximized;
//设置透明色
this.Background = Brushes.Transparent;
//设置渐显颜色
BG.Background = new RadialGradientBrush(Colors.Yellow,Colors.Blue);
//设置透明度
BG.Opacity = 0.8;
//设置宽
BG.Width = this.Width;
//设置高
BG.Height = this.Height;
//设置蛇的移动的计时器
//DispatcherTimer moveTimer = new DispatcherTimer();
moveTimer.Interval = TimeSpan.FromMilliseconds(300);
moveTimer.Tick += MoveTimer_Tick;
//moveTimer.Start();
//设置蛇能够移动的游戏区域边框
brd.Width = size * cols;
brd.Height = size * rows;
//设置边框厚度
brd.BorderThickness = new Thickness(20);
brd.BorderBrush = new LinearGradientBrush(Colors.Red,Colors.White,0);
brd.CornerRadius = new CornerRadius(10);
Canvas.SetLeft(brd,(BG.Width-brd.Width)/2);
Canvas.SetTop(brd,(BG.Height-brd.Height)/2);
BG.Children.Add(brd);
//游戏区
game.Width