C#实现贪吃蛇游戏

定义贪吃蛇和游戏逻辑

  1. 定义数据结构:创建一个类来表示贪吃蛇的每个部分(通常是一个具有X和Y坐标的结构体或类)。
  2. 定义游戏状态:包括蛇的位置、方向、长度以及食物的位置。
  3. 处理键盘输入:重写窗体的键盘事件处理函数,以便玩家可以使用键盘控制蛇的移动方向。
  4. 更新游戏状态:在每个游戏循环中,更新蛇的位置(根据当前方向和移动速度),并检查是否吃到食物、撞到墙壁或自己。
  5. 绘制游戏画面:在窗体的Paint事件中,根据当前的游戏状态绘制蛇和食物。
cs 复制代码
using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
    // 游戏区域大小
    static int width = 20;
    static int height = 10;

    // 蛇的方向
    enum Direction { Up, Down, Left, Right };
    static Direction dir = Direction.Right;

    // 蛇的初始位置
    static List<int[]> snake = new List<int[]> { new int[] { 3, 1 }, new int[] { 2, 1 }, new int[] { 1, 1 } };

    // 食物的位置
    static int[] food = new int[2];

    // 游戏是否结束
    static bool gameOver = false;

    static void Main(string[] args)
    {
        Console.CursorVisible = false;
        Console.SetWindowSize(width + 1, height + 1);

        // 设置初始食物位置
        GenerateFood();

        // 游戏循环
        while (!gameOver)
        {
            Draw();
            Input();
            Move();
            CheckCollision();
            Thread.Sleep(100);
        }

        Console.SetCursorPosition(width / 2 - 4, height / 2);
        Console.WriteLine("Game Over!");
        Console.ReadKey();
    }

    static void Draw()
    {
        Console.Clear();

        // 画蛇
        foreach (var segment in snake)
        {
            Console.SetCursorPosition(segment[0], segment[1]);
            Console.Write("o");
        }

        // 画食物
        Console.SetCursorPosition(food[0], food[1]);
        Console.Write("X");
    }

    static void Input()
    {
        if (Console.KeyAvailable)
        {
            ConsoleKeyInfo key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.W:
                    if (dir != Direction.Down)
                        dir = Direction.Up;
                    break;
                case ConsoleKey.S:
                    if (dir != Direction.Up)
                        dir = Direction.Down;
                    break;
                case ConsoleKey.A:
                    if (dir != Direction.Right)
                        dir = Direction.Left;
                    break;
                case ConsoleKey.D:
                    if (dir != Direction.Left)
                        dir = Direction.Right;
                    break;
            }
        }
    }

    static void Move()
    {
        int[] head = new int[] { snake[0][0], snake[0][1] };
        switch (dir)
        {
            case Direction.Up:
                head[1]--;
                break;
            case Direction.Down:
                head[1]++;
                break;
            case Direction.Left:
                head[0]--;
                break;
            case Direction.Right:
                head[0]++;
                break;
        }

        // 添加新的头部
        snake.Insert(0, head);

        // 如果吃到了食物
        if (head[0] == food[0] && head[1] == food[1])
        {
            GenerateFood();
        }
        else
        {
            // 移除尾部
            snake.RemoveAt(snake.Count - 1);
        }
    }

    static void GenerateFood()
    {
        Random rnd = new Random();
        bool validPosition = false;

        // 确保食物不在蛇身上
        while (!validPosition)
        {
            food[0] = rnd.Next(0, width);
            food[1] = rnd.Next(0, height);
            validPosition = true;

            foreach (var segment in snake)
            {
                if (food[0] == segment[0] && food[1] == segment[1])
                {
                    validPosition = false;
                    break;
                }
            }
        }
    }

    static void CheckCollision()
    {
        // 检查蛇头是否碰到边界
        if (snake[0][0] < 0 || snake[0][0] >= width || snake[0][1] < 0 || snake[0][1] >= height)
        {
            gameOver = true;
            return;
        }

        // 检查蛇头是否碰到自己的身体
        for (int i = 1; i < snake.Count; i++)
        {
            if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1])
            {
                gameOver = true;
                return;
            }
        }
    }
}

这段代码创建了一个简单的贪吃蛇游戏,你可以在控制台中运行它。玩家可以使用WASD键来控制蛇的移动,目标是尽可能地吃到食物而不与蛇的身体相撞。

相关推荐
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
摸鱼的春哥2 天前
10年3次大失败,他从“罪人”输成了中年人的“白月光”
游戏
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
研华嵌入式3 天前
如何在高通跃龙QCS6490 Arm架构上使用Windows 11 IoT企业版?
arm开发·windows·嵌入式硬件
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎