PageRenderTime 28ms CodeModel.GetById 14ms app.highlight 11ms RepoModel.GetById 2ms app.codeStats 0ms

/examples/Snake/snake.d

http://github.com/wilkie/djehuty
D | 118 lines | 90 code | 28 blank | 0 comment | 10 complexity | c21d33a7205b133993b23a6c1daec9e9 MD5 | raw file
  1import djehuty;
  2
  3import posn;
  4
  5enum MoveResult {
  6	Ok,
  7	CollisionSelf,
  8}
  9
 10class Snake {
 11	this(uint max_x, uint max_y, Dir d) {
 12		Posn.SetBounds(max_x, max_y);
 13
 14		_max_x = max_x;
 15		_max_y = max_y;
 16
 17		direction = d;
 18
 19		_max_length = max_x * max_y / 2;
 20
 21		_segments = new List!(Posn);
 22		_segments.add(new Posn(max_x/2, max_y/2));
 23	}
 24
 25	Snake dup() {
 26		Snake ret = new Snake(_max_x, _max_y, direction);
 27		ret._segments = _segments.dup;
 28		return ret;
 29	}
 30
 31	void direction(Dir d) {
 32		_direction = d;
 33	}
 34
 35	Dir direction() {
 36		return _direction;
 37	}
 38
 39	Posn[] segments() {
 40		return _segments.array();
 41	}
 42
 43	Posn head() {
 44		return first(segments);
 45	}
 46
 47	Posn neck() {
 48		return second(segments);
 49	}
 50
 51	Posn[] torso() {
 52		return rest(segments);
 53	}
 54
 55	Posn tail() {
 56		return last(segments);
 57	}
 58
 59	bool isVertical() {
 60		return direction == Dir.Up || direction == Dir.Down;
 61	}
 62
 63	uint length() {
 64		return _segments.length();
 65	}
 66
 67	void reverse() {
 68		_segments = _segments.reverse();
 69	}
 70
 71	void elongate(uint num = 1) {
 72		for (; length < _max_length && num > 0; num--)
 73			_segments.add(tail.dup());
 74	}
 75
 76	int opEquals(Posn p) {
 77		foreach (Posn s; torso)
 78			if (s == p)
 79				return 1;
 80		return 0;
 81	}
 82
 83	MoveResult slither() {
 84		foreach_reverse (uint i, Posn s; torso)
 85			s.moveTo(_segments[i]);
 86
 87		switch (_direction) {
 88			case Dir.Up:
 89				head.y = head.y - 1;
 90				break;
 91			case Dir.Down:
 92				head.y = head.y + 1;
 93				break;
 94			case Dir.Left:
 95				head.x = head.x - 1;
 96				break;
 97			case Dir.Right:
 98				head.x = head.x + 1;
 99				break;
100			default:
101				break;
102		}
103
104		if (this == head)
105			return MoveResult.CollisionSelf;
106
107		return MoveResult.Ok;
108	}
109
110private:
111	uint _max_x, _max_y;
112	uint _max_length;
113
114	Dir _direction;
115
116	List!(Posn) _segments;
117}
118