Home > Software design >  Implementation of mapping Hexagons in functional programming and problems with Lists
Implementation of mapping Hexagons in functional programming and problems with Lists

Time:04-19

I'm looking to create a framework for creating board/strategy games like CIV in unity however I intend on testing the function in vanilla c# before I implement it so in order to create symmetrical hexagonal grids that look like the following

 __    __    __    __    __    __    __
/13\__/14\__/15\__/16\__/17\__/18\__/19\
\__/07\__/08\__/09\__/10\__/11\__/12\__/
/00\__/01\__/02\__/03\__/04\__/05\__/06\
\__/  \__/  \__/  \__/  \__/  \__/  \__/

I need to have every other row reduced by 1 so that moving in any direction is simply increasing or decreasing the index by 7, 13 or 6

My current issue is that my struct:

struct hexagon{
    public int xpos;
    public int ypos;
}

is as of my understanding not being understood by the class List and so my code:

int width = 7;
int height = 7;
int l = width*2-1;
int r = 1;

Func<int,int> xhex = i => ((i%l) < width) ? 2*(i%l) : 2*(i%l)-l;
Func<int,int> yhex = i => ((i%l) < width) ? 2*(i/l) : 2*(i/l) 1;

var grid = new List<hexagon> [width * height - height/2].Select((h,i)=>{
    h.xpos = xhex(i)*r*1.5;
    h.ypos = yhex(i)*r*0.8660; // sqrt(3/2)
    });

is throwing the error

'List' does not contain a definition for 'xpos' and no accessible extension method 'xpos' accepting a first argument of type 'List' could be found (are you missing a using directive or an assembly reference?) [Grid-Parse]

I'm also not really sure if the function Select will accept the index overload is there anything I can use that is just as elegant?

CodePudding user response:

I hope this solution would help u:

    struct hexagon
       {
         public int xpos;
         public int ypos;
       }


        int width = 7;
        int height = 7;
        int l = width * 2 - 1;
        int r = 1;
        int counterx = 0;
        int countery = 0;

        Func<int, int> xhex = i => ((i % l) < width) ? 2 * (i % l) : 2 * (i % l) - l;
        Func<int, int> yhex = i => ((i % l) < width) ? 2 * (i / l) : 2 * (i / l)   1;


        var grid = new List<hexagon>[width * height - height / 2].Select(h => new hexagon()
        {
            xpos = (int)(xhex(counterx  ) * r * 1.5),
            ypos = (int)(yhex(countery  ) * r * 0.8660)
        });

CodePudding user response:

It looks as though you're trying to initialise a sequence of hexagons. Use Enumerable.Range to generate a sequence of integers, and then Select to create the hexagons:

var grid = Enumerable.Range(0, width * height - height / 2)
    .Select(i => new Hexagon(xhex(i) * r * 1.5, yhex(i) * r * 0.8660));

This is assuming that Hexagon looks like this:

public struct Hexagon
{
    public double xpos;
    public double ypos;

    public Hexagon(double xpos, double ypos)
    {
        this.xpos = xpos;
        this.ypos = ypos;
    }
}
  • Related