2 / 2 / 1
Регистрация: 26.09.2014
Сообщений: 79
1

Поменять точки входа и выхода лабиринта

14.04.2017, 12:33. Показов 1151. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
У меня есть два кода для создания лабиринта. Первый я не знаю как запустить, а второй не могу отредактировать под себя. Мне нужно , чтобы я сам мог задать точки начала и конца
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Maze.Logic
{
    [Flags]
    public enum Directions
    {
        N = 1,
        S = 2,
        E = 4,
        W = 8
    }
 
    public class Grid
    {
        private const int _rowDimension = 0;
        private const int _columnDimension = 1;
 
        public int MinSize { get; private set; }
        public int MaxSize { get; private set; }
        public int[,] Cells { get; private set; }
 
        public Grid() : this(3, 3)
        {
 
        }
 
        public Grid(int rows, int columns)
        {
            MinSize = 3;
            MaxSize = 10;
            Cells = Initialise(rows, columns);
        }
 
        public int[,] Initialise(int rows, int columns)
        {
            if (rows < MinSize)
                rows = MinSize;
 
            if (columns < MinSize)
                columns = MinSize;
 
            if (rows > MaxSize)
                rows = MaxSize;
 
            if (columns > MaxSize)
                columns = MaxSize;
 
            var cells = new int[rows, columns];
 
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    cells[i, j] = 0;
                }               
            }
 
            return cells;
        }
 
        private Dictionary<Directions, int> DirectionX = new Dictionary<Directions, int>
        {
            { Directions.N, 0 },
            { Directions.S, 0 },
            { Directions.E, 1 },
            { Directions.W, -1 }
        };
 
        private Dictionary<Directions, int> DirectionY = new Dictionary<Directions, int>
        {
            { Directions.N, -1 },
            { Directions.S, 1 },
            { Directions.E, 0 },
            { Directions.W, 0 }
        };
 
        private Dictionary<Directions, Directions> Opposite = new Dictionary<Directions, Directions>
        {
            { Directions.N, Directions.S },
            { Directions.S, Directions.N },
            { Directions.E, Directions.W },
            { Directions.W, Directions.E }
        };
 
        public int[,] Generate()
        {
            var cells = Cells;
            CarvePassagesFrom(0, 0, ref cells);
            return cells;
        }
 
        public void CarvePassagesFrom(int currentX, int currentY, ref int[,] grid)
        {
            var directions = new List<Directions>
            {
                Directions.N,
                Directions.S,
                Directions.E,
                Directions.W
            }
            .OrderBy(x => Guid.NewGuid());
 
            foreach (var direction in directions)
            {
                var nextX = currentX + DirectionX[direction];
                var nextY = currentY + DirectionY[direction];
 
                if (IsOutOfBounds(nextX, nextY, grid))
                    continue;
 
                if (grid[nextY, nextX] != 0) // has been visited
                    continue;
 
                grid[currentY, currentX] |= (int)direction;
                grid[nextY, nextX] |= (int)Opposite[direction];
 
                CarvePassagesFrom(nextX, nextY, ref grid);
            }
        }
 
        private bool IsOutOfBounds(int x, int y, int[,] grid)
        {
            if (x < 0 || x > grid.GetLength(_rowDimension) - 1)
                return true;
 
            if (y < 0 || y > grid.GetLength(_columnDimension) - 1)
                return true;
 
            return false;
        }
 
        public void Print(int[,] grid)
        {
            var rows = grid.GetLength(_rowDimension);
            var columns = grid.GetLength(_columnDimension);
            
            // Top line
            Console.Write(" ");
            for (int i = 0; i < columns; i++)
                Console.Write(" _");
            Console.WriteLine();
 
            for (int y = 0; y < rows; y++)
            {
                Console.Write(" |");
 
                for (int x = 0; x < columns; x++)
                {
                    var directions = (Directions)grid[y, x];
 
                    var s = directions.HasFlag(Directions.S) ? " " : "_";
 
                    Console.Write(s);
 
                    s = directions.HasFlag(Directions.E) ? " " : "|";
 
                    Console.Write(s);                   
                }
 
                Console.WriteLine();
            }
        }
    }
}
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace ConsoleApplication11
{
    class Program
    {
        static void CreateMap(ref int[,] maze)
        {
            //Для матрицы любого размера
            Random rnd = new Random(DateTime.Now.Millisecond);
            int length = -1;
            var nextPreviousNull = new List<int>();
            var resultPreviousNull = new List<int>();
            int ChisloHodov = 25; //Число одновременных ходов
            int shansTupika = 5; //Шанс тупика
            int DimensionMatrix = maze.GetLength(0);
            for (int i = 0; i < DimensionMatrix; i++)
                for (int j = 0; j < DimensionMatrix; j++)
                    maze[i, j] = 1;
            for (int i = 0; i < DimensionMatrix; i++)
            {
                if (i == 0)
                {
                    maze[i, 1] = 0;
                    resultPreviousNull.Add(1);
                    continue;
                };
                if (i + 1 == DimensionMatrix)
                {
                    maze[i, resultPreviousNull[rnd.Next(0, resultPreviousNull.Count)]] = 0;
                    continue;
                };
                nextPreviousNull.Clear();
                for (int x = 0; x < resultPreviousNull.Count; x++)
                {
                    if (x + 1 != resultPreviousNull.Count && rnd.Next(0, shansTupika) == 0) continue;
                    maze[i, resultPreviousNull[x]] = 0;
                    nextPreviousNull.Add(resultPreviousNull[x]);
                    length = rnd.Next(0, resultPreviousNull[x]);
                    for (int j = resultPreviousNull[x] - 1; length != 0; j--)
                    {
                        if (maze[i - 1, j] != 0)
                        {
                            maze[i, j] = 0;
                            nextPreviousNull.Add(j);
                        }
                        else break;
                        length--;
                    };
                    length = rnd.Next(0, DimensionMatrix - 1 - resultPreviousNull[x]);
                    for (int j = resultPreviousNull[x] + 1; length != 0; j++)
                    {
                        if (maze[i - 1, j] != 0)
                        {
                            maze[i, j] = 0;
                            nextPreviousNull.Add(j);
                        }
                        else break;
                        length--;
                    };
                }
 
                resultPreviousNull.Clear();
                for (int k = 0; k < ChisloHodov; k++)
                    resultPreviousNull.Add(nextPreviousNull[rnd.Next(0, nextPreviousNull.Count)]);
                resultPreviousNull = resultPreviousNull.Distinct().ToList();
                for (int h = 0; h < resultPreviousNull.Count; h++)
                {
                    if (resultPreviousNull.Contains(resultPreviousNull[h] + 1))
                        resultPreviousNull.Remove(resultPreviousNull[h] + 1);
                    if (resultPreviousNull.Contains(resultPreviousNull[h] - 1))
                        resultPreviousNull.Remove(resultPreviousNull[h] - 1);
                };
            }
        }
 
        static void Main(string[] args)
        {
            Console.CursorVisible = false;
 
            //ввод 
            int[,] maze = new int[20, 20]; //любой размер, но может не поместиться в консоль
            CreateMap(ref maze);  //создание карты
 
            //координаты игрока
            int x = 1, y = 1;
            while (true)
            {
                //рисуем лабиринт
                Console.Clear();
                for (int i = 0; i < maze.GetLength(0); i++)
                {
                    for (int j = 0; j < maze.GetLength(1); j++)
                    {
                        if (maze[i, j] == 0) Console.Write(".");
                        if (maze[i, j] == 1) Console.Write("#");
 
                    }
                    Console.WriteLine();
                }
                Console.CursorLeft = x;
                Console.CursorTop = y;
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write("@");
                Console.BackgroundColor = ConsoleColor.Cyan;
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.BackgroundColor = ConsoleColor.Black;
 
                // обработка ввода
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.Escape) break;
                if (ki.Key == ConsoleKey.UpArrow && y == 0) continue;
                if (ki.Key == ConsoleKey.DownArrow && y == maze.GetLength(0) - 1)
                {
                    Console.WriteLine(string.Empty);
                    Console.WriteLine("You Wins");
                    Console.ReadKey();
                    break;
                };
                if (ki.Key == ConsoleKey.LeftArrow && maze[y, x - 1] == 0) x--;
                if (ki.Key == ConsoleKey.RightArrow && maze[y, x + 1] == 0) x++;
                if (ki.Key == ConsoleKey.UpArrow && maze[y - 1, x] == 0) y--;
                if (ki.Key == ConsoleKey.DownArrow && maze[y + 1, x] == 0) y++;
            }
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
14.04.2017, 12:33
Ответы с готовыми решениями:

Чем могут помочь точки входа и выхода
У меня стоит на сайте ЛИ. Есть раздел точки входа и точки выхода (в ЛИ). Расскажите как можно...

Можноли поменять Разъем линейного входа с разъемом линейного выхода?
можноли поменять Разъем линейного входа с разъемом линейного выхода? Если да то пожалуйста...

Нахождение выхода из лабиринта
Нужна помощь.Может кто-нибудь видел туториал(или здесь,на форуме) по этой теме.Но хотелось бы,чтобы...

Поиск выхода из лабиринта
Доброго времени суток! Помогите написать процедуру использующую стек для отыскания прохода по...

4
0 / 0 / 0
Регистрация: 14.04.2017
Сообщений: 2
14.04.2017, 18:55 2
Во втором коде
int x = 1, y = 1;
заменить на
int x=0, y=0;
Console.Readln(x);
Console.Readln(y);

так же рекомендую сделать проверку, попадает ли координата в нужный диапазон допустимых значений, ну и оформить покрасивее

по поводу "выхода из лабиринта" - отредактируйте это условие:
if (ki.Key == ConsoleKey.DownArrow && y == maze.GetLength(0) - 1)
заменив на более удобные для вас данные
0
2 / 2 / 1
Регистрация: 26.09.2014
Сообщений: 79
14.04.2017, 22:08  [ТС] 3
WalterBlack, я пробовал так делать, но он начинает ругаться, если я ставлю вход с левой или с правой стороны
0
0 / 0 / 0
Регистрация: 14.04.2017
Сообщений: 2
15.04.2017, 13:37 4
Tatarinov35, покажите пример координат, когда программа не компилируется
0
84 / 85 / 48
Регистрация: 12.10.2013
Сообщений: 1,079
15.04.2017, 14:17 5
Tatarinov35,какой код ваш???
0
15.04.2017, 14:17
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
15.04.2017, 14:17
Помогаю со студенческими работами здесь

Поиск выхода из лабиринта
Такой вопрос. почему у меня не находит выход из лабиринта? предположительно ошибка в функции Solve...

Поиск выхода из лабиринта
Здравствуйте! Изучаю C#, застрял на одном моменте в задании. Суть такова: нужно найти выход из...

Поиск выхода из лабиринта
Здравствуйте! Изучаю C#, застрял на одном моменте в задании. Суть такова: нужно найти выход из...

Поиск выхода из лабиринта
Необходимо реализовать поиск выхода из лабиринта вот допустим лабиринт,но тут он выводит только...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru