betterchess

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

map.ha (900B)


      1 use fmt;
      2 
      3 export type map = (size, [][]*piece);
      4 
      5 const fakepiece = piece{x = 0, y = 0, ty = ptype::KING, team = color::WHITE, valid = &kingmove, moved = false, dead = false};
      6 
      7 // this function is a bit messy, but it provides a pretty good spread of values
      8 fn hash(x: i64, y: i64, buckets: size) size = (((x ^ y) * (x | y)) | x * y): size % buckets;
      9 
     10 fn addmap(m: *map, x: i64, y: i64, p: *piece) void = {
     11 	let i = hash(x, y, m.0);
     12 	append(m.1[i], p)!;
     13 };
     14 
     15 fn getmap(m: *map, x: i64, y: i64) (*piece | !empty) = {
     16 	let i = hash(x, y, m.0);
     17 	for (let p .. m.1[i]) {
     18 		if (p.x == x && p.y == y) 
     19 			return p;
     20 	};
     21 	return empty;
     22 };
     23 
     24 fn mkmap(buckets: size) *map = alloc((buckets, alloc([[]: []*piece...], buckets)!))!;
     25 
     26 fn finishmap(m: *map) void = {
     27 	free(m.1);
     28 };
     29 
     30 @test fn getmap() void = {
     31 	let m = mkmap(5);
     32 	defer finishmap(m);
     33 
     34 	addmap(m, 0, 0, &fakepiece);
     35 	assert(getmap(m, 0, 0) is *piece);
     36 };