编写一段贪吃蛇代码,用wpf实现
时间: 2023-02-26 11:52:28 浏览: 48
下面是一个使用 WPF 实现的贪吃蛇代码的示例:
```
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
namespace SnakeGameWPF
{
public partial class MainWindow : Window
{
private const int CellSize = 20;
private readonly Brush SnakeColor = Brushes.Green;
private readonly Brush FoodColor = Brushes.Red;
private readonly Brush BackgroundColor = Brushes.White;
private readonly int Columns = 30;
private readonly int Rows = 20;
private Rectangle[,] grid;
private Point[] snake;
private Point food;
private int direction;
public MainWindow()
{
InitializeComponent();
grid = new Rectangle[Columns, Rows];
for (int i = 0; i < Columns; i++)
{
for (int j = 0; j < Rows; j++)
{
grid[i, j] = new Rectangle
{
Fill = BackgroundColor,
Width = CellSize,
Height = CellSize
};
GameCanvas.Children.Add(grid[i, j]);
Canvas.SetLeft(grid[i, j], i * CellSize);
Canvas.SetTop(grid[i, j], j * CellSize);
}
}
NewGame();
}
private void NewGame()
{
snake = new Point[] { new Point(Columns / 2, Rows / 2) };
direction = 0;
PlaceFood();
UpdateDisplay();
}
private void PlaceFood()
{
Random random = new Random();
do
{
food = new Point(random.Next(Columns), random.Next(Rows));
} while (Array.IndexOf(snake, food) != -1);
}
private void UpdateDisplay()
{
for (int i = 0; i < Columns; i++)
{
for (int j = 0; j < Rows; j++)
{
grid[i, j].Fill = BackgroundColor;
}
}
foreach (Point p in snake)
{
grid[(int)p.X, (int)p.Y].Fill = SnakeColor;
}
grid[(int)food.X, (int)food.Y].Fill = FoodColor;
}
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
switch (e.Key)
{
case System.Windows.Input.Key.Left:
if (direction != 0)
{
direction = -1;
}
break;
case System.Windows.Input.Key.Right:
if (direction != -1)
{
direction = 0;
}
break;
case System.Windows.Input.Key.Up:
if (direction != 2)