Last active
January 4, 2017 17:53
-
-
Save GER-NaN/b6f7d9b5d5aa8bb818dabebada4c22f6 to your computer and use it in GitHub Desktop.
Classes for handling points in a 2d Grid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
public class Grid | |
{ | |
public List<Tile> Tiles; | |
public int Width; | |
public int Height; | |
public Grid(int width, int height) | |
{ | |
Tiles = new List<Tile>(width * height); | |
Width = width; | |
Height = height; | |
} | |
public Tile TileAtPoint(int x, int y) | |
{ | |
return Tiles.FirstOrDefault(t => t.Point.X == x && t.Point.Y == y); | |
} | |
public override string ToString() | |
{ | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < Height; i++) | |
{ | |
for (int j = 0; j < Width; j++) | |
{ | |
Tile t = TileAtPoint(i, j); | |
sb.Append(t?.Item); | |
} | |
sb.Append(Environment.NewLine); | |
} | |
return sb.ToString(); | |
} | |
} | |
public class Tile | |
{ | |
public Point Point; | |
public string Item; | |
public Tile(Point p, string item) | |
{ | |
Point = p; | |
Item = item; | |
} | |
} | |
public class Point | |
{ | |
public int Y; | |
public int X; | |
public Point(int x, int y) | |
{ | |
X = x; | |
Y = y; | |
} | |
public int DistanceFrom(Point q) | |
{ | |
double dx = X - q.X; | |
double dy = Y - q.Y; | |
var dist = Math.Sqrt(dx * dx + dy * dy); | |
return (int)dist; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change Point to be struct and probably should use int here since its a grid.