c#贪吃蛇小游戏Wpf
程序员文章站
2022-07-02 18:15:59
...
.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 WPF贪吃蛇
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.WindowState = WindowState.Maximized;
this.WindowStyle = WindowStyle.None;//支持透明度 要清除边框
this.AllowsTransparency = true;//支持透明度
/* SoundPlayer yinyue = new SoundPlayer("");*///音乐
TextBox newTextbox = new TextBox();
}
Label Scoring = new Label();//计分的Label
Label Countdownlabel = new Label();//倒数计时板
Label Scoring1 = new Label();//蛇二的计分板
DispatcherTimer Countdown = new DispatcherTimer();//倒数计时Timer
//加载完成
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//开关的位置
Canvas.SetLeft(bg,(this.Width-bg.Width)/2);
Canvas.SetTop(bg,(this.Height-bg.Height)/2-100);
bg.Background = Brushes.White;
//窗体的位置
this.Left = SystemParameters.WorkArea.Width / 2 - this.Width / 2;
this.Top = SystemParameters.WorkArea.Height / 2 - this.Height / 2;
//游戏区的背景
BG.Width = this.Width;
BG.Height = this.Height;
BG.Background = Brushes.Gray;
BG.Opacity = 1;
//游戏边框
rim.Width = size * cols-20;
rim.Height = size * rows-20;
rim.BorderThickness = new Thickness(20);//宽度
rim.BorderBrush = new LinearGradientBrush(Colors.White,Colors.Black,0);
rim.CornerRadius = new CornerRadius(10);//设置其边框的宽度
Canvas.SetLeft(rim,(BG.Width-rim.Width)/2);
Canvas.SetTop(rim,(BG.Height-rim.Height)/2);
BG.Children.Add(rim);
left = Canvas.GetLeft(rim) + 20;//方便算后面蛇的位置 和生成实物的位置
top = Canvas.GetTop(rim) + 20;//20指的是边框的宽度
//第一条蛇计分板
//Label Scoring = new Label();
Scoring.Width = 100;
Scoring.Height = 50;
Scoring.Content = "最后得分:"+0;
//第二条蛇的计分板
Scoring1.Width = 100;
Scoring1.Height = 50;
Scoring1.Content = "最后得分" + 0;
//倒数计时
//DispatcherTimer Countdown = new DispatcherTimer();//倒数计时Timer
Countdown.Interval = TimeSpan.FromSeconds(1);
Countdown.Tick += Countdown_Tick;
//移动蛇
MoveTimer.Interval = TimeSpan.FromMilliseconds(100);
MoveTimer.Tick += MoveTimer_Tick;
//按键
this.KeyDown += MainWindow_KeyDown;
}
//计时变量
int y = 6;
//倒数计时
private void Countdown_Tick(object sender, EventArgs e)
{
y--;
Countdownlabel.Content = y;//将计时变量赋值给Label
Countdownlabel.Width = 200;
Countdownlabel.Height = 200;
Countdownlabel.FontSize = 100;//大小为100
Canvas.SetLeft(Countdownlabel,(BG.Width-Countdownlabel.Width)/2);
Canvas.SetTop(Countdownlabel,(BG.Height-Countdownlabel.Height)/2);
if (y==0)
{
CreateSnake();//生成蛇
CreateSnake2();//生成蛇2
CreateDouDou();//升成食物
MoveTimer.Start();//因为创建蛇是在单击之后所以Timer需要在单击之后开启这样才能在snakes泛型中检索到数据 不然Timer加载时检索不出东西 所以为空集合
BG.Children.Remove(Countdownlabel);
}
}
DispatcherTimer MoveTimer = new DispatcherTimer();//移动的 Timer
List<Border> snakes = new List<Border>();//装蛇的泛型
List<Border> snake = new List<Border>();//装第二条蛇的泛型
Border rim = new Border();//边框
double size = 20;
double left = 0, top = 0;
int cols = 90, rows = 50;//列 和 行
Random rd = new Random();//随机数
//生成蛇1
private void CreateSnake()
{
int length = 6;
for (int i = 0; i < length; i++)
{
Border br = new Border();//生成蛇的身体
br.Width = size;
br.Height = size;
br.Tag = "Right";
if (i==0)
{
br.Background = Brushes.Black;
}
else if (i==2)
{
br.Background = Brushes.White;
br.Opacity = 0.5;
}
else if (i==4)
{
br.Background = Brushes.Yellow;
br.Opacity = 0;
}
else
{
br.Background = Brushes.Red;
}
Canvas.SetLeft(br,(BG.Width-br.Width)/2-i*size);//算的是最大的Left
Canvas.SetTop(br,(BG.Height-br.Height)/2);//算的是最大的Top
br.CornerRadius = new CornerRadius(10);
BG.Children.Add(br);
snakes.Add(br);
}
}
//生成蛇2
private void CreateSnake2()
{
int lengths = 6;
for (int i = 0; i < lengths; i++)
{
Border br1 = new Border();//生成蛇的身体
br1.Width = size;
br1.Height = size;
br1.Tag = "D";
if (i == 0)
{
br1.Background = Brushes.Yellow;
}
else if (i == 2)
{
br1.Background = Brushes.Red;
br1.Opacity = 0.5;
}
else if (i == 4)
{
br1.Background = Brushes.Yellow;
br1.Opacity = 0;
}
else
{
br1.Background = Brushes.Pink;
}
Canvas.SetLeft(br1, (BG.Width - br1.Width-240) / 2 - i * size);//算的是最大的Left
Canvas.SetTop(br1, (BG.Height - br1.Height)/2 );//算的是最大的Top
br1.CornerRadius = new CornerRadius(10);
BG.Children.Add(br1);
snake.Add(br1);
}
}
//单击事件 关闭bg开启BG 开始按钮
private void Button_Click(object sender, RoutedEventArgs e)
{
//CreateSnake();//生成蛇
//CreateDouDou();//升成食物
//点击则清除bg
BG.Children.Remove(start);
BG.Children.Remove(bg);
//单击后则让窗体最大设置透明度
this.Background = Brushes.Green;
this.Opacity = 50;
BG.Children.Add(Countdownlabel);
//MoveTimer.Start();//因为创建蛇是在单击之后所以Timer需要在单击之后开启这样才能在snakes泛型中检索到数据 不然Timer加载时检索不出东西 所以为空集合
Countdown.Start();
}
//生成全局的food
Border food;
//记录蛇1分数的变量
int x = 0;
//记录蛇2分数的变量
int z = 0;
//食物
private void CreateDouDou()
{
food = new Border();//创建豆豆食物
food.Width = food.Height = size;
food.Background = new RadialGradientBrush(Colors.Yellow,Colors.Violet);//设置其豆豆的颜色
food.CornerRadius = new CornerRadius(10);//让豆豆变得圆滑
Canvas.SetLeft(food,rd.Next(10,cols)*size+left);//Left跟列有关
Canvas.SetTop(food,rd.Next(10,rows)*size+top);//Top跟行有关
//Canvas.SetLeft(food,rd.Next((int)left,((int)(rim.Width-left-20))));//food 的生成left范围
//Canvas.SetTop(food,rd.Next((int)top,((int)(rim.Height-top-20))));
BG.Children.Add(food);
}
//蛇移动事件
private void MoveTimer_Tick(object sender, EventArgs e)
{
//第一条蛇的控制
for (int i = 0; i < snakes.Count; i++)
{
if (snakes[i].Tag.ToString()=="Right")
{
Canvas.SetLeft(snakes[i],Canvas.GetLeft(snakes[i])+size);
}
else if (snakes[i].Tag.ToString()=="Left")
{
Canvas.SetLeft(snakes[i],Canvas.GetLeft(snakes[i])-size);
}
else if (snakes[i].Tag.ToString()=="Up")
{
Canvas.SetTop(snakes[i], Canvas.GetTop(snakes[i]) - size);
}
else if (snakes[i].Tag.ToString()=="Down")
{
Canvas.SetTop(snakes[i],Canvas.GetTop(snakes[i])+size);
}
}
//第二条设的控制移动
for (int i = 0; i < snake.Count; i++)
{
if (snake[i].Tag.ToString()=="D")
{
Canvas.SetLeft(snake[i],Canvas.GetLeft(snake[i])+size);
}
if (snake[i].Tag.ToString()=="A")
{
Canvas.SetLeft(snake[i],Canvas.GetLeft(snake[i])-size);
}
if (snake[i].Tag.ToString()=="W")
{
Canvas.SetTop(snake[i],Canvas.GetTop(snake[i])-size);
}
if (snake[i].Tag.ToString()=="S")
{
Canvas.SetTop(snake[i],Canvas.GetTop(snake[i])+size);
}
}
//让第一条蛇移动跟随
for (int i = snakes.Count-1; i >0 ; i--)
{
snakes[i].Tag = snakes[i - 1].Tag;//从最后一个开始让一个跟一个 从而去判断移动的tag 以头为主
//判断头部与身体重合
if (Canvas.GetLeft(snakes[0]) == Canvas.GetLeft(snakes[i]) && Canvas.GetTop(snakes[0]) == Canvas.GetTop(snakes[i]))
{
Scoring.Content = "小黑你把自己吃了";
// MessageBox.Show(Scoring.Content.ToString());
MessageBox.Show("请重新开始游戏"+ Scoring.Content.ToString());
// snakes.Clear();
}
}
//第二条蛇 跟随移动和与身体碰撞
for (int i = snake.Count-1; i >0 ; i--)
{
snake[i].Tag = snake[i - 1].Tag;
if (Canvas.GetLeft(snake[0]) == Canvas.GetLeft(snake[i]) && Canvas.GetTop(snake[0]) == Canvas.GetTop(snake[i]))
{
Scoring1.Content = "小黄你把自己吃了";
MessageBox.Show("请重新开始游戏");
MessageBox.Show(Scoring1.Content.ToString());
MoveTimer.Stop();
// snakes.Clear();
}
}
// 蛇与蛇碰撞
for (int i = 0; i < snakes.Count; i++)
{
if (Canvas.GetLeft(snake[0]) == Canvas.GetLeft(snakes[i])+size && Canvas.GetTop(snake[0]) <= Canvas.GetTop(snakes[i]))
{
//for (int j = 0; j < ; j++)
//{
//}
// MessageBox.Show("撞了");
MoveTimer.Stop();
snake.Clear();
snakes.Clear();
BG.Children.Clear();
MessageBoxResult r = MessageBox.Show("撞了" , "是否重新开始游戏?", MessageBoxButton.OKCancel);
if (r == MessageBoxResult.OK)
{
/// Scoring.Content = "";
CreateDouDou();
CreateSnake2();
CreateSnake();
MoveTimer.Start();
BG.Children.Add(rim);
}
else
{
this.Close();
}
}
}
//头部与食物重合 第一条蛇
if (Canvas.GetLeft(snakes[0]) == Canvas.GetLeft(food) && Canvas.GetTop(snakes[0]) == Canvas.GetTop(food))//所以判断为空
{
//CreateDouDou();
x++;
if (x>=3)
{
MoveTimer.Interval = TimeSpan.FromMilliseconds(50);
}
Scoring.Content ="最后得分:"+x;
//添加蛇的身体
Border body = new Border();
body.Tag = "";
body.Height = body.Width = size;
body.CornerRadius = new CornerRadius(10);
body.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255))));
Canvas.SetLeft(body,Canvas.GetLeft(snakes[snakes.Count-1]));
Canvas.SetTop(body,Canvas.GetTop(snakes[snakes.Count-1]));
snakes.Add(body);
BG.Children.Add(body);
// CreateDouDou();
//食物的位置
food.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255))));
// Canvas.SetLeft(food,Canvas.GetLeft(food));
Canvas.SetLeft(food, rd.Next(10,cols) * size + left);//Left跟列有关
Canvas.SetTop(food, rd.Next(1,rows) * size + top);//Top跟行有关
}
//头部与食物重合 第二条蛇
if ( Canvas.GetLeft(snake[0]) == Canvas.GetLeft(food) && Canvas.GetTop(snake[0]) == Canvas.GetTop(food))//所以判断为空
{
//CreateDouDou();
z++;
if (z >= 3)
{
MoveTimer.Interval = TimeSpan.FromMilliseconds(50);
}
Scoring1.Content = "最后得分:" + z;
//添加蛇的身体
Border body1 = new Border();
body1.Tag = "";
body1.Height = body1.Width = size;
body1.CornerRadius = new CornerRadius(10);
body1.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255))));
Canvas.SetLeft(body1, Canvas.GetLeft(snake[snake.Count - 1]));
Canvas.SetTop(body1, Canvas.GetTop(snake[snake.Count - 1]));
snake.Add(body1);
BG.Children.Add(body1);
// CreateDouDou();
//食物的位置
food.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255)), Convert.ToByte(rd.Next(0, 255))));
// Canvas.SetLeft(food,Canvas.GetLeft(food));
Canvas.SetLeft(food, rd.Next(10, cols) * size + left);//Left跟列有关
Canvas.SetTop(food, rd.Next(1, rows) * size + top);//Top跟行有关
}
// 第一条蛇 碰撞墙事件
if (Canvas.GetLeft(snakes[0]) <= left || Canvas.GetLeft(snakes[0]) >= rim.Width + left - 60 || Canvas.GetTop(snakes[0]) <= top || Canvas.GetTop(snakes[0]) >= rim.Height)
{
x = 0;
z = 0;
snake.Clear();
MoveTimer.Stop();
snakes.Clear();
BG.Children.Clear();
MessageBoxResult r = MessageBox.Show("小黑你死了" + Scoring.Content.ToString(), "是否重新开始游戏?", MessageBoxButton.OKCancel);
if (r == MessageBoxResult.OK)
{
Scoring.Content = "";
CreateDouDou();
CreateSnake2();
CreateSnake();
MoveTimer.Start();
BG.Children.Add(rim);
}
else
{
this.Close();
}
}
// 第二条蛇 碰撞墙的事件
if (Canvas.GetLeft(snake[0]) <= left + 20 || Canvas.GetLeft(snake[0]) >= rim.Width + left - 60 || Canvas.GetTop(snake[0]) <= top || Canvas.GetTop(snake[0]) >= rim.Height)
{
x = 0;
z = 0;
// Scoring1.Content = "小黄得分:";
MoveTimer.Stop();
snake.Clear();
snakes.Clear();
BG.Children.Clear();
MessageBoxResult r = MessageBox.Show("小黄你死了" + Scoring1.Content.ToString(), "是否重新开始游戏?", MessageBoxButton.OKCancel);
if (r == MessageBoxResult.OK)
{
Scoring1.Content = "";
CreateDouDou();
CreateSnake2();
CreateSnake();
MoveTimer.Start();
BG.Children.Add(rim);
}
else
{
this.Close();
}
// MessageBox.Show();
// MessageBox.Show(Scoring1.Content.ToString());
}
}
bool link = true;//暂停游戏的开关
//键盘移动事件 上下左右按键
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
//不可相对而行
switch (e.Key)
{
case Key.Left:
if (!(snakes[0].Tag.ToString()=="Right"))
{
snakes[0].Tag = "Left";
}
break;
case Key.Right:
if (!(snakes[0].Tag.ToString()=="Left"))
{
snakes[0].Tag = "Right";
}
break;
case Key.Up:
if (!(snakes[0].Tag.ToString()=="Down"))
{
snakes[0].Tag = "Up";
}
break;
case Key.Down:
if (!(snakes[0].Tag.ToString()=="Up"))
{
snakes[0].Tag = "Down";
}
break;
case Key.W:
if (!(snake[0].Tag.ToString()=="S"))
{
snake[0].Tag = "W";
}
break;
case Key.S:
if (!(snake[0].Tag.ToString()=="W"))
{
snake[0].Tag = "S";
}
break;
case Key.A:
if (!(snake[0].Tag.ToString()=="D"))
{
snake[0].Tag = "A";
}
break;
case Key.D:
if (!(snake[0].Tag.ToString()=="A"))
{
snake[0].Tag = "D";
}
break;
default:
break;
}
if (e.KeyStates == Keyboard.GetKeyStates(Key.Space))//空格暂停游戏
{
if (link == true)
{
MoveTimer.Stop();
link = false;
}
else
{
MoveTimer.Start();
link = true;
}
}
}
}
}
Xaml界面
<Window x:Class="WPF贪吃蛇.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:WPF贪吃蛇"
mc:Ignorable="d"
Title="贪吃蛇" Height="800" Width="1000" Loaded="Window_Loaded">
<Canvas x:Name="BG">
<Canvas x:Name="bg" Width="100" Height="40">
<Button Content="开始游戏" Width="100" Height="40" x:Name="start" ButtonBase.Click="Button_Click"/>
</Canvas>
</Canvas>
</Window>