This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mutation.cs
62 lines (60 loc) · 2.18 KB
/
Mutation.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace LevelGenerator
{
/// This class holds the mutation operator.
public class Mutation
{
/// The rate at which the mutation adds or removes a lock and a key.
private static int MUTATION_TYPE_RATE = 50;
/// Reproduce a new individual by mutating a parent.
public static Individual Apply(
Individual _parent,
ref Random _rand
) {
Individual individual = _parent.Clone();
// Remove or add a lock and a key
if (MUTATION_TYPE_RATE > Common.RandomPercent(ref _rand))
{
individual.dungeon.AddLockAndKey(ref _rand);
}
else
{
individual.dungeon.RemoveLockAndKey(ref _rand);
}
// Transfer enemies between rooms
int size = individual.dungeon.rooms.Count;
List<int> options = Enumerable.Range(1, size - 1).ToList<int>();
while (options.Count / 2 > 1)
{
// Select random rooms
int idx_f = Common.RandomElementFromList(options, ref _rand);
options.Remove(idx_f);
int idx_t = Common.RandomElementFromList(options, ref _rand);
options.Remove(idx_t);
// If the chosen room `to` has more enemies than the
// room `from`, then swap them
Room from = individual.dungeon.rooms[idx_f];
Room to = individual.dungeon.rooms[idx_t];
if (to.enemies > from.enemies)
{
Room aux = from;
from = to;
to = aux;
}
// Transfer enemies
int transfer = 0;
if (from.enemies > 0)
{
transfer = Common.RandomInt((1, from.enemies), ref _rand);
}
from.enemies -= transfer;
to.enemies += transfer;
Debug.Assert(from.enemies >= 0 && to.enemies >= 0);
}
return individual;
}
}
}