Beispiel #1
0
        /**
         * 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);
        }
Beispiel #2
0
        /**
         * check cell for obstruction
         */
        private bool isBarrier(Cell head)
        {
            int x;
            int y;

            x = head.getX();
            y = head.getY();
            if (x <= 1 || x >= Constants.FIELD_WIDTH - 1)
            {
                return(true);
            }
            else if (y <= 1 || y >= Constants.FIELD_HEIGHT - 1)
            {
                return(true);
            }
            else if (x == food.getX() && y == food.getY())
            {
                isFood = true;
            }
            foreach (Cell obj in body)
            {
                if (!obj.getType().Equals(Constants.SNAKE_HEAD))
                {
                    if (obj.getX() == x && obj.getY() == y)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }