/** * moves snake in a given direction */ public bool move() { erase(); if (!isBarrier((Cell)body [0])) { for (int i = body.Count - 1; i >= 0; i--) { Cell obj = (Cell)body [i]; if (isFood && i == body.Count - 1) { body.Add(new Cell(obj.getX(), obj.getY(), Constants.SNAKE_BODY)); } if (obj.getType().Equals(Constants.SNAKE_HEAD)) { switch (direction) { case (0): { obj.setY(obj.getY() - 1); break; } case (1): { obj.setX(obj.getX() + 1); break; } case (2): { obj.setY(obj.getY() + 1); break; } case (3): { obj.setX(obj.getX() - 1); break; } } } else { Cell previous = (Cell)body [i - 1]; obj.setX(previous.getX()); obj.setY(previous.getY()); } } drawSnake(); if (isFood) { isFood = false; placeFood(); } return(true); } return(false); }
/** * place new food on field */ private void placeFood() { Random random = new Random(); food = new Cell(0, 0, Constants.FOOD); food.setX(random.Next(Constants.FIELD_WIDTH - 10) + 5); food.setY(random.Next(Constants.FIELD_HEIGHT - 6) + 3); food.draw(); }