2

Я недавно начал учить программирование, в частности C#. Дошел до ООП, выучил теорию, попытался что-то реализовать.

Не подскажете, насколько код написан верно с точки зрения ООП, что можно переделать и что не так?

Игра 2048

    using System;
    using System.Linq;
    
    namespace _20
    {
        class Control
        {
            static void Main(string[] args)
            {
                Game game = new Game();
    
                while(game.IsMovies())
                {
                    var k = Console.ReadKey().Key;
    
                    game.ControlBlock(k);
                }
    
                Console.WriteLine("Game over!");
            }
    
            string s = Console.ReadLine();
        }
    
        class Game
        {
            private const int SIZE = 4;
            private int[,] _field;
    
            private int _col;
            private int _row;
            private int _score;
    
            private bool _moveIsDoing;
    
            private Random _random;
            private Paint _paint;
    
            public Game()
            {
                _random = new Random();
                _paint = new Paint();
                _field = new int[SIZE, SIZE];
                _score = 0;
                _moveIsDoing = false;
                for (int i = 0; i < 2; i++) { GetCoordinate(); AssignCoordinate(); }
    
                ShowAr();
            }
    
            public void ControlBlock(ConsoleKey key)
            {
                if (key == ConsoleKey.LeftArrow)
                {
                    Left();
                }
    
                if (key == ConsoleKey.RightArrow)
                {
                    Right();
                }
    
                if (key == ConsoleKey.UpArrow)
                {
                    Up();
                }
    
                if (key == ConsoleKey.DownArrow)
                {
                    Down();
                }
    
                if (IsEmptyCell())
                {
                    if (_moveIsDoing)
                    {
                        GetCoordinate();
                        AssignCoordinate();
                        _moveIsDoing = false;
                    }
                }
    
                _paint.Clear();
                ShowAr();
            }
    
            private void Right()
            {
                int startCoordiante = 2;
    
                for (int i = startCoordiante; i >= 0; i--)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[j, i] == 0)
                        {
                            continue;
                        }
    
                        int doubleI = i;
    
                        while (doubleI < SIZE - 1)
                        {
                            if (_field[j, doubleI] != _field[j, doubleI + 1] && _field[j, doubleI + 1] != 0)
                            {
                                break;
                            }
    
                            _moveIsDoing = true;
    
                            if (_field[j, doubleI] == _field[j, doubleI + 1])
                            {
                                _field[j, doubleI + 1] *= 2;
                                _field[j, doubleI] = 0;
                                _score += _field[j, doubleI + 1];
                                break;
                            }
                            else if (_field[j, doubleI + 1] == 0)
                            {
                                int val = _field[j, doubleI];
                                _field[j, doubleI] = _field[j, doubleI + 1];
                                _field[j, doubleI + 1] = val;
                                doubleI++;
                            }
                        }
                    }
                }
            }
    
            private void Left()
            {
                int startCoordiante = 1;
    
                for (int i = startCoordiante; i < SIZE; i++)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[j, i] == 0)
                        {
                            continue;
                        }
    
                        int doubleI = i;
    
                        while (doubleI > 0)
                        {
                            if (_field[j, doubleI] != _field[j, doubleI - 1] && _field[j, doubleI - 1] != 0)
                            {
                                break;
                            }
    
                            _moveIsDoing = true;
    
                            if (_field[j, doubleI] == _field[j, doubleI - 1])
                            {
                                _field[j, doubleI - 1] *= 2;
                                _field[j, doubleI] = 0;
                                _score += _field[j, doubleI - 1];
                                break;
                            }
                            else if (_field[j, doubleI - 1] == 0)
                            {
                                int val = _field[j, doubleI];
                                _field[j, doubleI] = _field[j, doubleI - 1];
                                _field[j, doubleI - 1] = val;
                                doubleI--;
                            }
                        }
                    }
                }
            }
    
            private void Up()
            {
                int startCoordiante = 1;
    
                for (int i = startCoordiante; i < SIZE; i++)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[i, j] == 0)
                        {
                            continue;
                        }
    
                        int doubleI = i;
    
                        while (doubleI > 0)
                        {
                            if (_field[doubleI, j] != _field[doubleI - 1, j] && _field[doubleI - 1, j] != 0)
                            {
                                break;
                            }
    
                            _moveIsDoing = true;
    
                            if (_field[doubleI, j] == _field[doubleI - 1, j])
                            {
                                _field[doubleI - 1, j] *= 2;
                                _field[doubleI, j] = 0;
                                _score += _field[doubleI - 1, j];
                                break;
                            }
                            else if (_field[doubleI - 1, j] == 0)
                            {
                                int val = _field[doubleI, j];
                                _field[doubleI, j] = _field[doubleI - 1, j];
                                _field[doubleI - 1, j] = val;
                                doubleI--;
                            }
                        }
                    }
                }
            }
    
            private void Down()
            {
                int startCoordiante = 2;
    
                for (int i = startCoordiante; i >= 0; i--)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[i, j] == 0)
                        {
                            continue;
                        }
    
                        int doubleI = i;
    
                        while (doubleI < SIZE - 1)
                        {
                            if (_field[doubleI, j] != _field[doubleI + 1, j] && _field[doubleI + 1, j] != 0)
                            {
                                break;
                            }
    
                            _moveIsDoing = true;
    
                            if (_field[doubleI, j] == _field[doubleI + 1, j])
                            {
                                _field[doubleI + 1, j] *= 2;
                                _field[doubleI, j] = 0;
                                _score += _field[doubleI + 1, j];
                                break;
                            }
                            else if (_field[doubleI + 1, j] == 0)
                            {
                                int val = _field[doubleI, j];
                                _field[doubleI, j] = _field[doubleI + 1, j];
                                _field[doubleI + 1, j] = val;
                                doubleI++;
                            }
                        }
                    }
                }
            }
    
            private bool IsEmptyCell()
            {
                for(int i = 0; i < SIZE; i++)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[i, j] == 0)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
    
            private void GetCoordinate()
            {
               _col = _random.Next(SIZE);
               _row = _random.Next(SIZE);
    
                if (_field[_col, _row] == 0)
                {
                    return;
                }
    
                for (int i = _col; i < SIZE; i++)
                {
                    for (int j = _row; j < SIZE; j++)
                    {
                        if (_field[i, j] == 0)
                        {
                            _col = i;
                            _row = j;
                            return;
                        }
                    }
                }
    
                for (int i = _col; i >= 0; i--)
                {
                    for (int j = _row; j >= 0; j--)
                    {
                        if (_field[i, j] == 0)
                        {
                            _col = i;
                            _row = j;
                            return;
                        }
                    }
                }
            }
    
            private void AssignCoordinate()
            {
                if (_random.Next(100) > 10)
                {
                    _field[_col, _row] = 2;
                }
                else
                {
                    _field[_col, _row] = 4;
                }
            }
    
            private void ShowAr()
            {
                _paint.ShowField(_field, _score, SIZE);
            }
    
            public bool IsMovies()
            {
                if (IsEmptyCell())
                {
                    return true;
                }
    
                for (int i = 0; i < SIZE; i++)
                {
                    for (int j = 0; j < SIZE - 1; j++)
                    {
                        if (_field[i, j] == _field[i, j + 1])
                        {
                            return true;
                        }
                    }
                }
    
                for (int i = 0; i < SIZE - 1; i++)
                {
                    for (int j = 0; j < SIZE; j++)
                    {
                        if (_field[i + 1, j] == _field[i, j])
                        {
                            return true;
                        }
                    }
                }
    
                return false;
            }
        }
    
        class Paint
        {
            public void ShowField(int[,] field, int score, int size, int cellPadding = 4)
            {
                string plus = "+";
                char minus = '-';
                char vertLine = '|';
    
    
                string[,] numsAsString = new string[size, size];
                int maxSymbols = 0;
    
                for (int i = 0; i < size; i++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        numsAsString[i, j] = field[i, j].ToString();
    
                        int symbolsCount = numsAsString[i, j].Length;
    
                        if (symbolsCount > maxSymbols)
                            maxSymbols = symbolsCount;
    
                    }
                }
    
                int cellWidth = maxSymbols + cellPadding * 2;
    
                string horizontalLine = plus + string.Concat(Enumerable.Repeat(plus.PadLeft(cellWidth + 1, minus), size));
                Console.WriteLine(horizontalLine);
    
                for (int i = 0; i < size; i++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        int leftSpacesCount = cellWidth / 2 - numsAsString[i, j].Length / 2;
                        int rightSpacesCount = cellWidth - numsAsString[i, j].Length - leftSpacesCount;
    
                        string spacesL = new string(' ', leftSpacesCount);
                        string spacesR = new string(' ', rightSpacesCount);
    
                        Console.Write($"{vertLine}{spacesL}");
    
                        Console.ForegroundColor = GetColor(field[i, j]);
                        Console.Write($"{numsAsString[i, j]}{spacesR}");
                        Console.ResetColor();
                    }
                    Console.Write(vertLine + "\n");
                    Console.WriteLine(horizontalLine);
                }
                Console.WriteLine($"Score: {score}");
            }
    
            private ConsoleColor GetColor(int val)
            {
                return val switch
                {
                    2 => ConsoleColor.Red,
                    4 => ConsoleColor.DarkMagenta,
                    8 => ConsoleColor.Green,
                    16 => ConsoleColor.Magenta,
                    32 => ConsoleColor.Cyan,
                    64 => ConsoleColor.DarkCyan,
                    128 => ConsoleColor.DarkBlue,
                    256 => ConsoleColor.DarkGreen,
                    512 => ConsoleColor.DarkYellow,
                    1024 => ConsoleColor.DarkRed,
                    _ => ConsoleColor.White,
                };
            }
    
            public void Clear()
            {
                Console.Clear();
            }
        }
    }

1 ответ 1

6

После 2 недель возни с этой игрой на JS, смотреть на нее больше не могу :) даже любовь к C# не может меня заставить это победить, но пару советов дам.

С точки зрения ООП написано неверно, у вас вся игра - 1 класс. Отдельно вынесена работа с UI - но это больше не само ООП, а проектирование приложения.

У вас на экране объекты - игровое поле и ячейки с числами. Давайте создадим ячейки и поле, отдельно.

Нужны координаты, создам структуру и сделаю, чтобы одни координаты можно было сравнивать с другими.

struct Point : IEquatable<Point>
{
    public int X;
    public int Y;

    public bool Equals(Point other)
    {
        return X == other.X && Y == other.Y;
    }

    public override bool Equals(object obj)
    {
        return obj is Point point && Equals(point);
    }

    public static bool operator ==(Point left, Point right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Point left, Point right)
    {
        return !left.Equals(right);
    }
}

Вот направление движения

enum Direction
{
    Left, Right, Up, Down
}

Вот ячейка

class Cell
{
    public Point Location;
    public int Value;

    public Cell(Point location, int value)
    {
        Location = location;
        Value = value;
    }

    public void Move(Direction direction, int distance)
    {
        switch (direction)
        {
            case Direction.Left: Location.X -= distance; break;
            case Direction.Right: Location.X += distance; break;
            case Direction.Up: Location.Y -= distance; break;
            case Direction.Down: Location.Y += distance; break;
        }
    }

    public void Bump()
    {
        Value *= 2;
    }
}

Создать такую ячейку просто

Cell cell = new Cell(new Point(1, 1), 2);
cell.Move(Direction.Right, 1); // двинуть
cell.Bump(); // удвоить

Вот и получилась ячейка, она имеет координаты и значение, она может двигаться, она может удваивать свое значение. Согласитесь - полезные функции. А это значит, что в логике игры вам не нужно будет их писать, а только использовать. Здесь нет границ передвижения, нет проверки соседней клетки, можно ли туда двигаться. Это игровая логика, и она должна быть в классе с игрой, а не здесь.

Игровое поле

class Board
{
    private const int _size = 4;
    private Random rnd = new Random();
    public List<Cell> Cells = new List<Cell>();

    private Point[] GetFreeCells()
    {
        List<Point> points = new List<Point>();
        for (int y = 0; y < _size; y++)
        {
            for (int x = 0; x < _size; x++)
            {
                Point p = new Point(x, y);
                if (!Cells.Any(c => c.Location == p))
                    points.Add(p);
            }
        }
        return points.ToArray();
    }

    public bool TryCreateCell(int value)
    {
        if (Cells.Count == _size * _size)
            return false;
        Point[] freeCells = GetFreeCells();
        Cell newCell = new Cell(freeCells[rnd.Next(freeCells.Length)], value);
        Cells.Add(newCell);
        return true;
    }

    public void Clear()
    {
        Cells.Clear();
    }

    //...
}

Вот фактически готовое поле с возможностью добавлять ячейку в рандомное пустое место. Конечно список ячеек может быть не так удобен, как поле интов виде массива 4x4, и я наверное даже не буду рекомендовать этот подход использовать, если игра для консоли, но представьте себе, вам при движении ячеек нужно будет одновременно для всех выполнить анимацию перемещения, как в той самой оригинальной игре, но это ведь это лучше всего выполнять в методе Move самой ячейки, так? А у вас его нет и не предусмотрено.

Нарисовать такое поле просто - один цикл foreach и познакомиться с методом Console.SetCursorPosition(x, y). Убрать ячейку с поля тоже проще простого _cells.Remove(cell)

Кстати, игровое поле - это не сама игра. Поле отвечает за то что в него можно добавить ячейку и убрать. Оно защищает ячейки от движений в недопустимые места и т.д. Из него можно получить ячейку по координатам и т.д. А игровая логика будет в классе Game, именно он будет управлять классом Board.

class Game
{
    private Board _board = new Board();
    private Random rnd = new Random();

    public void NewGame()
    {
        _board.Clear();
        TryCreateCell((rnd.Next(2) + 1) * 2); // 2, 4
        TryCreateCell((rnd.Next(2) + 1) * 2);
        DrawBoard(_board.Cells);
    }
}

Здесь и будет связующее звено между UI и игровой логикой.

Вот и получается логическая структура Game > Board > Cell.

Это всего-лишь абстрактный пример, решайте сами, стоит ли его брать в работу или нет.

1
  • 1
    Спасибо большое за настолько развернутый ответ! 4 фев 2022 в 7:55

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.