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