C#写贪吃蛇

编写一个贪吃蛇游戏涉及到图形界面、事件处理、游戏逻辑等多个方面。在这里,我将提供一个简化版本的贪吃蛇游戏的基本框架,使用C#和Windows窗体应用程序(WinForms)。

步骤 1: 创建Windows窗体应用程序

  1. 打开Visual Studio。
  2. 创建一个新的Windows窗体应用程序项目。

步骤 2: 设计界面

  • 在Form的属性中设置足够大的尺寸,比如 800x600
  • 禁用窗口的标题栏、边框等,以便创建一个全屏的游戏界面。

步骤 3: 定义游戏变量

在Form的代码中定义贪吃蛇的初始状态和游戏逻辑所需的变量。

public partial class MainForm : Form
{
    private const int CellSize = 10; // 每个格子的大小
    private int score = 0;
    private int speed = 100; // 蛇的移动速度,单位毫秒

    // 蛇的身体,使用List<T>存储
    private List<Point> snakeBody = new List<Point>
    {
        new Point(10, 10), // 蛇的初始位置
        new Point(9, 10),
        new Point(8, 10)
    };

    // 蛇头的方向
    private Point direction = new Point(0, -1); // 初始向上移动

    // 食物的位置
    private Point food = new Point(20, 20);

    // 游戏是否暂停
    private bool isPaused = true;
}

步骤 4: 初始化界面和游戏逻辑

  1. 在Form的构造函数中初始化界面和游戏逻辑。
  2. 创建一个定时器(Timer)来控制蛇的移动。
    public MainForm()
    {
        InitializeComponent();
        this.DoubleBuffered = true; // 减少闪烁
        InitializeGame();
    }
    
    private void InitializeGame()
    {
        // 设置定时器
        Timer timer = new Timer();
        timer.Interval = speed;
        timer.Tick += Timer_Tick;
        timer.Start();
    
        // 随机生成食物
        GenerateFood();
    }

    步骤 5: 绘制蛇和食物

  3. 重写 OnPaint 方法来绘制蛇的身体和食物。
  4. 使用 e.Graphics.FillRectangle 方法填充矩形。
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        DrawSnake(e.Graphics);
        DrawFood(e.Graphics);
    }
    
    private void DrawSnake(Graphics g)
    {
        foreach (var part in snakeBody)
        {
            g.FillRectangle(Brushes.Green, part.X * CellSize, part.Y * CellSize, CellSize, CellSize);
        }
    }
    
    private void DrawFood(Graphics g)
    {
        g.FillRectangle(Brushes.Red, food.X * CellSize, food.Y * CellSize, CellSize, CellSize);
    }

    步骤 6: 控制蛇的移动

  5. 在定时器的事件处理器中更新蛇的位置。
    private void Timer_Tick(object sender, EventArgs e)
    {
        if (!isPaused)
        {
            MoveSnake();
            Invalidate(); // 重绘界面
        }
    }
    
    private void MoveSnake()
    {
        var head = new Point(snakeBody[0].X + direction.X, snakeBody[0].Y + direction.Y);
    
        // 检查蛇是否吃到食物
        if (head == food)
        {
            score++;
            GenerateFood();
        }
        else
        {
            snakeBody.RemoveAt(snakeBody.Count - 1); // 移除蛇尾
        }
    
        snakeBody.Insert(0, head); // 新的蛇头
    
        // 检查蛇是否撞到自己或墙壁
        if (snakeBody.Any(part => part == head) || head.X < 0 || head.Y < 0 || head.X >= ClientSize.Width / CellSize || head.Y >= ClientSize.Height / CellSize)
        {
            // 游戏结束逻辑
        }
    }

    步骤 7: 处理键盘输入

  6. 重写 OnKeyDown 方法来处理键盘输入,改变蛇的移动方向。
    protected override void OnKeyDown(KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Up:
                direction = new Point(0, -1);
                break;
            case Keys.Down:
                direction = new Point(0, 1);
                break;
            case Keys.Left:
                direction = new Point(-1, 0);
                break;
            case Keys.Right:
                direction = new Point(1, 0);
                break;
            case Keys.Space:
                isPaused = !isPaused;
                break;
        }
        base.OnKeyDown(e);
    }

    步骤 8: 生成食物

  7. 创建一个方法来随机生成食物的位置。
    private void GenerateFood()
    {
        Random random = new Random();
        food = new Point(
            random.Next(0, (int)(ClientSize.Width / CellSize)),
            random.Next(0, (int)(ClientSize.Height / CellSize))
        );
    }

    这只是一个非常基础的贪吃蛇游戏框架。完整的游戏还需要添加许多特性,比如分数显示、游戏结束逻辑、开始界面、暂停菜单等。此外,为了提高性能和用户体验,你可能需要使用更高级的图形处理技术,比如DirectX或OpenGL。但这个框架提供了一个起点,你可以在此基础上进行扩展和完善。

  • 30
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C#的简单贪吃蛇游戏代码,仅供参考: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApp1 { class Program { static int width = 20; static int height = 20; static int score = 0; static int[,] grid = new int[width, height]; static List<Point> snake = new List<Point>(); static Point food = new Point(); static Random rnd = new Random(); static void Main(string[] args) { InitGame(); while (true) { DrawGrid(); DrawSnake(); DrawFood(); MoveSnake(); if (CheckCollision()) { Console.Clear(); Console.WriteLine("Game over!"); Console.WriteLine("Score: " + score); Console.ReadKey(); break; } Thread.Sleep(100); } } static void InitGame() { snake.Add(new Point(width / 2, height / 2)); grid[snake[0].x, snake[0].y] = 1; food = GenerateFood(); } static void DrawGrid() { Console.Clear(); for (int i = 0; i < height + 2; i++) { for (int j = 0; j < width + 2; j++) { if (i == 0 || i == height + 1 || j == 0 || j == width + 1) Console.Write("#"); else Console.Write(" "); } Console.WriteLine(); } Console.WriteLine("Score: " + score); } static void DrawSnake() { foreach (Point p in snake) { Console.SetCursorPosition(p.x + 1, p.y + 1); Console.Write("*"); } } static void DrawFood() { Console.SetCursorPosition(food.x + 1, food.y + 1); Console.Write("@"); } static void MoveSnake() { Point head = new Point(snake[0].x, snake[0].y); switch (Console.ReadKey().Key) { case ConsoleKey.LeftArrow: head.x--; break; case ConsoleKey.RightArrow: head.x++; break; case ConsoleKey.UpArrow: head.y--; break; case ConsoleKey.DownArrow: head.y++; break; } snake.Insert(0, head); if (head.x == food.x && head.y == food.y) { score++; food = GenerateFood(); } else { snake.RemoveAt(snake.Count - 1); } } static bool CheckCollision() { if (snake[0].x == 0 || snake[0].x == width + 1 || snake[0].y == 0 || snake[0].y == height + 1) return true; for (int i = 1; i < snake.Count; i++) { if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) return true; } return false; } static Point GenerateFood() { Point p = new Point(rnd.Next(1, width + 1), rnd.Next(1, height + 1)); while (grid[p.x, p.y] == 1) { p.x = rnd.Next(1, width + 1); p.y = rnd.Next(1, height + 1); } return p; } class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值