如何使用C#实现贪吃蛇小游戏代码

297 阅读1分钟
using System;
using System.Collections.Generic;

namespace SnakeGame
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set up the game board
            Console.WindowHeight = 30;
            Console.WindowWidth = 50;
            Console.BufferHeight = 30;
            Console.BufferWidth = 50;

            // Initialize the snake
            List<Tuple<int, int>> snake = new List<Tuple<int, int>>();
            snake.Add(new Tuple<int, int>(0, 0));

            // Main game loop
            while (true)
            {
                // Clear the console
                Console.Clear();

                // Draw the snake
                foreach (var segment in snake)
                {
                    Console.SetCursorPosition(segment.Item1, segment.Item2);
                    Console.Write("O");
                }

                // Move the snake
                var head = snake[snake.Count - 1];
                var x = head.Item1;
                var y = head.Item2;
                snake.RemoveAt(0);
                switch (Console.ReadKey().Key)
                {
                    case ConsoleKey.LeftArrow:
                        x--;
                        break;
                    case ConsoleKey.RightArrow:
                        x++;
                        break;
                    case ConsoleKey.UpArrow:
                        y--;
                        break;
                    case ConsoleKey.DownArrow:
                        y++;
                        break;
                }
                snake.Add(new Tuple<int, int>(x, y));

                // Pause for a short time
                System.Threading.Thread.Sleep(100);
            }
        }
    }
}