### Archive

Archive for the ‘C#’ Category

## Checking the validity of an NHS Number using 1 line of C#

This is an experiment to reduce the checking method to one line of code, and makes no attempt at being efficient. This single line, below, is arranged into 8 lines to make it easier to read.

```
pNHSNumber.ToCharArray().Where (i=> i>= 48 && i <=57).Count() != 10 ? false :
new List() { pNHSNumber.ToCharArray()
.Where((value, index) => index < 9)
.Select((value, index) => (10 - index) * (value - 48))
.Sum() }
.Select(i=> i % 11)
.Select(i=> (11 - i) == 11 ? 0 : (11-i))
.First() == (pNHSNumber[pNHSNumber.Length - 1] - 48);

```

It is constructed as follows:

• Line 1: Checking the string length is 10 and consists only of digits
• Lines 2 – 5:  Multiply the first nine digits by a weighting factor and sum, storing the result, a single value, in a generic list.
• Line 3 : select the first 9 digits of pNHSNumber.ToCharArray()
• Line 4: Multiply each of the digits by it’s weighting – first digit by 10 e.g. (10 – index of 0), second digit by 9 (e.g. 10 minus index of 1) etc
• Lin 5: sum the values produced by line 4
• Line 6: Get the remainder of the sum when divided by 11
• Line 7: Subtract the remainder from 11, and if the resultant value is 11 change to 0
• Line 8: Test if the check digit is equal to last digit

Usage

Wrap up the above in a function:

```
bool CheckNNHSNumber (pNHSNumber string)
{
pNHSNumber.ToCharArray().Where (i=> i>= 48 && i <=57).Count() != 10 ? false :
new List() { pNHSNumber.ToCharArray()
.Where((value, index) => index < 9)
.Select((value, index) => (10 - index) * (value - 48))
.Sum() }
.Select(i=> i % 11)
.Select(i=> (11 - i) == 11 ? 0 : (11-i))
.First() == (pNHSNumber[pNHSNumber.Length - 1] - 48);
}
```

and call it, thusly:

```
//valid NHS number
Console.WriteLine(CheckNHSNumber("4800963435"));

//invalid NHS Number
Console.WriteLine(CheckNHSNumber("4800963439"));

```
Categories: Tags:

## C# Brute Force Sudoku Algorithm

I’ve created in C# an algorithm that solves sudoku using the brute force method. This algorithm is contained in the class csSudokuBruteForce.cs that can be found on GitHub here.

## A little bit about it

The csSudokuBruteForce class contains a class called csCell which represents a cell within a sudoku grid with properties representing the row, column, box that cell belongs to, the cell’s value and whether it is solved; 81 of these cells are stored within a generic list called grid which represent sudoku.

The public method BruteForce is called to begin the brute algorithm, which returns a integer array representing the solved sudoku. Testing on Quad core PC shows that solutions can be found in under a second for any tried.

This algorithm doesn’t test the validity of the provided sudoku before it starts the brute force algorithm, and may therefore crash out if what is given to it is incomplete, malformed, containing incorrect characters. It just assumes it’ll get a string 81 characters in length that consists of only the numbers 1 to 9 and 0.

## Using the code

This class is easy to use, and requires only a string of 81 characters representing the sudoku to be solved.  Here’s an example of it’s use:

```
csSudokuBruteForce b = new csSudokuBruteForce();

<span style="line-height: 1.5em;">string puzzle = "003020600900305001001806400008102900700000008006708200002609500800203009005010300";</span>

//solve the sudoku and return the result as an integer array

int [] solution =  b.BruteForce(puzzle);

```

If you’re using this code in a C# Console Application and want to output the array containing the solution, here’s how to do it using Linq:

```
Console.WriteLine (
solution.Select((val, ind) => val.ToString() + ((ind+1) % 9 == 0 ? "\n" : ""))
.Aggregate((total, current) => total + current)
);

```

## What about Project Euler 96?

No. I’m not going to tell you how to to solve it.

## Go on!

No.

I’ll give you a hand, but no more. Here’s how to extract one puzzle at a time from Euler 96′s text file of puzzles:

```

string puzzle;

for (int ctr = 0; ctr <= 49; ctr++)</span>
{

puzzle = puzzles.Where((val, ind) => ind >= (ctr * 10) +1 &amp;amp;amp; ind < (ctr * 10) +10)
.Aggregate((total, current) => total + current);

}

```

It uses loads the text file into a generic list, and then uses Linq to extract the required data from that file. Use your brain and work out how to use it yourself.

You’re welcome.

Categories: C# Tags:

## A C# algorithm to build interesting cave systems for your Roguelike part 1 UPDATED!!!!

I’ve been playing roguelikes for the last twenty years or so, and one thing that has consistently annoyed me is that dungeons, on the whole, tend to be rectangular rooms connected with long, straight corridors that turn at right angles. I’ve never came across a roguelike that has complex, chaotic looking cave systems with twisting corridors  and misshapen rooms, and that has annoyed me so much I decided to put together a simple algoritm in C# to generate such a system. Here’s an example of a complex cave systems generated by my code, and below that I discuss the code used to generate it.

## !!!Update!!!

I have been blown away by the interest from the users of Reddit’s Unity3D  and made an update to the code allowing users to generate a Bitmap of the generated map. See here for more details.

## Overview

This algorithm works by using a modified form of Conway’s Game of Life where:

1. Each cell in the map is visited and a randomly probability is used to determine if that cell is closed,
2. Cells are randomly visited and the number of neighbours that cell has is used to determine whether to close it or open it.

By repeating the second step thousands of times, “blobs” or “caves” start to form which. By adjusting various available properties the characteristics of the caves formed can change considerably, which can lead to some very interesting cave systems being formed.

After caves have been generated, a flood fill based algorithm locates each cave and the data for each cave into a generic list. With this list of caves they can be easily connected together with a dumb corridor building routine is used to try and connect the caves. This works by randomly selecting a cave and growing a corridor in a random direction and seeing if it hits another cave within a time period determined by a series of properties. If sucessful the two connected caves are placed in a list, and a further attempt is made to connect one of those caves to another, and so on.

## The Application

You can find a simple C# application which demos the algorithm I’ve written here, and below is a screenshot of it.

The app consists of three areas:

1. Property grid – the properties which govern the generation of the cave system.
2. Picturebox – displays the generated cave system.
3. Buttons:
1. Build Caves – click to build a cave system.
2. Connect Caves – click to connect the caves.
3. Reset Properties – click the reset the property values to their default state.

Simply put, to build a cave system click the Build Caves button, and to change the appearance of a cave system fiddle with the properties.

### Properties

This application has a number of properties which can be adjusted to determine the appearance of the generated generated cave system:

1. Cave Cleaning
1. Filling - Fills in holes within caves: an open cell with this number closed neighbours is closed.
2. Lower Limit – the minimum size of caves allowed. If a cave is smaller than this number, it will be removed.
3. Smoothing - Removes single cells from cave edges: a cell with this number of empty neighbours is removed
4. Upper Limit - the maximum size of caves allowed. If a cave is larger than this number, it will be removed.
2. Cave Generation
1. Close Cell Prob – this value determines the chance of closing a visited cell.
2. Cells to visit – the number of cells to visit during the generation process.
3. Map Size – guess what this does.
4. Neighbours – when this value is equalled or exceeded, change the cell state.
3. Corridor
1. Breakout  - a counter value, that when exceeded stops attempting to generate corridors. Stops the corridor building process from getting stuck.
2. Corridor Spacing - the number of empty cells the corridor has to have on either side of it for it to be built. This is dependant upon the direction it is travelling. If travelling north, it must have that number of empty cells to the east and west of it.
3. Minimum Length - the minimum length of a corridor.
4. Maximum Length - the maximum length of a corridor.
5. Maximum Turns - the maximum number of direction changes a corridor can make whilst it is being built.
4. Generated Map
1. Caves – the number of caves in the generated system.

## The Code

The code used to generate a caver system is contained within the class csCaveGenerator.cs, which sits in a standard C# form with a few controls on it which can manipulate that class.

For a more detailed look at using the class csCaveGenerator.cs, click here.

To view the class csCaveGenerator.cs in GitHub click here.

## Interesting Patterns

Playing around with the properties can produce cave systems with markedly different appearances, here are a few interesting systems that can be produced.

### Several Large Caves

Setting the properties to:

1. MaxSizeToRemove: 1500
2. MinSizeToRemove: 450
3. EmptyCells > EmptyCellNeighbours: 3

and clicking build a few times produced these three lovely caves.

### Many small chunky caves

Setting the properties to:

1. Iterations: 10,000
2. Smothing>EmptyNeighbours:3
3. EmptyCells>EmptyNeighbours:4

And clicking build, produces lots of little chunky caves with straight edges, packed closer together.

### One Massive Cave

Setting the properties to:

1. Caves > MaxSizeToRemove: 10000
2. Cells > CloseCellProb: 55

And clicking Go a few times will produce a lovely, humongous cave, as shown below.

Github: To view the class csCaveGenerator.cs, which is used to generate the cave system, click here.

To download a C# app which demos the Cave Generator algorithm click  here.

Categories: Tags:

## A C# algorithm to build interesting cave systems for your Roguelike – part 3

This post contains a more detailed look at the class csCaveGenerator.cs, whose layout is discussed here, and can be viewed on GitHub here

Within the class csCaveGenerator.cs, the source code is fully commented and easy to follow, and because I’m lazy I’m not going to copy those comments again :). However I will tell you how to use the class. Refer to the section below called Using the Class.

## Using the class

This is simple enough:

```
csCaveGenerator cavgen = new csCaveGenerator();

```

To build a cave system:

```
cavgen.Build();

```

Connecting rooms is also simple:

```
cavgen.ConnectCaves();

```

## The Generated Map

The publicly exposed property Map is a 2d array which contains the generated map – a value of 1 indicates a closed cell.

Categories: Tags:

## A C# algorithm to build interesting cave systems for your Roguelike – part 2 class layout

This article describes the layout of the class csCaveGenerator.cs which is used to generate a cave system, and can be viewed on GitHub here. Within this class are several regions which are used to group together related methods, properties, data structures etc. These regions are:

1. Properties
2. Misc
3. Map Structures
4. Lookups
5. Cave Related
6. Corridor Related
7. Direction Related
8. Cell Related

## Properties Region

Contains the properties used to control the appearance of the cave system being generated. Discussed in detail in part 1.

## Misc

Contains the class constructor and the method Build() which generates the caves.

## Map Structures Region

This contains the generic lists used to hold cave system data: Caves, Corridors and Map.

## Lookups Region

Contains two lists of points which contain directions:

1. Directions: four points which represent North, South, East and West.
2. Directions1: 8 points which represent North, South, East, West, North East, North West, South East and South West.

These lists are used to examine the neighbours of a cell for the cave generation, smoothing and filling operations.

## Cave Related Region

Contains the code used to generate caves, and subdivided into three regions:

1. Make Caves
2. Locate Caves
3. Connect Caves

#### Make Caves

This contains the method BuildCaves() which generates the cave system

#### Locate Caves

This contains three methods used to locate discrete caves on the map and place them in the generic list Caves. The method GetCaves() is called to do this – which uses a recursive flood fill algorithm.

#### Connect Caves

Contains the method ConnectCaves(), a brute force method which randomly attempts to connect caves. Dependant upon methods in the Cave Related Region.

## Corridor Related Region

Contains the methods:

1. Corridor_GetEdge()
2. Corridor_Attempt()
3. Corridor_PointTest()

Which are all used by the method ConnectCaves().

## Direction Related Region

This region contains a series of methods using in locating the neighbours of a cell, generating a randomly direction etc

## Cell Related Region

A series of methods used for manipulating map cells.

Categories: Tags:

## 7 tricks to simplify your programs with LINQ

Categories: C# Tags:

## Creating a RogueLike Game View with C#

In a RogueLike the game view (GV) is a rectangular area of the map occupied by the player that is displayed on screen, an example of which is shown below. A gameview consists of two parts: a size and an origin (the x and y coordinates which define the top left corner). The origin is calculated from the player’s current coordinates by subtracting half the GV width from player X and half the GV height from player Y, and making adjustments to them under certain conditions described below.

This article describes how to calculate the coordinates required for a game view.

Terminology

The following terms are required in order to calculate the GV origin coordinates GVOriginX and GVOriginY:

1. PlayerX, PlayerY – The coordinates of the player’s current location
2. GVWidth, GVHeight  - The size of the game view
3. MapWidth, MapHeight – The size of the map the player is exploring.

It is assumed that MapWidth > GVWidth and MapHeight > GVHeight.

For the player to be displayed dead centre in the GV GVWidth and GVHeight must be odd numbers.

Calculations

This origin of the GV is defined as:

• GVOriginX = playerX – GVWidth / 2
• GVOriginY = playerY – GVHeight / 2

Therefore, the bottom right corners coordinates of the GV are GVOriginX + GVWidth and GVOriginY + GVHeight.

However, there are obvious conditions where GVOriginX and / or GVOriginY are less than 0, or the bottom right coordinates exceed the MapHeight and / or MapWidth, so we need to make the followings checks and correct as appropriate after calculating generating GVOriginX and GVOriginY:

Check Correction if true
GVOriginX < 0 GVOriginX = 0
GVOriginY < 0 GVOriginY = 0
GVOriginX + GVWidth > MapWidth GVOriginX -= (GVOriginX + iViewWidth – MapWidth)
GVOriginY + GWHeigtht > MapHeight GVOriginY -= (GVOriginY + iViewHeight – MapHeight)

The effect of making these changes will cause the player to be displayed off centre and closer to the edge being moved towards, as shown below. If none of the above corrections are required, the player will be shown in centre of GV as shown in the picture at the start of this article.

Code

A Visual Studio demonstrating the above method in a simple demo which allows a player to explore a map using the keys Q,W,E,A,S,D,Z,X and C can be found here.

Github: here.

Have I seen this before?

The observant amongst you will notice that this code comes from my Evil Science article Field of Vision using recursive shadow casting: C# .Net 3.5 implementation, but I thought I’d use the code again with emphasis on how to draw the Game View.

Categories: Tags:

## Island and labyrinth generating algorithm using C#

This is a simple generating routine I developed in C# whilst experimenting whilst playing around with the algorithms for Conway’s Game of Life.By adjusting the properties it can produce “island” or “labyrinth ” type maps. I “discovered” this algorithm

Here’s a few examples of maps it can generate, with the property values used to create them.  Explanations of the properties are given later in the article.

```
x=100,y=100,p=45, h=true, n=4, i = 50000 produce an "island" map.```
```
x=100,y=100,p=45, h=false, n=4, i = 50000 produce a "labyrinth" map.```
```
x=100,y=100,p=55, h=true, n=4, i = 50000.```
```
x=100,y=100,p=45, h=true, n=4, i = 85000.```
```
x=100,y=100,p=45, h=false, n=2, i = 50000.```
```
x=100,y=100,p=75, h=true, n=5, i = 80000.```

Using the App

Load up the app, fiddle with the properties and click the Go button.

How it Works

Map generation is controlled by the following variables:

1. p (int) – close cell probability. Between 0 and 100.
2. h (bool) – cell operation specifier.
3. i (int) – counter.
4. n (int) – number of cell’s neighbours.
5. c (int) – examined cell’s closed neighbours. Between 0 and 8.

Calling the method go() in the class csIslandMaze will generate a map using the following logic:

1. Randomly choose a cell from map
2. If the cell is open use a p to determine whether we close it.
3. Get c
1. h = true: If c > n close the cell, else open it.
2. h = false: If c > n open the cell, else close it.
4. Repeat steps1 – 3 i number of times.

Varying the above mentioned variables will produce maps of surprisingly different appearances.

Source Code

Github: here.

Categories: Tags:

## Field of Vision using recursive shadow casting: C# .Net 3.5 implementation

A working field-of-view  (FOV) algorithm is one of the essential parts in any roguelike, it is used to calculate which mapcells, within a given radius, that can be seen by seen by the player. This article describes a C# implementation of such an algorithm, known as recursive shadow casting which is described in more detail in the article  FOV using recursive shadowcasting – improved.

Shadowcasting divides the FOV calculations into eight octants and visits the  mapcells of each  row by row or column by column, starting with the nearest row or column and working it’s way outward.

```  ------>  6 row 6 last
----->  5 .
---->  4 .
--->  3 .
-->  2 row 2 second
->  1 row 1 is scanned first
@  @ this is the starting point```

When a scan comes across a cell that blocks the players line of sight it calculates which other cells in rows/columns farther away that isn’t visible because of the blocker. Those cells are “in shadow”, hence the term shadowcasting.

```  -...---  - = visible cells
-..---  # = blocking cell
-#---  . = cells in blocker's shadow
----
---
--
@```

The above text is taken from this article, from the website RogueBasin. I have shamelessly lifted this text, as I feel it is a very clear description of how shadowcasting works, and I can’t improve upon it.

The Application

Below are several pictures of the application which demonstrate that algorithm. The lighter squares represent the cells visible to the player, and the darker ones are those which the player cannot see. The maze displayed in the map has been generated using another algorithm (which I’ll post soon) and is loaded when the application starts up.

The keys q,w,e,a,d,z,x and c control the player move the player. W is up, S down, d right, A left right etc

Source Code

The source code can be downloaded here. And to run it, you’ll need Microsoft Visual Studio which you can find here.

Github: the code for the class FOVRecurse.

What’s Going On?

The class FOVRecurse.cs contains the FOV algorithm, and the methods are GetVisibleCells and ScanOctant are where the magic happens.

When the player moves, the method GetVisibleCells is called which in turn calls the method ScanOctant for each of the 8 areas surrounding the player and all the cells that the player can see are stored in a generic list. Upon completion of this scan the the event playerMoved is fired, which causes the map to be redrawn in the form event pictureBox1_Paint.

There really isn’t that much to say about it as the code speaks for itself, but if you’re stuck with anything please add a comment and I’ll get back to you.

Acknowledgements

This post takes text from the RogueBasin articles:

I have used the take from the above as I feel these are the best explanations of how the shadow casting technique works, and I can’t really improve upon them.

Categories: Tags:

## Sudoku Brute – a C# implementation of the Brute-force algorithm

December 20th, 2013 1 comment

The brute force algorithm is “dumb” method of solving a sudoku puzzle: it sequentially tries a potential solution for an unsolved cell and then moves onto the next and attempts to find a solution for that cell, and upon finding one will move onto the next and if a solution is not found, it steps back to the previous solved cell, selects a new solution and moves onto the next again. By doing this over and over, it can be guaranteed to find a solution for any valid sudoku puzzle. However, this can be time consuming with some of the more complex puzzles taking several minutes to solve.

I have written a C# application which implements the brute-force algorithm to solve Sudoku puzzles. It’s written using .Net 3.5 in Visual Studio 2008, and offers two different implementations of the brute-force algorithm – one uses arrays to hold data and the other using Linq to manipulate classes which hold data. Practically, they both use the same algorithm, just different methods of implementation. From my limited testing, they both take the same time to produce a solution for any grid; the inclusion of both was just me trying different technologies.

The app is pictured below and comes with fifty examples and allows one to add and save sudoku grids, and modify existing ones. To view an animated gif of the brute in action click here.

It’s  straight forwards to use and is controlled through the toolbar, whose functions left to right, are as follows:

1. New sudoku
3. Save an existing sudoku
4. Solved the current sudoku
6. Stop a solution attempt
7. Display screen updates – selecting yes will display the solution process in real time. Selecting this option will slow down the solution process.

In addition, there are two radio buttons allowing one to select the solution class – either a Linq or array based method.