forked from fxwkes/Roguelike
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMap.cs
More file actions
679 lines (546 loc) · 21.7 KB
/
Copy pathMap.cs
File metadata and controls
679 lines (546 loc) · 21.7 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.ComponentModel;
using System.IO;
using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace CaveGenerator
{ [DataContract]
class Cave
{
private Random rnd;
public string[] WorldAscii { get; private set; }
public Roguelike.Tile[,] WorldTile { get; private set; }
public Roguelike.Point Offset { get; set; }
#region properties
public int Neighbours { get; set; }
public int CloseCellProb { get; set; } //55 tends to produce 1 cave, 40 few and small caves
public int Iterations { get; set; }
[DataMember]
public Size MapSize { get; set; }
public int LowerLimit { get; set; }
public int UpperLimit { get; set; }
public int EmptyNeighbours { get; set; }
public int EmptyCellNeighbours { get; set; }
//corridor properties
public int Corridor_Min { get; set; }
public int Corridor_Max { get; set; }
public int Corridor_MaxTurns { get; set; }
public int CorridorSpace { get; set; }
public int BreakOut { get; set; }
public int CaveNumber { get { return Caves == null ? 0 : Caves.Count; } }
#endregion
#region map structures
/// <summary>
/// Caves within the map are stored here
/// </summary>
///
[JsonIgnore]
private List<List<Point>> Caves;
/// <summary>
/// Corridors within the map stored here
/// </summary>
[JsonIgnore]
private List<Point> Corridors;
/// <summary>
/// Contains the map
/// </summary>
[DataMember]
public int[][] Map;
#endregion
#region lookups
/// <summary>
/// Generic list of points which contain 4 directions
/// </summary>
List<Point> Directions = new List<Point>()
{
new Point (0,-1) //north
, new Point(0,1) //south
, new Point (1,0) //east
, new Point (-1,0) //west
};
List<Point> Directions1 = new List<Point>()
{
new Point (0,-1) //north
, new Point(0,1) //south
, new Point (1,0) //east
, new Point (-1,0) //west
, new Point (1,-1) //northeast
, new Point(-1,-1) //northwest
, new Point (-1,1) //southwest
, new Point (1,1) //southeast
, new Point(0,0) //centre
};
#endregion
#region misc
/// <summary>
/// Constructor
/// </summary>
public Cave()
{
rnd = new Random();
Neighbours = 4;
Iterations = 50000;
CloseCellProb = 45;
LowerLimit = 16;
UpperLimit = 500;
MapSize = new Size(150, 150);
EmptyNeighbours = 3;
EmptyCellNeighbours = 4;
CorridorSpace = 2;
Corridor_MaxTurns = 10;
Corridor_Min = 2;
Corridor_Max = 5;
BreakOut = 100000;
}
public void WriteMapIntoFile()
{
int worldHeight = Map.GetLength(0);
int worldWidth = Map.GetLength(1);
WorldTile = new Roguelike.Tile[worldHeight, worldWidth];
for (int x = 0; x < MapSize.Width; x++)
for (int y = 0; y < MapSize.Height; y++)
{
if (x == 0 || x == MapSize.Width - 1 || y == 0 || y == MapSize.Height - 1)
Map[x][y] = 0 ;
WorldTile[x, y] = new Roguelike.Tile((Roguelike.TileFlyweight.Type)Map[x, y]);
}
WorldAscii = new string[worldHeight];
StringBuilder[] builder = new StringBuilder[worldHeight];
for (var x = 0; x < worldHeight; x++)
{
builder[x] = new StringBuilder();
for (var y = 0; y < worldWidth; y++)
{
//true == wall, false == ".", 2 == treasure; 0 == wall, 1 == ".".
if (Map[x][y] == 0)
builder[x].Append("▒");
//Console.Write("#");
//The colour of treasure!
else
builder[x].Append(".");
//Console.Write(".");
}
//Console.WriteLine();
}
for (int i = 0; i < worldHeight; i++)
{
WorldAscii[i] = builder[i].ToString();
}
}
public int Build()
{
BuildCaves();
GetCaves();
return Caves.Count();
}
#endregion
#region cave related
#region make caves
/// <summary>
/// Calling this method will build caves, smooth them off and fill in any holes
/// </summary>
private void BuildCaves()
{
Map = new int[MapSize.Width] [];
for (int i = 0; i < MapSize.Width; i++)
{
Map[i] = new int[MapSize.Height];
}
//go through each map cell and randomly determine whether to close it
//the +5 offsets are to leave an empty border round the edge of the map
for (int x = 0; x < MapSize.Width; x++)
for (int y = 0; y < MapSize.Height; y++)
if (rnd.Next(0, 100) < CloseCellProb)
Map[x] [y] = 1;
Point cell;
//Pick cells at random
for (int x = 0; x <= Iterations; x++)
{
cell = new Point(rnd.Next(0, MapSize.Width), rnd.Next(0, MapSize.Height));
//if the randomly selected cell has more closed neighbours than the property Neighbours
//set it closed, else open it
if (Neighbours_Get1(cell).Where(n => Point_Get(n) == 1).Count() > Neighbours)
Point_Set(cell, 1);
else
Point_Set(cell, 0);
}
//
// Smooth of the rough cave edges and any single blocks by making several
// passes on the map and removing any cells with 3 or more empty neighbours
//
for (int ctr = 0; ctr < 5; ctr++)
{
//examine each cell individually
for (int x = 0; x < MapSize.Width; x++)
for (int y = 0; y < MapSize.Height; y++)
{
cell = new Point(x, y);
if (
Point_Get(cell) > 0
&& Neighbours_Get(cell).Where(n => Point_Get(n) == 0).Count() >= EmptyNeighbours
)
Point_Set(cell, 0);
}
}
//
// fill in any empty cells that have 4 full neighbours
// to get rid of any holes in an cave
//
for (int x = 0; x < MapSize.Width; x++)
for (int y = 0; y < MapSize.Height; y++)
{
cell = new Point(x, y);
if (
Point_Get(cell) == 0
&& Neighbours_Get(cell).Where(n => Point_Get(n) == 1).Count() >= EmptyCellNeighbours
)
Point_Set(cell, 1);
}
}
#endregion
#region locate caves
/// <summary>
/// Locate the edge of the specified cave
/// </summary>
/// <param name="pCaveNumber">Cave to examine</param>
/// <param name="pCavePoint">Point on the edge of the cave</param>
/// <param name="pDirection">Direction to start formting the tunnel</param>
/// <returns>Boolean indicating if an edge was found</returns>
private void Cave_GetEdge(List<Point> pCave, ref Point pCavePoint, ref Point pDirection)
{
do
{
//random point in cave
pCavePoint = pCave.ToList()[rnd.Next(0, pCave.Count())];
pDirection = Direction_Get(pDirection);
do
{
pCavePoint.Offset(pDirection);
if (!Point_Check(pCavePoint))
break;
else if (Point_Get(pCavePoint) == 0)
return;
} while (true);
} while (true);
}
/// <summary>
/// Locate all the caves within the map and place each one into the generic list Caves
/// </summary>
private void GetCaves()
{
Caves = new List<List<Point>>();
List<Point> Cave;
Point cell;
//examine each cell in the map...
for (int x = 0; x < MapSize.Width; x++)
for (int y = 0; y < MapSize.Height; y++)
{
cell = new Point(x, y);
//if the cell is closed, and that cell doesn't occur in the list of caves..
if (Point_Get(cell) > 0 && Caves.Count(s => s.Contains(cell)) == 0)
{
Cave = new List<Point>();
//launch the recursive
LocateCave(cell, Cave);
//check that cave falls with the specified property range size...
if (Cave.Count() <= LowerLimit | Cave.Count() > UpperLimit)
{
//it does, so bin it
foreach (Point p in Cave)
Point_Set(p, 0);
}
else
Caves.Add(Cave);
}
}
}
/// <summary>
/// Recursive method to locate the cells comprising a cave,
/// based on flood fill algorithm
/// </summary>
/// <param name="cell">Cell being examined</param>
/// <param name="current">List containing all the cells in the cave</param>
private void LocateCave(Point pCell, List<Point> pCave)
{
foreach (Point p in Neighbours_Get(pCell).Where(n => Point_Get(n) > 0))
{
if (!pCave.Contains(p))
{
pCave.Add(p);
LocateCave(p, pCave);
}
}
}
#endregion
#region connect caves
/// <summary>
/// Attempt to connect the caves together
/// </summary>
public bool ConnectCaves()
{
if (Caves.Count() == 0)
return false;
List<Point> currentcave;
List<List<Point>> ConnectedCaves = new List<List<Point>>();
Point cor_point = new Point();
Point cor_direction = new Point();
List<Point> potentialcorridor = new List<Point>();
int breakoutctr = 0;
Corridors = new List<Point>(); //corridors built stored here
//get started by randomly selecting a cave..
currentcave = Caves[rnd.Next(0, Caves.Count())];
ConnectedCaves.Add(currentcave);
Caves.Remove(currentcave);
//starting builder
do
{
//no corridors are present, sp build off a cave
if (Corridors.Count() == 0)
{
currentcave = ConnectedCaves[rnd.Next(0, ConnectedCaves.Count())];
Cave_GetEdge(currentcave, ref cor_point, ref cor_direction);
}
else
//corridors are presnt, so randomly chose whether a get a start
//point from a corridor or cave
if (rnd.Next(0, 100) > 50)
{
currentcave = ConnectedCaves[rnd.Next(0, ConnectedCaves.Count())];
Cave_GetEdge(currentcave, ref cor_point, ref cor_direction);
}
else
{
currentcave = null;
Corridor_GetEdge(ref cor_point, ref cor_direction);
}
//using the points we've determined above attempt to build a corridor off it
potentialcorridor = Corridor_Attempt(cor_point
, cor_direction
, true);
//if not null, a solid object has been hit
if (potentialcorridor != null)
{
//examine all the caves
for (int ctr = 0; ctr < Caves.Count(); ctr++)
{
//check if the last point in the corridor list is in a cave
if (Caves[ctr].Contains(potentialcorridor.Last()))
{
if (
currentcave == null //we've built of a corridor
| currentcave != Caves[ctr] //or built of a room
)
{
//the last corridor point intrudes on the room, so remove it
potentialcorridor.Remove(potentialcorridor.Last());
//add the corridor to the corridor collection
Corridors.AddRange(potentialcorridor);
//write it to the map
foreach (Point p in potentialcorridor)
Point_Set(p, 1);
//the room reached is added to the connected list...
ConnectedCaves.Add(Caves[ctr]);
//...and removed from the Caves list
Caves.RemoveAt(ctr);
break;
}
}
}
}
//breakout
if (breakoutctr++ > BreakOut)
return false;
} while (Caves.Count() > 0);
Caves.AddRange(ConnectedCaves);
ConnectedCaves.Clear();
return true;
}
#endregion
#endregion
#region corridor related
/// <summary>
/// Randomly get a point on an existing corridor
/// </summary>
/// <param name="Location">Out: location of point</param>
/// <returns>Bool indicating success</returns>
private void Corridor_GetEdge(ref Point pLocation, ref Point pDirection)
{
List<Point> validdirections = new List<Point>();
do
{
//the modifiers below prevent the first of last point being chosen
pLocation = Corridors[rnd.Next(1, Corridors.Count - 1)];
//attempt to locate all the empy map points around the location
//using the directions to offset the randomly chosen point
foreach (Point p in Directions)
if (Point_Check(new Point(pLocation.X + p.X, pLocation.Y + p.Y)))
if (Point_Get(new Point(pLocation.X + p.X, pLocation.Y + p.Y)) == 0)
validdirections.Add(p);
} while (validdirections.Count == 0);
pDirection = validdirections[rnd.Next(0, validdirections.Count)];
pLocation.Offset(pDirection);
}
/// <summary>
/// Attempt to build a corridor
/// </summary>
/// <param name="pStart"></param>
/// <param name="pDirection"></param>
/// <param name="pPreventBackTracking"></param>
/// <returns></returns>
private List<Point> Corridor_Attempt(Point pStart, Point pDirection, bool pPreventBackTracking)
{
List<Point> lPotentialCorridor = new List<Point>();
lPotentialCorridor.Add(pStart);
int corridorlength;
Point startdirection = new Point(pDirection.X, pDirection.Y);
int pTurns = Corridor_MaxTurns;
while (pTurns >= 0)
{
pTurns--;
corridorlength = rnd.Next(Corridor_Min, Corridor_Max);
//build corridor
while (corridorlength > 0)
{
corridorlength--;
//make a point and offset it
pStart.Offset(pDirection);
if (Point_Check(pStart) && Point_Get(pStart) == 1)
{
lPotentialCorridor.Add(pStart);
return lPotentialCorridor;
}
if (!Point_Check(pStart))
return null;
else if (!Corridor_PointTest(pStart, pDirection))
return null;
lPotentialCorridor.Add(pStart);
}
if (pTurns > 1)
if (!pPreventBackTracking)
pDirection = Direction_Get(pDirection);
else
pDirection = Direction_Get(pDirection, startdirection);
}
return null;
}
private bool Corridor_PointTest(Point pPoint, Point pDirection)
{
//using the property corridor space, check that number of cells on
//either side of the point are empty
foreach (int r in Enumerable.Range(-CorridorSpace, 2 * CorridorSpace + 1).ToList())
{
if (pDirection.X == 0)//north or south
{
if (Point_Check(new Point(pPoint.X + r, pPoint.Y)))
if (Point_Get(new Point(pPoint.X + r, pPoint.Y)) != 0)
return false;
}
else if (pDirection.Y == 0)//east west
{
if (Point_Check(new Point(pPoint.X, pPoint.Y + r)))
if (Point_Get(new Point(pPoint.X, pPoint.Y + r)) != 0)
return false;
}
}
return true;
}
#endregion
#region direction related
/// <summary>
/// Return a list of the valid neighbouring cells of the provided point
/// using only north, south, east and west
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private List<Point> Neighbours_Get(Point p)
{
return Directions.Select(d => new Point(p.X + d.X, p.Y + d.Y))
.Where(d => Point_Check(d)).ToList();
}
/// <summary>
/// Return a list of the valid neighbouring cells of the provided point
/// using north, south, east, ne,nw,se,sw
private List<Point> Neighbours_Get1(Point p)
{
return Directions1.Select(d => new Point(p.X + d.X, p.Y + d.Y))
.Where(d => Point_Check(d)).ToList();
}
/// <summary>
/// Get a random direction, provided it isn't equal to the opposite one provided
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private Point Direction_Get(Point p)
{
Point newdir;
do
{
newdir = Directions[rnd.Next(0, Directions.Count())];
} while (newdir.X != -p.X & newdir.Y != -p.Y);
return newdir;
}
/// <summary>
/// Get a random direction, excluding the provided directions and the opposite of
/// the provided direction to prevent a corridor going back on it's self.
///
/// The parameter pDirExclude is the first direction chosen for a corridor, and
/// to prevent it from being used will prevent a corridor from going back on
/// it'self
/// </summary>
/// <param name="dir">Current direction</param>
/// <param name="pDirectionList">Direction to exclude</param>
/// <param name="pDirExclude">Direction to exclude</param>
/// <returns></returns>
private Point Direction_Get(Point pDir, Point pDirExclude)
{
Point NewDir;
do
{
NewDir = Directions[rnd.Next(0, Directions.Count())];
} while (
Direction_Reverse(NewDir) == pDir
| Direction_Reverse(NewDir) == pDirExclude
);
return NewDir;
}
private Point Direction_Reverse(Point pDir)
{
return new Point(-pDir.X, -pDir.Y);
}
#endregion
#region cell related
/// <summary>
/// Check if the provided point is valid
/// </summary>
/// <param name="p">Point to check</param>
/// <returns></returns>
private bool Point_Check(Point p)
{
return p.X >= 0 & p.X < MapSize.Width & p.Y >= 0 & p.Y < MapSize.Height;
}
/// <summary>
/// Set the map cell to the specified value
/// </summary>
/// <param name="p"></param>
/// <param name="val"></param>
private void Point_Set(Point p, int val)
{
Map[p.X] [p.Y] = val;
}
/// <summary>
/// Get the value of the provided point
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private int Point_Get(Point p)
{
return Map[p.X] [p.Y];
}
#endregion
}
}