Created
December 6, 2013 18:21
-
-
Save gmfawcett/7829710 to your computer and use it in GitHub Desktop.
initializing a board from a string, at compile-time
This file contains 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
enum COLOR : byte { BLANK, BLACK, WHITE }; | |
enum TYPE : byte { NA, MAN, KING }; | |
struct Piece { | |
COLOR color; TYPE type; | |
string toString() { | |
if (color == COLOR.BLANK) | |
return "."; | |
if (color == COLOR.WHITE) | |
return (type == TYPE.MAN) ? "w" : "W"; | |
else | |
return (type == TYPE.MAN) ? "b" : "B"; | |
} | |
} | |
enum W = 8, H = 8; | |
alias Board = Piece[H][W]; | |
Board initialize(dstring data) { | |
Board board; | |
foreach(r; 0..H) | |
foreach(c; 0..W) { | |
auto mark = data[r*W+c]; | |
if (mark == '.') | |
continue; | |
if (mark == 'b' || mark == 'B') | |
board[r][c].color = COLOR.BLACK; | |
if (mark == 'w' || mark == 'W') | |
board[r][c].color = COLOR.WHITE; | |
board[r][c].type = | |
(mark == 'W' || mark == 'B') ? TYPE.KING : TYPE.MAN; | |
} | |
return board; | |
} | |
void main() { | |
import std.stdio; | |
enum dstring data = | |
"ww..W..W" | |
"........" | |
"........" | |
"........" | |
"........" | |
"........" | |
"........" | |
"..b.BB.b"; | |
// we can evaluate at compile time! | |
enum Board board = initialize(data); | |
foreach(row; board) { | |
foreach(piece; row) | |
write(piece); | |
writeln(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment