项目要求:
贪吃蛇游戏 : 控制蛇的移动,要有果实的随机生成 ,蛇可以吃到食物并且在后面加长蛇身 写两条蛇
碰到墙壁 蛇互相碰撞游戏结束
效果图如下:
代码如下:
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="贪吃蛇" Height="450" Width="800" Loaded="Window_Loaded">
<Canvas x:Name="BG">
</Canvas>
</Window>
CS界面:
namespace 贪吃蛇
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
List<Border> snake = new List<Border>();//装sanke1
List<Border> snake1 = new List<Border>();//装snake2
List<Border> slocation = new List<Border>();
double size = 20;//蛇的size
Border bk = new Border();//边框
int rows = 35; int cols = 60;
double left = 0, top=0;
Border food;//食物
Random r = new Random();//食物的随机
Button ks = new Button();//开始按钮
Button cs = new Button();//重新开始按钮
Canvas game = new Canvas();//游戏区域
DispatcherTimer move = new DispatcherTimer();//移动蛇1
DispatcherTimer move1 = new DispatcherTimer();//蛇2
int x = 0;//蛇1分数
Label df1 = new Label();//蛇1计分板
int y = 0;//蛇2分数
Label df2 = new Label();//蛇2计分板
public MainWindow()
{
InitializeComponent();
//this.WindowStyle = WindowStyle.None;//去掉边框
//this.AllowsTransparency = true;//设置透明度改为true
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//this.Background = Brushes.Transparent;//设置透明
//this.WindowState = WindowState.Maximized;//窗口最大化
this.Width = 1500;
this.Height = 800;
this.Left = SystemParameters.FullPrimaryScreenWidth / 2 - this.Width / 2;
this.Top = SystemParameters.FullPrimaryScreenHeight / 2 - this.Height / 2;//居中
//设置背景的大小
BG.Width = 1500;
BG.Height = 800;
BG.Background = Brushes.MediumSeaGreen;
//创建边框
bk.Width = 1200;
bk.Height = 700;
bk.BorderThickness = new Thickness(20);//边框的厚度
bk.BorderBrush = new LinearGradientBrush(Colors.Black, Colors.Orange, 0);
bk.CornerRadius = new CornerRadius(10);
Canvas.SetLeft(bk, 30);
Ca