Tick method
This commit is contained in:
+48
-1
@@ -10,7 +10,8 @@ public class SnakeLevel{
|
||||
Obstacle,
|
||||
Egg,
|
||||
Snake,
|
||||
SnakeHead
|
||||
SnakeHead,
|
||||
OutOfBounds
|
||||
}
|
||||
|
||||
public enum SnakeDirection{
|
||||
@@ -20,16 +21,23 @@ public class SnakeLevel{
|
||||
Right
|
||||
}
|
||||
|
||||
public enum GameState{
|
||||
Running,
|
||||
Dead
|
||||
}
|
||||
|
||||
private readonly List<Point> _obstacles;
|
||||
public ReadOnlyCollection<Point> Obstacles => _obstacles.AsReadOnly();
|
||||
public Point SnakeHead {get; private set;}
|
||||
private readonly List<Point> _snake;
|
||||
// Head is not in snake
|
||||
// Last is closest to the head
|
||||
public ReadOnlyCollection<Point> Snake => _snake.AsReadOnly();
|
||||
public int SnakeLength => Snake.Count + 1;
|
||||
private readonly List<Point> _eggs;
|
||||
public ReadOnlyCollection<Point> Eggs => _eggs.AsReadOnly();
|
||||
public SnakeDirection SnakeHeadDirection {get; private set;}
|
||||
public GameState State {get; private set;}
|
||||
|
||||
public SnakeLevel(int size, IEnumerable<Point> obstacles, int snake_start_length){
|
||||
this.Size = size;
|
||||
@@ -55,9 +63,48 @@ public class SnakeLevel{
|
||||
return LevelBlock.Snake;
|
||||
}else if(_eggs.Contains(p)){
|
||||
return LevelBlock.Egg;
|
||||
}else if(p.X < 0 || p.Y < 0 || p.X>=Size || p.Y >= Size){
|
||||
return LevelBlock.OutOfBounds;
|
||||
}
|
||||
|
||||
return LevelBlock.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public void Tick(){
|
||||
Point new_snake_head = (0,0);
|
||||
switch(SnakeHeadDirection){
|
||||
case SnakeDirection.Up:
|
||||
new_snake_head = (SnakeHead.X, SnakeHead.Y - 1);
|
||||
break;
|
||||
case SnakeDirection.Down:
|
||||
new_snake_head = (SnakeHead.X, SnakeHead.Y + 1);
|
||||
break;
|
||||
case SnakeDirection.Left:
|
||||
new_snake_head = (SnakeHead.X - 1, SnakeHead.Y);
|
||||
break;
|
||||
case SnakeDirection.Right:
|
||||
new_snake_head = (SnakeHead.X + 1, SnakeHead.Y);
|
||||
break;
|
||||
}
|
||||
|
||||
if(this[new_snake_head] is LevelBlock.Obstacle or LevelBlock.Snake or LevelBlock.OutOfBounds){
|
||||
State = GameState.Dead;
|
||||
return;
|
||||
}
|
||||
|
||||
var first = Snake[0];
|
||||
|
||||
for(int i=_snake.Count-1; i>0; i--){
|
||||
_snake[i-1] = _snake[i];
|
||||
}
|
||||
_snake[^1] = SnakeHead;
|
||||
|
||||
if(this[new_snake_head] is LevelBlock.Egg){
|
||||
_snake.Insert(0, first);
|
||||
_eggs.Remove(new_snake_head);
|
||||
}
|
||||
|
||||
SnakeHead = new_snake_head;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user