Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

напиши змейку на C#, в консоли

  1. User

    напиши змейку на C#, в консоли

  2. Assistant

    Для написания игры Змейка на C# в консольном приложении, разберем на несколько общих шагов:

    1. Определение необходимых классов и перечислений.
    2. Загрузка игрового поля и генерация элементов (змейка, стены, еда).
    3. Обработка пользовательского ввода и перемещение змейки.
    4. Проверка на столкновения, увеличение счетчика и обновление игрового поля.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    
    namespace ConsoleSnake
    {
        public enum Direction { Up, Down, Left, Right };
    
        public class Position
        {
            public int X { get; set; }
            public int Y { get; set; }
    
            public Position(int x, int y)
            {
                X = x;
                Y = y;
            }
        }
    
        public class SnakePart
        {
            public Position Position { get; set; }
            public char Symbol { get; set; }
    
            public SnakePart(Position position, char symbol)
            {
                Position = position;
                Symbol = symbol;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                int screenwidth = Console.WindowWidth;
                int screenheight = Console.WindowHeight;
                Random rnd = new Random();
                Position food = new Position(rnd.Next(1, screenwidth - 2), rnd.Next(1, screenheight - 2));
    
                int score = 5;
                char foodSymbol = '¤';
                List<SnakePart> snake = new List<SnakePart>
                {
                    new SnakePart(new Position(screenwidth / 2, screenheight / 2), 'O')
                };
    
                Direction direction = Direction.Right;
                bool gameOver = false;
                Console.CursorVisible = false;
    
                while (!gameOver)
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKey key = Console.ReadKey(true).Key;
                        if (key == ConsoleKey.W && direction != Direction.Down) direction = Direction.Up;
                        if (key == ConsoleKey.S && direction != Direction.Up) direction = Direction.Down;
                        if (key == ConsoleKey.A && direction != Direction.Right) direction = Direction.Left;
                        if (key == ConsoleKey.D && direction != Direction.Left) direction = Direction.Right;
                    }
    
                    Position head = GetNextPosition(snake.First().Position, direction);
                    if (head.X < 0 || head.Y < 0 || head.X >= screenwidth || head.Y >= screenheight || snake.Any(x => x.Position.X == head.X && x.Position.Y == head.Y))
                    {
                        gameOver = true;
                        continue;
                    }
    
                    snake.Insert(0, new SnakePart(head, 'O'));
                    if (head.X == food.X && head.Y == food.Y)
                    {
                        food = new Position(rnd.Next(1, screenwidth - 2), rnd.Next(1, screenheight - 2));
                        score += 10;
                    }
                    else
                    {
                        snake.RemoveAt(snake.Count - 1);
                    }
    
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.SetCursorPosition(food.X, food.Y);
                    Console.Write(foodSymbol);
    
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    foreach (SnakePart part in snake)
                    {
                        Console.SetCursorPosition(part.Position.X, part.Position.Y);
                        Console.Write(part.Symbol);
                    }
    
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.SetCursorPosition(0, 0);
                    Console.Write("Score: " + score.ToString());
    
                    Thread.Sleep(100);
                }
    
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Clear();
                Console.SetCursorPosition(screenwidth / 2 - 4, screenheight / 2);
                Console.Write("GAME OVER");
    
                Console.ReadKey();
                Console.CursorVisible = true;
            }
    
            static Position GetNextPosition(Position position, Direction direction)
            {
                int x = position.X;
                int y = position.Y;
    
                switch (direction)
                {
                    case Direction.Up:
                        y -= 1;
                        break;
                    case Direction.Down:
                        y += 1;
                        break;
                    case Direction.Left:
                        x -= 1;
                        break;
                    case Direction.Right:
                        x += 1;
                        break;
                    default:
                        break;
                }
                return new Position(x, y);
            }
        }
    }
    

    Это простейший пример игры Змейка на C# с использованием консоли. Все объекты и элементы игры представлены символами.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.