1 module example.snake; 2 3 version(GAMEEXAMPLE){ 4 5 import gameentity; 6 import gamemap; 7 import game; 8 9 import nudsfml.graphics; 10 11 import std.stdio; 12 13 enum Direction{ 14 Up, 15 Down, 16 Left, 17 Right 18 } 19 20 Vector2f[Direction] dir; 21 22 class Snake { 23 SnakeEntity[] parts; 24 int len; 25 Direction direction; 26 Vector2i headPosition; 27 28 float updateTimer = .25;; 29 float updateInterval= .24; 30 31 int head = -1; 32 int tail = -1; 33 bool doAdd = false; 34 35 Game g; 36 37 this(Game game_){ 38 dir = [ Direction.Up : Vector2f(0, -1), 39 Direction.Down : Vector2f(0, 1), 40 Direction.Left : Vector2f(-1, 0), 41 Direction.Right : Vector2f(1, 0)]; 42 g = game_; 43 } 44 45 void generate(int length){ 46 this.len = len; 47 for(int i = 0; i < length; i++){ 48 auto p = new SnakeEntity(g.map.tex); 49 p.mapLocation = Vector2f(headPosition.x - i, headPosition.y); 50 parts ~= p; 51 } 52 53 foreach(ref part ; parts){ 54 g.map.addSnake(part); 55 } 56 57 writeln(parts.length); 58 59 direction = Direction.Right; 60 head = 0; 61 tail = length - 1; 62 } 63 64 65 void move(){ 66 int id = tail; 67 68 foreach(i ,ref part ; parts){ 69 if(i + 1 < parts.length){ 70 auto next = parts[i+1]; 71 part.mapLocation = next.mapLocation; 72 } else { 73 part.mapLocation = part.mapLocation + dir[direction]; 74 } 75 } 76 77 g.map.sortEntities; 78 } 79 80 bool canDirection(Direction dir){ 81 if (direction == Direction.Up && dir == Direction.Down) 82 return false; 83 if (direction == Direction.Down && dir == Direction.Up) 84 return false; 85 if (direction == Direction.Left && dir == Direction.Right) 86 return false; 87 if (direction == Direction.Right && dir == Direction.Left) 88 return false; 89 return true; 90 } 91 92 void update(float deltaTime){ 93 updateTimer -= deltaTime; 94 if(updateTimer < 0){ 95 updateTimer = updateInterval; 96 if(g.doMove) 97 move(); 98 } 99 } 100 101 102 SnakeEntity addPart(){ 103 auto part = new SnakeEntity(g.map.tex); 104 part.parentID = tail; 105 part.mapLocation = parts[parts.length-1].mapLocation; 106 part.id = len; 107 parts ~= part; 108 g.map.addSnake(part); 109 len++; 110 doAdd = false; 111 return part; 112 } 113 114 115 } 116 }