예제 #1
0
        private static double ContainsFood(SnakeGame game, Direction direction)
        {
            switch (direction)
            {
            case Direction.Up:
                return((game.SnakeXPos == game.FoodXPos &&
                        game.SnakeYPos > game.FoodYPos)
                        ? 5
                        : 0);

            case Direction.Down:
                return((game.SnakeXPos == game.FoodXPos &&
                        game.SnakeYPos < game.FoodYPos)
                        ? 5
                        : 0);

            case Direction.Left:
                return((game.SnakeXPos > game.FoodXPos &&
                        game.SnakeYPos == game.FoodYPos)
                        ? 5
                        : 0);

            case Direction.Right:
                return((game.SnakeXPos < game.FoodXPos &&
                        game.SnakeYPos == game.FoodYPos)
                        ? 5
                        : 0);

            default:
                return(-1);
            }
        }
예제 #2
0
        public void PlantTest()
        {
            SnakeGame.Initialise();

            int expectedAppleCount = 0;
            int expectedSpikeCount = 0;

            var appleCount = GetGridContentCount(CellContent.Apple);
            var spikeCount = GetGridContentCount(CellContent.Spikes);

            Assert.IsTrue(appleCount == expectedAppleCount);
            Assert.IsTrue(spikeCount == expectedSpikeCount);

            for (int i = 0; i < 10; i++)
            {
                if (i % 3 == 0)
                {
                    SnakeGame.Plant(CellContent.Apple);
                    appleCount = GetGridContentCount(CellContent.Apple);
                    expectedAppleCount++;
                }
                else
                {
                    SnakeGame.Plant(CellContent.Spikes);
                    spikeCount = GetGridContentCount(CellContent.Spikes);
                    expectedSpikeCount++;
                }

                Assert.IsTrue(appleCount == expectedAppleCount);
                Assert.IsTrue(spikeCount == expectedSpikeCount);
            }
        }
예제 #3
0
 public GameStateManager(SnakeGame game, GameContentManager gameContentManager)
 {
     MenuState = new MenuState(this, game, gameContentManager);
     PlayingGameState = new PlayingGameState(this, game, gameContentManager);
     EndGameState = new EndGameState(this, game, gameContentManager);
     _currentState = MenuState;
 }
예제 #4
0
        public MainWindow()
        {
            InitializeComponent();
            cells          = AreaGrid.Children;
            TextScore.Text = Score.ToString();

            int rows    = 23;
            int columns = 51;

            AreaGrid.Rows    = rows;
            AreaGrid.Columns = columns;
            SetBackground(AreaGrid, "LightGray");

            DrawRegion(rows, columns);

            game = new SnakeGame();

            game.Draw += this.Draw;


            stepTimer          = new System.Windows.Forms.Timer();
            stepTimer.Interval = 100;
            stepTimer.Enabled  = false;
            stepTimer.Tick    += OnStepTimer;
        }
예제 #5
0
        private void MovePlayer()
        {
            SnakeGame.MoveBodyLogic();

            //limitez sarpele la screen, spatiul de joc
            GamePlay.Instance.maxX = screen.Size.Width / GamePlay.Instance.Width;//pozitia max x si y
            GamePlay.Instance.maxY = screen.Size.Height / GamePlay.Instance.Height;
        }
예제 #6
0
        public void TestLoadFile()
        {
            var map   = new SnakeMap();
            var snake = new SnakeGame(map);

            snake.LoadFile(fileName);
            Assert.IsTrue(snake.SnakeMap.Map.Count > 0, "Not load SnakeMap");
        }
예제 #7
0
 public Form1()
 {
     InitializeComponent();
     rand   = new Random();
     player = new SnakePlayer(1000, rand);
     player.Init();
     game = new SnakeGame(rand, 20);
     game.Init();
 }
예제 #8
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        public SnakeViewModel()
        {
            SnakeGameLogic = new SnakeGame();

            UpKeyPressedCommand    = new DelegateCommand(OnUpKeyPressed);
            RightKeyPressedCommand = new DelegateCommand(OnRightKeyPressed);
            DownKeyPressedCommand  = new DelegateCommand(OnDownKeyPressed);
            LeftKeyPressedCommand  = new DelegateCommand(OnLeftKeyPressed);
        }
예제 #9
0
        public void TestReadCells()
        {
            var map   = new SnakeMap();
            var snake = new SnakeGame(map);

            snake.LoadFile(fileName);
            snake.SnakeMap.BuildMapCell();
            Assert.IsTrue(snake.SnakeMap.MapCells.Count > 0, "Not load Cell SnakeMap");
        }
예제 #10
0
        static void Main( string[] args )
        {
            ConsoleHandler handler = new ConsoleHandler( 80, 30 );

            SnakeGame snake = new SnakeGame( handler );
            snake.Start();

            Console.ReadKey();
        }
예제 #11
0
        public void InitializeTest()
        {
            Assert.IsNull(GameState.grid);
            Assert.IsNull(GameState.snake);

            SnakeGame.Initialise();

            Assert.IsNotNull(GameState.grid);
            Assert.IsNotNull(GameState.snake);
        }
예제 #12
0
        //private void Recognize(View.TouchEventArgs e)
        //{
        //    var dir = MotionRecognizer.Recognize(down, new Position((int)e.Event.RawX, (int)e.Event.RawY));
        //    WriteLine($"dir: {dir}");
        //    switch (dir)
        //    {
        //        case Direction.Left:
        //            LeftBtnOnClick(null, null);
        //            break;
        //        case Direction.Right:
        //            RightBtnOnClick(null, null);
        //            break;
        //        case Direction.Up:
        //            UpBtnOnClick(null, null);
        //            break;
        //        case Direction.Down:
        //            DownBtnOnClick(null, null);
        //            break;
        //    }
        //}

        private void InitGame()
        {
            if (_game == null)
            {
                var bodyFactory = new BodyFactory(Resources);
                var foodFactory = new FoodFactory(Resources);
                _game                 = new SnakeGame(_snakeField, bodyFactory, foodFactory, 34, 200);
                _game.OnGameOver     += OnGameOver;
                _game.OnScoreChanged += GameOnOnScoreChanged;
            }
        }
예제 #13
0
        private static int GetObstacleDistance(SnakeGame game, Direction direction)
        {
            ITile tile;

            switch (direction)
            {
            case Direction.Left:
                tile = game.Map.Tiles.Where(x
                                            => x.Value == TileValues.Snake &&
                                            x.XPos < game.SnakeXPos &&
                                            x.YPos == game.SnakeYPos)
                       .OrderByDescending(x => x.XPos)
                       .FirstOrDefault();
                return(tile == null
                        ? game.SnakeXPos + 1
                        : game.SnakeXPos - tile.XPos);

            case Direction.Right:
                tile = game.Map.Tiles.Where(x
                                            => x.Value == TileValues.Snake &&
                                            x.XPos > game.SnakeXPos &&
                                            x.YPos == game.SnakeYPos)
                       .OrderBy(x => x.XPos)
                       .FirstOrDefault();
                return(tile == null
                        ? game.Map.Width - game.SnakeXPos
                        : tile.XPos - game.SnakeXPos);

            case Direction.Up:
                tile = game.Map.Tiles.Where(x
                                            => x.Value == TileValues.Snake &&
                                            x.XPos == game.SnakeXPos &&
                                            x.YPos < game.SnakeYPos)
                       .OrderByDescending(x => x.YPos)
                       .FirstOrDefault();
                return(tile == null
                        ? game.SnakeYPos + 1
                        : game.SnakeYPos - tile.YPos);

            case Direction.Down:
                tile = game.Map.Tiles.Where(x
                                            => x.Value == TileValues.Snake &&
                                            x.XPos == game.SnakeXPos &&
                                            x.YPos > game.SnakeYPos)
                       .OrderBy(x => x.YPos)
                       .FirstOrDefault();
                return(tile == null
                        ? game.Map.Height - game.SnakeYPos
                        : tile.YPos - game.SnakeYPos);

            default:
                return(-1);
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            Console.Write("Enter port: ");
            int port = int.Parse(Console.ReadLine());

            game = new SnakeGame("127.0.0.1", port);

            game.PlayGame(DecideDirection, false);

            System.Environment.Exit(1);
        }
예제 #15
0
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            renderer = new Render(spriteBatch, GraphicsDevice);
            graphics.PreferredBackBufferWidth  = 700; // set this value to the desired width of your window
            graphics.PreferredBackBufferHeight = 700; // set this value to the desired height of your window
            graphics.ApplyChanges();

            net       = Trainer.train(renderer);
            debugGame = new SnakeGame();
        }
예제 #16
0
        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox.AllowDrop = true;

            Game              = new SnakeGame(gamePanel.Size);
            Game.GameChanged += Game_GameChanged;
            Game.initGame();

            Watcher          = new GameProgressWatcher(Game, this);
            Watcher.NewData += graphGameProgressControl.UpdateGraph;
            Watcher.NewData += gridGameProgressControl.UpdateGraph;
            Watcher.Start();
        }
        public void SnakeGameTest()
        {
            var sg = new SnakeGame(3, 2, new[, ] {
                { 1, 2 }, { 0, 1 }
            });

            Assert.AreEqual(sg.Move("R"), 0);
            Assert.AreEqual(sg.Move("D"), 0);
            Assert.AreEqual(sg.Move("R"), 1);
            Assert.AreEqual(sg.Move("U"), 1);
            Assert.AreEqual(sg.Move("L"), 2);
            Assert.AreEqual(sg.Move("U"), -1);
        }
예제 #18
0
        private static Dictionary <IWeightedNetwork, SnakeGame> SetupAlgorithmDictionary()
        {
            Dictionary <IWeightedNetwork, SnakeGame> networkAndSnakeGame = new Dictionary <IWeightedNetwork, SnakeGame>();

            for (int i = 0; i < algorithm.NetworksAndFitness.Count; ++i)
            {
                SnakeGame game = new SnakeGame(HEIGHTS_GAME, WIDTH_GAME, INITIAL_SNAKE_LENGTH);
                game.Printer.IsPrintingMap = isPrintingMap;
                game.PlaceSnakeOnMap();
                networkAndSnakeGame.Add(algorithm.NetworksAndFitness.Select(x => x.Key).ElementAt(i), game);
            }
            return(networkAndSnakeGame);
        }
예제 #19
0
        public void StartGameTest()
        {
            SnakeGame.Initialise();

            var appleCount = GetGridContentCount(CellContent.Apple);

            Assert.IsTrue(appleCount == 0);

            SnakeGame.StartGame();

            appleCount = GetGridContentCount(CellContent.Apple);
            Assert.IsTrue(GameState.score == 0);
            Assert.IsTrue(appleCount == 1);
        }
예제 #20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //Для предотвращения мерцания при перерисовке
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            //Создаем экземпляр с игрой на форме.
            snake = new SnakeGame(this);

            //Добавляем событие на нажатие Esc
            snake.PressEsc += new SnakeGame.EscPressHandler(snake_PressEsc);

            UpdateLevelBox();
        }
예제 #21
0
        public SnakeViewModel()
        {
            SnakeGame = new SnakeGame();

            Settings = new Settings();

            Timer.Tick += OnTimerTick;

            UpKeyCommand    = new Command(OnUpKeyPressed);
            DownKeyCommand  = new Command(OnDownKeyPressed);
            LeftKeyCommand  = new Command(OnLeftKeyPressed);
            RightKeyCommand = new Command(OnRightKeyPressed);
            PauseCommand    = new Command(OnEscPressed);
        }
예제 #22
0
파일: SnakeMain.cs 프로젝트: lic5663/Cshap
        static void Main(string[] args)
        {
            // 서버 생성 및 클라이언트 연결, 모든 클라이언트 ready 대기
            AsynchronousSocketListener.StartListening();

            while (true)
            {
                started.WaitOne();
                Clear();
                started.Reset();

                snakeGame = new SnakeGame();
                snakeGame.ProcedureGameHandler();
            }
        }
예제 #23
0
        public void TestShareCell()
        {
            var map       = new SnakeMap();
            var snakeGame = new SnakeGame(map);

            snakeGame.LoadFile(fileName);
            snakeGame.SnakeMap.BuildMapCell();
            var snake1 = new Snake();

            snakeGame.Play(snake1);
            Assert.IsTrue(snake1.Cells.Count == 7, "Falhou na busca 1");
            var snake2 = new Snake();

            snakeGame.Play(snake2);
            Assert.IsTrue(snake2.Cells.Count == 7, "Falhou na busca 2");
        }
예제 #24
0
        private static void ReplayWithBestNetwork()
        {
            SnakeGame game = new SnakeGame(HEIGHTS_GAME, WIDTH_GAME, INITIAL_SNAKE_LENGTH);

            game.Printer.IsPrintingMap = true;
            game.InitializeGame();
            game.PlaceSnakeOnMap();
            KeyValuePair <IWeightedNetwork, SnakeGame> bestnetworkAndGame = new KeyValuePair <IWeightedNetwork, SnakeGame>(
                algorithm.NetworksAndFitness[0].Key,
                game);

            int previousNextRoundDelay = nextRoundDelay;

            nextRoundDelay = 100;
            RunSnakeGame(bestnetworkAndGame, false);
            nextRoundDelay = previousNextRoundDelay;
        }
예제 #25
0
        public void CellContainsSomethingOrSnakeIsThereTest()
        {
            SnakeGame.Initialise();
            Assert.IsTrue(GetFilledCellsCount() == 1);

            SnakeGame.StartGame();

            Assert.IsTrue(GetFilledCellsCount() == 2);

            GameState.snake.Grow();
            GameState.snake.Move(Direction.Left);

            Assert.IsTrue(GetFilledCellsCount() == 3);

            SnakeGame.Plant(CellContent.Spikes);

            Assert.IsTrue(GetFilledCellsCount() == 4);
        }
예제 #26
0
        private static void Run()
        {
            var width  = 3;
            var height = 2;
            var food   = new int[][]
            {
                new int[] { 1, 2 },
                new int[] { 0, 1 }
            };
            var snakeGame = new SnakeGame(width, height, food);

            snakeGame.Move("R"); // 0
            snakeGame.Move("D"); // 0
            snakeGame.Move("R"); // 1
            snakeGame.Move("U"); // 1
            snakeGame.Move("L"); // 2
            snakeGame.Move("U"); // - 1
        }
예제 #27
0
        public GameForm(Point snake, Direction direction, int w, int h)
        {
            DoubleBuffered = true;
            game           = new SnakeGame(snake, direction, w, h);
            var timer = new Timer();

            timer.Interval = 200;
            KeyPress      += (sender, args) =>
            {
                switch (args.KeyChar)
                {
                case 'w':
                    game.Snake.ChangeDirection(Direction.Up);
                    break;

                case 's':
                    game.Snake.ChangeDirection(Direction.Down);
                    break;

                case 'a':
                    game.Snake.ChangeDirection(Direction.Left);
                    break;

                case 'd':
                    game.Snake.ChangeDirection(Direction.Right);
                    break;
                }
            };
            timer.Tick += (sender, args) =>
            {
                if (!game.MakeTurn())
                {
                    timer.Stop();
                    fail = true;
                }
                Invalidate();
            };
            timer.Start();
            Paint += (sender, args) =>
            {
                Draw(args);
            };
        }
예제 #28
0
파일: Menu.cs 프로젝트: Sanyco007/Tetris
        public void Update(long delta)
        {
            var screen = _menus.Peek();

            if (Keyboard.IsKeyDown(Key.Enter))
            {
                if (screen.GetType() == typeof(TetrisMenu))
                {
                    var tetris = new TetrisGame(_canvas, _next, _lines, _game);
                    _game.PushScreen(tetris);
                }
                if (screen.GetType() == typeof(SnakeMenu))
                {
                    var snake = new SnakeGame(_canvas, _game);
                    _game.PushScreen(snake);
                }
            }
            screen.Update(delta);
        }
예제 #29
0
        private static double ObstacleNearby(SnakeGame game, Direction direction)
        {
            int   snakeXPos = game.SnakeXPos;
            int   snakeYPos = game.SnakeYPos;
            ITile tile;

            switch (direction)
            {
            case Direction.Up:
                tile = game.Map.GetTile(snakeXPos, snakeYPos - 1);
                return(tile?.Value == TileValues.Snake ||
                       game.SnakeYPos == 0
                            ? 1
                            : 0);

            case Direction.Down:
                tile = game.Map.GetTile(snakeXPos, snakeYPos + 1);
                return(tile?.Value == TileValues.Snake ||
                       game.SnakeYPos == game.Map.Height - 1
                            ? 1
                            : 0);

            case Direction.Left:
                tile = game.Map.GetTile(snakeXPos - 1, snakeYPos);
                return(tile?.Value == TileValues.Snake ||
                       game.SnakeXPos == 0
                            ? 1
                            : 0);

            case Direction.Right:
                tile = game.Map.GetTile(snakeXPos + 1, snakeYPos);
                return(tile?.Value == TileValues.Snake ||
                       game.SnakeXPos == game.Map.Width + 1
                            ? 1
                            : 0);

            default:
                return(-1);
            }
        }
예제 #30
0
        int GetFilledCellsCount()
        {
            var p = new Position {
                X = 0, Y = 0
            };
            int filledCellsCount = 0;

            for (int y = 0; y < GameState.sideCellCount; y++)
            {
                p.Y = y;

                for (int x = 0; x < GameState.sideCellCount; x++)
                {
                    p.X = x;
                    if (SnakeGame.CellContainsSomethingOrSnakeIsThere(ref p))
                    {
                        filledCellsCount++;
                    }
                }
            }

            return(filledCellsCount);
        }
예제 #31
0
        private static double[] GetNetworkInput(SnakeGame game)
        {
            double nextObstacleLeftDistance  = GetObstacleDistance(game, Direction.Left);
            double nextObstacleUpDistance    = GetObstacleDistance(game, Direction.Up);
            double nextObstacleDownDistance  = GetObstacleDistance(game, Direction.Down);
            double nextObstacleRightDistance = GetObstacleDistance(game, Direction.Right);
            double foodToRight     = ContainsFood(game, Direction.Right);
            double foodToLeft      = ContainsFood(game, Direction.Left);
            double foodToDown      = ContainsFood(game, Direction.Down);
            double foodToUp        = ContainsFood(game, Direction.Up);
            double obstacleToRight = ObstacleNearby(game, Direction.Right);
            double obstacleToLeft  = ObstacleNearby(game, Direction.Left);
            double obstacleToDown  = ObstacleNearby(game, Direction.Down);
            double obstacleToUp    = ObstacleNearby(game, Direction.Up);

            return(new double[INPUT_NODES]
            {
                //game.SnakeXPos,
                //game.SnakeYPos,
                (double)game.Direction,
                nextObstacleLeftDistance,
                nextObstacleUpDistance,
                nextObstacleDownDistance,
                nextObstacleRightDistance,
                //obstacleToRight,
                //obstacleToLeft,
                //obstacleToUp,
                //obstacleToDown,
                foodToRight,
                foodToLeft,
                foodToDown,
                foodToUp,
                //game.SnakeXPos - game.FoodXPos,
                //game.SnakeYPos - game.FoodYPos,
            });
        }
예제 #32
0
    private void genBoard()
    {
        singleton = this;

        endings = Ending.findEndings(data).OrderBy<Ending, float>(e => e.difficulty).ToArray();
        if (endings.Length != 2) {
            Debug.Log("This game is designed to support 2 endings (in order of ascending difficulty): lose and stockCycle");
        }
        winThreshold = MathData.GetInt(endings[1].otherData(SNAKE_LENGTH_THRESHOLD));
        nodesPerLerp = MathData.GetInt(data.SelectSingleNode(NODES_PER_ETTELL_LERP));

        width = MathData.GetInt(data.SelectSingleNode(XmlUtilities.WIDTH));
        height = MathData.GetInt(data.SelectSingleNode(XmlUtilities.HEIGHT));
        freeTiles = new Queue<SnakeTileController>();

        spawnTiles(width * 2 + height * 2 + INITIAL_TILE_EXTRAS - 4);

        filledSpaces = new Square[width, height];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                filledSpaces[x, y] = new Square();
                this[x, y] = (x == 0 || x == width - 1 || y == 0 || y == height - 1) ? BorderColor : EMPTY_COLOR;
            }
        }

        GameObject ettell = Instantiate(ettellSnake) as GameObject;
        ettell.transform.parent = transform;
        GameObject stockCtrl = Instantiate(stockController) as GameObject;
        stockCtrl.transform.parent = transform;
    }
예제 #33
0
 public GameProgressWatcher(SnakeGame game, Form owner)
 {
     Owner = owner;
     Game  = game;
     Data  = new List <Point>();
 }
예제 #34
0
 public PlayingGameState(GameStateManager stateManager, SnakeGame game, GameContentManager contentManager)
     : base(stateManager, game, contentManager)
 {
 }
예제 #35
0
 public void DestroyInstance()
 {
     instance = null;
 }
예제 #36
0
 protected BaseGameState(GameStateManager stateManager, SnakeGame game, GameContentManager contentManager)
 {
     StateManager = stateManager;
     Game = game;
     ContentManager = contentManager;
 }
예제 #37
0
	public void DestroyInstance(){
		print ("Snake Game Instance Destroyed");
		instance = null;
	}