示例#1
11
        public static void Main(string[] args)
        {
            Console.WindowWidth = ConsoleWidth;
            Console.WindowHeight = ConsoleHeight;
            Console.BufferHeight = Console.WindowHeight;
            Console.BufferWidth = Console.WindowWidth;
            Console.CursorVisible = false;

            KeyboardControls keyboard = new KeyboardControls();
            keyboard.OnLeftPress += HandleOnLeftPress;
            keyboard.OnRightPress += HandleOnRightPress;
            keyboard.OnUpPress += HandleOnUpPress;
            keyboard.OnDownPress += HandleOnDownPress;
            keyboard.OnEscape += HandleOnEscape;

            bool placeFood = false;
            Food food = new Food(RandomNumber.Generate(0, ConsoleWidth), RandomNumber.Generate(0, ConsoleHeight), '+');

            while (runGame)
            {
                Console.Clear();
                keyboard.ProcessInput();
                snake.Draw();
                snake.Update();

                food.Draw();
                if (placeFood)
                {
                    food = new Food(RandomNumber.Generate(0, ConsoleWidth), RandomNumber.Generate(0, ConsoleHeight), '+');
                    placeFood = false;
                }

                if (food.Position.X == snake.Body[0].Position.X && food.Position.Y == snake.Body[0].Position.Y)
                {
                    Console.Beep();
                    snake.AddBodyPart();
                    placeFood = true;
                }

                if (snake.Body[0].Position.X < 0 ||
                    snake.Body[0].Position.X >= ConsoleWidth ||
                    snake.Body[0].Position.Y < 0 ||
                    snake.Body[0].Position.Y >= ConsoleHeight)
                {
                    runGame = false;
                }

                for (int i = 1; i < snake.Body.Count; i++)
                {
                    if (snake.Body[0].Position.X == snake.Body[i].Position.X && snake.Body[0].Position.Y == snake.Body[i].Position.Y)
                    {
                        runGame = false;
                        break;
                    }
                }

                Thread.Sleep(ThreadSpeed);
            }

            Console.WriteLine("Thanks for playing");
        }
示例#2
10
文件: Form1.cs 项目: Froggy293/Snake
 private void Restart()
 {
     gameLoop.Stop();
     graphics.Clear(SystemColors.Control);
     snake = new Snake();
     food = new Food(rand);
     direction = 0;
     score = 1;
     lblMenu.Visible = true;
     this.Text = "Snake";
 }
示例#3
6
文件: Game1.cs 项目: zawata/Snake
 protected override void Initialize()
 {
     base.Initialize();
     spriteBatch = new SpriteBatch(GraphicsDevice);
     Screen.setScreen();
     food = new Food(GraphicsDevice, Screen.Size);
 }
示例#4
6
        internal void Eat(Food result)
        {
            var lastBodyPartDirectionX = (SnakeBody[SnakeBody.Count - 2].X - SnakeBody[SnakeBody.Count - 1].X) / BodyPartSize;
            var lastBodyPartDirectionY = (SnakeBody[SnakeBody.Count - 2].Y - SnakeBody[SnakeBody.Count - 1].Y) / BodyPartSize;

            for (int i = 0; i < result.Bounty; i++)
            {
                SnakeBody.Add(
                    new BodyPart()
                    {
                        X = SnakeBody[SnakeBody.Count - 1].X * BodyPartSize * (-1) * lastBodyPartDirectionX,
                        Y = SnakeBody[SnakeBody.Count - 1].Y * BodyPartSize * (-1) * lastBodyPartDirectionY
                    });
            }
        }
示例#5
6
 public GameField()
 {
     snake = new Snake();
     food = new Food();
     snake.makeSnakeHead();
 }
示例#6
6
 //initial the game
 public void Initialize()
 {
     inputControllerP1 = new InputController(Keys.A, Keys.D, Keys.W, Keys.S);
     inputControllerP2 = new InputController(Keys.Left, Keys.Right, Keys.Up, Keys.Down);
     snake = new Snake(inputControllerP1,Resources.tail2);
     food = new Food();
     foodCount = 0;
     timeCount = 0;
 }
示例#7
5
        //Adding food in randome places
        private void FoodCreate(ref Ellipse food, ref Food foodObject)
        {
            double x, y;
            Size size = foodSize;
            Random randomNumber = new Random();
            food = new Ellipse();
            food.Fill = GenerateColor();
            food.Width = size.Width;
            food.Height = size.Height;
            //generating random coordinates while there is a free place for the food
            do
            {
                x = randomNumber.Next(0, (int)(playGroundSize.Width - size.Width) + 1);
                y = randomNumber.Next(0, (int)(playGroundSize.Height - size.Height) + 1);
            } while (!IsFree(x, y, size, 0));

            playField.Children.Add(food);
            Canvas.SetTop(food, y);
            Canvas.SetLeft(food, x);
            //creating food object
            foodObject = new Food(food, new Point(x, y));
            foodCollection.Add(foodObject, 0);
        }
示例#8
4
文件: Game.cs 项目: umit9k/PT2016
        public static void Init()
        {
            isActive = true;
            snake = new Snake();
            food = new Food();
            wall = new Wall();

            snake.body.Add(new Point { x = 15, y = 14 });
            food.body.Add(new Point { x = 14, y = 15 });

            food.color = ConsoleColor.Blue;
            wall.color = ConsoleColor.Green;
            snake.color = ConsoleColor.Yellow;

            Console.SetWindowSize(48, 19);
        }
示例#9
4
        //when snake eat food and generate a new one
        public void foodCollision(Snake snake)
        {
            bool flag = snake.Collision(food.Position.X, food.Position.Y, snake.Head);
            if (flag)
            {
                snake.BodyGrow();
                score += 1;

                foodCount++;
                do
                {
                    food = new Food();

                } while (snake.Collision(food.Position.X, food.Position.Y, snake.Head));
            }
        }
示例#10
3
        public bool Move(int dx, int dy, Food food)
        {

            if (body[0].x + dx == food.location.x && body[0].y + dy == food.location.y) //Если голова змейки коснулась 
            {                                                                          //еды, то увеличиваем её тело
                AddNewElement(body[0].x + dx, body[0].y + dy);
                return true;
            }

            ChangeBodyLocation(body[0].x + dx, body[0].y + dy);   //Иначе, просто двигаем змейку
            return false;
        }
示例#11
3
 public void CreateFood(GameObjects gameObjects, int count)
 {
     int createdFood = 0;
     while(createdFood < count)
     {
         Food food = new Food(sym);
         food.CreatFood();
         // Если еда не пересецается ни с одним из других объектов, то отрисуем их
         if (!gameObjects.Intersect(food) && !Intersect(food))
         {
             this.gameObjects.Add(food);
             food.Draw();
             createdFood++;
         }
     }
 }
示例#12
3
 //Food's lifetime, at the end (when this food is not needed anymore)
 //calling FoodRemove method
 private void FoodLifeTime(Food foodObject)
 {
     Random randomNumber = new Random();
     //generating randome food life time in seconds
     int lifeTime = randomNumber.Next(((int)speed) / 6, ((int)speed) / 6 + ((int)speed) / 6);
     //while the food time havent ended
     for (int i = 0; i < lifeTime; i++)
     {
         Thread.Sleep(1000);
         if (foodCollection.ContainsKey(foodObject))
         {
             foodCollection[foodObject]++;
         }
     }
     field.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
     {
         FoodRemove(foodObject);
     }));
 }
示例#13
2
文件: Arena.cs 项目: qizhiyu/Snake
        public Arena(int width, int height)
        {
            Width = width;
            Height = height;

            Cells = new Food[width, height];

            Snake = new SnakeModel(this);
        }
示例#14
2
 //removing food
 private void FoodRemove(Food foodObject)
 {
     playField.Children.Remove(foodObject.FoodObject);
     foodCollection.Remove(foodObject);
 }
示例#15
0
文件: Form1.cs 项目: Froggy293/Snake
 public formMain()
 {
     InitializeComponent();
     snake = new Snake();
     food = new Food(rand);
     gameLoop.Interval = 55;
     gameLoop.Tick += Update;
 }
示例#16
0
        public void OpenMenu()
        {
            int           cursor = 0;
            List <string> menu   = new List <string>();

            menu.Add("Start game");
            menu.Add("Exit");
            while (true)
            {
                for (int i = 0; i < 2; i++)
                {
                    if (i == cursor)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkCyan;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                    }
                    Console.WriteLine(menu[i]);
                }
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key == ConsoleKey.UpArrow)
                {
                    cursor--;
                }
                if (key.Key == ConsoleKey.DownArrow)
                {
                    cursor++;
                }
                if (cursor == -1)
                {
                    cursor = 1;
                }
                if (cursor == 2)
                {
                    cursor = 0;
                }
                Console.Clear();
                for (int i = 0; i < 2; i++)
                {
                    if (i == cursor)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkCyan;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                    }
                    Console.WriteLine(menu[i]);
                }
                Console.Clear();
                if (key.Key == ConsoleKey.Enter)
                {
                    if (cursor == 1)
                    {
                        break;
                    }
                    if (cursor == 0)
                    {
                        x        = 1; y = 0; sc = 0; levelCount = 1; score = 0;
                        wall     = new Wall();
                        snake    = new Snake();
                        playGame = true; moovable = false;
                        food     = new Food();
                        Thread t = new Thread(MoveSnakeThread);
                        t.Start();
                        while (true)
                        {
                            ConsoleKeyInfo k = new ConsoleKeyInfo();
                            k = Console.ReadKey();
                            if (k.Key == ConsoleKey.Escape)
                            {
                                break;
                            }
                            if ((k.Key == ConsoleKey.UpArrow || k.Key == ConsoleKey.W))
                            {
                                y = -1;
                                x = 0;
                            }
                            if ((k.Key == ConsoleKey.DownArrow || k.Key == ConsoleKey.S))
                            {
                                y = 1;
                                x = 0;
                            }
                            if ((k.Key == ConsoleKey.LeftArrow || k.Key == ConsoleKey.A))
                            {
                                x = -1;
                                y = 0;
                            }
                            if (k.Key == ConsoleKey.RightArrow || k.Key == ConsoleKey.D)
                            {
                                x = 1;
                                y = 0;
                            }
                        }
                        Console.Clear();
                        playGame = false;
                    }
                }
            }
        }
示例#17
0
        public static void Init()
        {
            exit  = Over = false;
            pause = true;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("ENTER YOUR USERNAME: "******"Please enter a non-empty username with no more than 16 letters!";

            while (username.Length > 16 || username.Length == 0)
            {
                if (wrongForFirstTime)
                {
                    Console.WriteLine(message);
                    wrongForFirstTime = false;
                }
                Console.SetCursorPosition(21, 0);

                for (int i = 0; i < username.Length; i++)
                {
                    Console.Write(' ');
                }

                Console.SetCursorPosition(21, 0);
                username = Console.ReadLine();
            }

            string        path      = @"C:\snake game\usernames\" + username + "\\saves";
            DirectoryInfo directory = new DirectoryInfo(path);

            Console.ForegroundColor = ConsoleColor.Cyan;

            List <string> options = new List <string>();

            options.Add("New game");
            if (directory.Exists && directory.GetDirectories().Length > 0)
            {
                options.Add("Load game");
            }
            if (new FileInfo(@"C:\snake game\usernames\" + username + "\\highscores.txt").Exists)
            {
                options.Add("List of highscores");
            }
            options.Add("Exit");
            int option = 0;

            while (true)
            {
                bool resumeCycle = false;

                while (true)
                {
                    Console.Clear();
                    Console.WriteLine("MAIN MENU\n");
                    for (int i = 0; i < options.Count; i++)
                    {
                        Console.BackgroundColor = i == option ? ConsoleColor.White : ConsoleColor.Black;
                        Console.WriteLine(options[i]);
                    }

                    ConsoleKey key = Console.ReadKey(true).Key;
                    switch (key)
                    {
                    case ConsoleKey.UpArrow:
                        if (option > 0)
                        {
                            option--;
                        }
                        break;

                    case ConsoleKey.DownArrow:
                        if (option < options.Count - 1)
                        {
                            option++;
                        }
                        break;
                    }

                    if (key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }

                if (options[option] == "Load game")
                {
                    Console.Clear();
                    string saveName;
                    Console.WriteLine("Load game\n");

                    DirectoryInfo   dir  = new DirectoryInfo(path);
                    DirectoryInfo[] dirs = dir.GetDirectories();

                    for (int i = 0; i < dirs.Length; i++)
                    {
                        for (int j = i + 1; j < dirs.Length; j++)
                        {
                            if (dirs[i].CreationTime < dirs[j].CreationTime)
                            {
                                DirectoryInfo d = dirs[j];
                                dirs[j] = dirs[i];
                                dirs[i] = d;
                            }
                        }
                    }

                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    for (int i = 0; i < dirs.Length; i++)
                    {
                        Console.WriteLine(dirs[i].Name);
                    }
                    int saveNum = 0;

                    while (true)
                    {
                        Console.SetCursorPosition(0, 2 + saveNum);
                        Console.BackgroundColor = ConsoleColor.White;
                        Console.WriteLine(dirs[saveNum]);

                        int        prevSaveNum = saveNum;
                        ConsoleKey key         = Console.ReadKey(true).Key;
                        switch (key)
                        {
                        case ConsoleKey.UpArrow:
                            if (saveNum > 0)
                            {
                                saveNum--;
                            }
                            break;

                        case ConsoleKey.DownArrow:
                            if (saveNum < dirs.Length - 1)
                            {
                                saveNum++;
                            }
                            break;
                        }

                        if (key == ConsoleKey.Enter)
                        {
                            break;
                        }

                        Console.SetCursorPosition(0, 2 + prevSaveNum);
                        Console.BackgroundColor = ConsoleColor.Black;
                        Console.WriteLine(dirs[prevSaveNum]);
                    }

                    saveName = dirs[saveNum].Name;

                    Console.Clear();

                    path += "\\" + saveName;

                    string fSnake = path + "\\snake.xml";
                    string fWall  = path + "\\wall.xml";
                    string fFood  = path + "\\food.xml";

                    FileStream fs = new FileStream(fSnake, FileMode.Open);
                    snake = new XmlSerializer(typeof(Snake)).Deserialize(fs) as Snake;
                    fs.Close();

                    fs   = new FileStream(fWall, FileMode.Open);
                    wall = new XmlSerializer(typeof(Wall)).Deserialize(fs) as Wall;
                    fs.Close();

                    fs   = new FileStream(fFood, FileMode.Open);
                    food = new XmlSerializer(typeof(Food)).Deserialize(fs) as Food;
                    fs.Close();

                    Console.BackgroundColor = ConsoleColor.Black;
                }

                else if (options[option] == "New game")
                {
                    DirectoryInfo dir = new DirectoryInfo(@"C:\Snake Game\usernames\" + username);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }

                    FileStream   highscore = new FileStream(dir.FullName + @"\highscores.txt", FileMode.OpenOrCreate);
                    StreamReader sr        = new StreamReader(highscore);
                    string       line      = sr.ReadLine();
                    sr.Close();

                    if (line == null)
                    {
                        StreamWriter sw = new StreamWriter(dir.FullName + @"\highscores.txt");
                        sw.Write("1)  " + 0);
                        sw.Close();
                    }
                    highscore.Close();

                    snake = new Snake(username);
                    wall  = new Wall();
                    food  = new Food();
                }

                else if (options[option] == "List of highscores")
                {
                    Console.Clear();
                    string       hsPath = @"C:\snake game\usernames\" + username + "\\highscores.txt";
                    StreamReader sr     = new StreamReader(hsPath);
                    Console.Write(sr.ReadToEnd());
                    sr.Close();

                    while (Console.ReadKey(true).Key != ConsoleKey.Escape)
                    {
                    }

                    resumeCycle = true;
                }
                else if (options[option] == "Exit")
                {
                    exit = true;
                }
                if (!resumeCycle)
                {
                    break;
                }
            }
        }
示例#18
0
 private static void DrawFood(Food food)
 {
     Console.SetCursorPosition(food.X + 1, food.Y + 1);
     Console.Write("F");
 }
示例#19
0
        public static void Main(string[] args)
        {
            // console settings
            Console.InputEncoding  = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;

            // Body[] snake;
            ArrayList  snake = new ArrayList();
            Point      center;
            Vector     v     = new Vector(0, 0);
            ConsoleKey k     = ConsoleKey.F24;
            long       score = 0;
            bool       end   = false;
            bool       retry = false;

            int wSize;

            do
            {
                Console.Write("Game size (square): ");
                wSize = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter a number bigger than 50!");
            } while (wSize < 50);
            Console.Clear();

            int xMax = wSize;
            int yMax = wSize / 2;

            Console.SetWindowSize(xMax + 20, yMax);
            Console.Clear();
            Console.CursorVisible = false;

            Board b = new Board(xMax, yMax);
            Food  f = new Food(xMax, yMax);

            f.New();
            f.Show();

            center = new Point(xMax / 2, yMax / 2); // center point of game

            snake.Add(new Body(center, true));      // head; first index

            while (true)
            {
                if (!end)
                {
                    foreach (Body s in snake)
                    {
                        if (s != null)
                        {
                            s.Show();
                        }
                    }
                }

                ArrayList body = snake.GetRange(1, snake.Count - 1);
                foreach (Body bd in body)
                {
                    if (bd.pos == (snake[0] as Body).pos)
                    {
                        end = true;
                        break;
                    }
                }


                if (f.FoodEaten((snake[0] as Body).pos))
                {
                    f.New();
                    score++;
                    snake.Add(new Body(Point.Subtract((snake[(int)score - 1] as Body).pos, v)));
                }
                f.Show();

                while (Console.KeyAvailable)
                {
                    k = Console.ReadKey(true).Key;
                }
                switch (k)
                {
                case ConsoleKey.W:
                    if ((snake[0] as Body).pos.Y < 2)
                    {
                        end = true;
                    }
                    else
                    {
                        v = new Vector(0, -1);
                    }
                    break;

                case ConsoleKey.S:
                    if ((snake[0] as Body).pos.Y > yMax - 3)
                    {
                        end = true;
                    }
                    else
                    {
                        v = new Vector(0, 1);
                    }
                    break;

                case ConsoleKey.A:
                    if ((snake[0] as Body).pos.X < 2)
                    {
                        end = true;
                    }
                    else
                    {
                        v = new Vector(-1, 0);
                    }
                    break;

                case ConsoleKey.D:
                    if ((snake[0] as Body).pos.X > xMax - 3)
                    {
                        end = true;
                    }
                    else
                    {
                        v = new Vector(1, 0);
                    }
                    break;

                case ConsoleKey.Q:
                    end = true;
                    break;
                }

                if (!end)
                {
                    Thread.Sleep(200);
                    foreach (Body s in snake)
                    {
                        if (s != null)
                        {
                            s.Clear();
                        }
                    }
                    for (int i = snake.Count - 1; i > 0; i--)
                    {
                        if (snake[i] != null && snake[i - 1] != null)
                        {
                            (snake[i] as Body).pos = (snake[i - 1] as Body).pos;
                        }
                    }
                    (snake[0] as Body).Move(v);
                }
                else if (end)
                {
                    Console.Clear();
                    Console.WriteLine("You lost!");
                    Console.WriteLine($"Score: {score}");
                    break;
                }
            }
            Console.ReadKey(true);
        }
示例#20
0
 public void Start()
 {
     snake = new Snake();
     food  = new Food();
     wall  = new Wall(level);
 }
示例#21
0
        public static int ChooseDir(DL.Snake snake, Food food)
        {
            if (lastOptions.Count > 0 && Game.alive)
            {
                Situation situation = GetSituationByOptions(lastOptions);
                if (situation != null)
                {
                    Situation tmpSit = Situations[Situations.IndexOf(situation)];
                    foreach (Tuple <int, int> tmp in tmpSit.Options)
                    {
                        if (tmp.Item1 == lastdir)
                        {
                            Situations[Situations.IndexOf(situation)].Options[Situations[Situations.IndexOf(situation)].Options.IndexOf(tmp)] = new Tuple <int, int>(lastdir, tmp.Item2 + 1);
                            break;
                        }
                    }
                }
            }
            Random rnd = new Random();

            if (nextdir >= 0)
            {
                //randomChange++;
                int tmp = nextdir;
                nextdir = -1;
                lastdir = tmp;
                logging(tmp, -1, null);
                return(tmp);
            }

            List <int> Options = new List <int> {
                0, 1, 2, 3
            };
            int dir = 0;

            if (lastdir == 0)
            {
                Options.Remove(2);
            }
            else if (lastdir == 1)
            {
                Options.Remove(3);
            }
            else if (lastdir == 2)
            {
                Options.Remove(0);
            }
            else if (lastdir == 3)
            {
                Options.Remove(1);
            }

            for (int i = 1; i < snake.Elements.Count; i++)
            {
                //if(!((snake.Elements[i].PosX - snake.Elements[0].PosX) < Globals.Width  +1 && (((snake.Elements[i].PosY - snake.Elements[0].PosY) < Globals.Width && (snake.Elements[i].PosY - snake.Elements[0].PosY) > 0) || ((snake.Elements[0].PosY - snake.Elements[i].PosY) < Globals.Width && (snake.Elements[0].PosY - snake.Elements[i].PosY) > 0 ))))
                //{
                //    Options.Remove(0);
                //}
                //if (!((snake.Elements[i].PosY - snake.Elements[0].PosY) < Globals.Width +1 && (((snake.Elements[i].PosX - snake.Elements[0].PosX) < Globals.Width && (snake.Elements[i].PosX - snake.Elements[0].PosX) > 0) || ((snake.Elements[0].PosX - snake.Elements[i].PosX) < Globals.Width && (snake.Elements[0].PosX - snake.Elements[i].PosX) > 0))))
                //{
                //    Options.Remove(1);
                //}
                //if(!((snake.Elements[0].PosX - snake.Elements[i].PosX) < Globals.Width  +1 && (((snake.Elements[i].PosY - snake.Elements[0].PosY) < Globals.Width && (snake.Elements[i].PosY - snake.Elements[0].PosY) > 0) || ((snake.Elements[0].PosY - snake.Elements[i].PosY) < Globals.Width && (snake.Elements[0].PosY - snake.Elements[i].PosY) > 0))))
                //{
                //    Options.Remove(2);
                //}
                //if(!((snake.Elements[0].PosY - snake.Elements[i].PosY) < Globals.Width +1 && (((snake.Elements[i].PosX - snake.Elements[0].PosX) < Globals.Width && (snake.Elements[i].PosX - snake.Elements[0].PosX) > 0) || ((snake.Elements[0].PosX - snake.Elements[i].PosX) < Globals.Width && (snake.Elements[0].PosX - snake.Elements[i].PosX) > 0))))
                //{
                //    Options.Remove(3);
                //}

                if (snake.Elements[0].PosX > snake.Elements[i].PosX)
                {
                    if (snake.Elements[0].PosY == snake.Elements[i].PosY)
                    {
                        if (snake.Elements[0].PosX - snake.Elements[i].PosX == Globals.Width + 1)
                        {
                            Options.Remove(2);
                        }
                    }
                }
                else if (snake.Elements[0].PosX == snake.Elements[i].PosX)
                {
                }
                else
                {
                    if (snake.Elements[0].PosY == snake.Elements[i].PosY)
                    {
                        if (snake.Elements[i].PosX - snake.Elements[0].PosX == Globals.Width + 1)
                        {
                            Options.Remove(0);
                        }
                    }
                }
                if (snake.Elements[0].PosY > snake.Elements[i].PosY)
                {
                    if (snake.Elements[0].PosX == snake.Elements[i].PosX)
                    {
                        if (snake.Elements[0].PosY - snake.Elements[i].PosY == Globals.Width + 1)
                        {
                            Options.Remove(3);
                        }
                    }
                }
                else if (snake.Elements[0].PosY == snake.Elements[i].PosY)
                {
                }
                else
                {
                    if (snake.Elements[0].PosX == snake.Elements[i].PosX)
                    {
                        if (snake.Elements[i].PosY - snake.Elements[0].PosY <= Globals.Width + 1)
                        {
                            Options.Remove(1);
                        }
                    }
                }
            }

            //if (food.posX > snake.Elements[0].PosX && Options.Contains(0))
            //{
            //    dir = 0;
            //}
            //else if (food.posY > snake.Elements[0].PosY && Options.Contains(1))
            //{
            //    dir = 1;
            //}
            //else if (food.posX < snake.Elements[0].PosX && Options.Contains(2))
            //{
            //    dir = 2;
            //}
            //else if (food.posY < snake.Elements[0].PosY && Options.Contains(3))
            //{
            //    dir = 3;
            //}
            //else
            //{

            //    if (Options.Contains(lastdir - 1))
            //    {
            //        dir = lastdir - 1;
            //        //nextdir = dir - 1;
            //    }
            //    else if (Options.Contains(lastdir + 1))
            //    {
            //        dir = lastdir + 1;
            //        //nextdir = dir + 1;
            //    }
            //    else if (Options.Contains(lastdir))
            //    {
            //        dir = lastdir;
            //        //nextdir = dir + 1;
            //    }
            //    else
            //    {
            //        //dir = Options[rnd.Next(0, Options.Count)];
            //    }
            //}
            if (Options.Count > 1)
            {
                Situation mySituation = GetSituationByOptions(Options);
                if (food.posX >= snake.Elements[0].PosX && food.posY >= snake.Elements[0].PosY)
                {
                    if ((food.posX - snake.Elements[0].PosX) > (food.posY - snake.Elements[0].PosY))
                    {
                        if (Options.Contains(0))
                        {
                            dir = 0;
                            logging(dir, 1, Options);
                        }
                        else if (Options.Contains(1))
                        {
                            dir = 1;
                            logging(dir, 2, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else if ((food.posX - snake.Elements[0].PosX) < (food.posY - snake.Elements[0].PosY))
                    {
                        if (Options.Contains(1))
                        {
                            dir = 1;
                            logging(dir, 3, Options);
                        }
                        else if (Options.Contains(0))
                        {
                            dir = 0;
                            logging(dir, 4, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //nextdir = dir;
                            //dir = Options[rnd.Next(0, Options.Count)];
                            logging(dir, 0, Options);
                        }
                    }
                    else
                    {
                        //dir = Options[rnd.Next(0, Options.Count)];
                        //nextdir = dir;
                        logging(dir, 0, Options);
                    }
                }
                else if (food.posX >= snake.Elements[0].PosX && food.posY <= snake.Elements[0].PosY)
                {
                    if ((food.posX - snake.Elements[0].PosX) > (snake.Elements[0].PosY - food.posY))
                    {
                        if (Options.Contains(0))
                        {
                            dir = 0;
                            logging(dir, 5, Options);
                        }
                        else if (Options.Contains(3))
                        {
                            dir = 3;
                            logging(dir, 6, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else if ((food.posX - snake.Elements[0].PosX) < (snake.Elements[0].PosY - food.posY))
                    {
                        if (Options.Contains(3))
                        {
                            dir = 3;
                            logging(dir, 7, Options);
                        }
                        else if (Options.Contains(0))
                        {
                            dir = 0;
                            logging(dir, 8, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else
                    {
                        dir = mySituation.GetBestDir();
                        //dir = Options[rnd.Next(0, Options.Count)];
                        //nextdir = dir;
                        logging(dir, 0, Options);
                    }
                }
                else if (food.posX <= snake.Elements[0].PosX && food.posY >= snake.Elements[0].PosY)
                {
                    if ((snake.Elements[0].PosX - food.posX) > (food.posY - snake.Elements[0].PosY))
                    {
                        if (Options.Contains(2))
                        {
                            dir = 2;
                            logging(dir, 9, Options);
                        }
                        else if (Options.Contains(1))
                        {
                            dir = 1;
                            logging(dir, 10, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else if ((snake.Elements[0].PosX - food.posX) < (food.posY - snake.Elements[0].PosY))
                    {
                        if (Options.Contains(1))
                        {
                            dir = 1;
                            logging(dir, 11, Options);
                        }
                        else if (Options.Contains(2))
                        {
                            dir = 2;
                            logging(dir, 12, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else
                    {
                        dir = mySituation.GetBestDir();
                        //dir = Options[rnd.Next(0, Options.Count)];
                        //nextdir = dir;
                        logging(dir, 0, Options);
                    }
                }
                else if (food.posX <= snake.Elements[0].PosX && food.posY <= snake.Elements[0].PosY)
                {
                    if ((snake.Elements[0].PosX - food.posX) > (snake.Elements[0].PosY - food.posY))
                    {
                        if (Options.Contains(2))
                        {
                            dir = 2;
                            logging(dir, 13, Options);
                        }
                        else if (Options.Contains(3))
                        {
                            dir = 3;
                            logging(dir, 14, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else if ((snake.Elements[0].PosX - food.posX) < (snake.Elements[0].PosY - food.posY))
                    {
                        if (Options.Contains(3))
                        {
                            dir = 3;
                            logging(dir, 14, Options);
                        }
                        else if (Options.Contains(2))
                        {
                            dir = 2;
                            logging(dir, 15, Options);
                        }
                        else
                        {
                            dir = mySituation.GetBestDir();
                            //dir = Options[rnd.Next(0, Options.Count)];
                            //nextdir = dir;
                            logging(dir, 0, Options);
                        }
                    }
                    else
                    {
                        dir = mySituation.GetBestDir();
                        //dir = Options[rnd.Next(0, Options.Count)];
                        //nextdir = dir;
                        logging(dir, 0, Options);
                    }
                }
                else
                {
                    dir = mySituation.GetBestDir();
                    logging(dir, 0, Options);
                }
                if (rnd.Next(0, 100) < randomChange)
                {
                    dir = Options[rnd.Next(0, Options.Count)];
                    logging(dir, 999, Options);
                }
            }
            else if (Options.Count == 1)
            {
                dir = Options[0];
            }



            lastOptions = Options;
            lastdir     = dir;
            return(dir);
        }
示例#22
0
文件: Form1.cs 项目: Dafiruz/Snake
        private void Snake_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.W:
            case Keys.Up:
                if (last_direction != "down" && snake.GetY(0) >= max_up)
                {
                    snake.move("up");
                    last_direction = "up";
                }
                break;

            case Keys.A:
            case Keys.Left:
                if (last_direction != "right" && snake.GetX(0) >= max_left)
                {
                    snake.move("left");
                    last_direction = "left";
                }
                break;

            case Keys.S:
            case Keys.Down:
                if (last_direction != "up" && snake.GetY(0) <= max_down)
                {
                    snake.move("down");
                    last_direction = "down";
                }
                break;

            case Keys.D:
            case Keys.Right:
                if (last_direction != "left" && snake.GetX(0) <= max_right)
                {
                    snake.move("right");
                    last_direction = "right";
                }
                break;

            default:
                break;
            }
            if (snake.eat(food.GetX(), food.GetY()))
            {
                game.incrementPoints(10);
                food = new Food();
                snake.grow();
            }

            if (game.gameOver(snake.GetX(0), snake.GetY(0), snake))
            {
                MessageBox.Show("Game Over!\n\nYou got " + game.getPoints() + " points!");
                this.Close();
            }

            if (game.gameWin())
            {
                MessageBox.Show("You Won!\n\nFinal Points: " + game.getPoints());
            }

            this.Text = "Snake | Points: " + game.getPoints();

            this.Invalidate();
        }
示例#23
0
        static void Main(string[] args)
        {
            Console.WindowHeight = 40;
            Console.WindowWidth  = 70;
            Snake snake = new Snake();
            int   lvl   = 1;
            Wall  wall  = new Wall(lvl);

            Console.CursorVisible = false;
            Thread thread = new Thread(func);

            thread.Start();

            Random rnd  = new Random();
            int    _x   = rnd.Next(1, 70);
            int    _y   = rnd.Next(1, 20);
            Food   food = new Food(_x, _y);


            while (true)
            {
                foreach (Point p in wall.body)
                {
                    if (p.x == food.body[0].x && p.y == food.body[0].y)
                    {
                        rnd  = new Random();
                        _x   = rnd.Next(1, 70);
                        _y   = rnd.Next(1, 20);
                        food = new Food(_x, _y);
                        continue;
                    }
                }
                for (int p = 1; p <= snake.body_cnt; p++)
                {
                    if (snake.body[p].x == food.body[0].x && snake.body[p].y == food.body[0].y)
                    {
                        rnd  = new Random();
                        _x   = rnd.Next(1, 70);
                        _y   = rnd.Next(1, 20);
                        food = new Food(_x, _y);
                        continue;
                    }
                }
                break;
            }
            int k = 1;

            while (!gameOver)
            {
                while (true)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey();
                    if (keyInfo.Key == ConsoleKey.DownArrow && direction != 4)
                    {
                        direction = 3;
                    }
                    if (keyInfo.Key == ConsoleKey.UpArrow && direction != 3)
                    {
                        direction = 4;
                    }
                    if (keyInfo.Key == ConsoleKey.LeftArrow && direction != 1)
                    {
                        direction = 2;
                    }
                    if (keyInfo.Key == ConsoleKey.RightArrow && direction != 2)
                    {
                        direction = 1;
                    }

                    if (keyInfo.Key == ConsoleKey.R)
                    {
                        level = 1;
                        snake = new Snake();
                        wall  = new Wall(level);
                    }
                    if (keyInfo.Key == ConsoleKey.Escape)
                    {
                        gameOver = true;
                    }
                    foreach (Point p in wall.body)
                    {
                        if (p.x == snake.body[0].x && p.y == snake.body[0].y)
                        {
                            gameOver = true;
                        }
                    }
                    for (int p = 1; p <= snake.body_cnt; p++)
                    {
                        if (snake.body[p].x == snake.body[0].x && snake.body[p].y == snake.body[0].y)
                        {
                            gameOver = true;
                        }
                    }


                    if (food.body[0].x == snake.body[0].x && food.body[0].y == snake.body[0].y)
                    {
                        k++;
                        snake.Add();
                        _x   = rnd.Next(1, 70);
                        _y   = rnd.Next(1, 20);
                        food = new Food(_x, _y);
                        bool ok = true;
                        while (ok)
                        {
                            foreach (Point p in wall.body)
                            {
                                if (p.x == food.body[0].x && p.y == food.body[0].y)
                                {
                                    _x   = rnd.Next(1, 70);
                                    _y   = rnd.Next(1, 20);
                                    food = new Food(_x, _y);
                                }
                            }
                            for (int p = 1; p <= snake.body_cnt; p++)
                            {
                                if (snake.body[p].x == food.body[0].x && snake.body[p].y == food.body[0].y)
                                {
                                    _x   = rnd.Next(1, 70);
                                    _y   = rnd.Next(1, 20);
                                    food = new Food(_x, _y);
                                }
                            }
                            ok = false;
                        }
                    }
                    if (k % 5 == 0)
                    {
                        k = 1;
                        lvl++;
                        wall = new Wall(lvl);
                    }
                }
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.White;
                Console.SetCursorPosition(35, 12);
                Console.WriteLine("GAME OVER!");
                Console.ReadKey();
            }
        }