Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public override void Update(GameLoop gameLoop)
        {
            Program.TotalTime += (float)Glfw.GetTime();
            double delta = Glfw.GetTime();
            if (Program.TotalTime > 1f)
            {
                Glfw.SetTime(0.0);
            }
            if (currentKillPercentage < (int)(((double)totalKills / (double)totalPotentionalKills) * 100.0))
            {
                percentageCounter += delta;
                if (percentageCounter > percentageDelay)
                {
                    percentageCounter = 0;

                    currentKillPercentage++;
                }
            }
            else
            {
                if (Input.GetState(0).Keyboard[Key.Enter] && !Input.GetState(1).Keyboard[Key.Enter])
                {
                    ((GamePlayState)parent).rayCaster = new RayCaster();
                    gameLoop.ActiveGameState = parent;

                }
            }

        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var tower = new Tower();
            var loop  = new GameLoop();

            loop.Run();
        }
Exemplo n.º 3
0
        public override void Update(GameLoop gameLoop)
        {
            FontHandler.AddText(new Text("My house is secure", "menu1", new Vector2(Program.Window.Width / 2, 100), 2f, false));
            FontHandler.AddText(new Text("start game", "menu2", new Vector2(Program.Window.Width / 2, 350), 1f, false));
            FontHandler.AddText(new Text("exit", "menu3", new Vector2(Program.Window.Width / 2, 420), 1f, false));

            if (Input.GetState(0).Mouse.LeftButton)
            {
                if (GameObject.Contains(Input.GetState(0).MousePosition, button1))
                {
                    button1.color        = Color4.DarkBlue;
                    button1Outline.color = Color4.Blue;
                }
                else if (GameObject.Contains(Input.GetState(0).MousePosition, button2))
                {
                    button2.color        = Color4.DarkGreen;
                    button2Outline.color = Color4.Green;
                }
            }
            else
            {
                button1.color        = Color4.Blue;
                button1Outline.color = Color4.DarkBlue;
                button2.color        = Color4.Green;
                button2Outline.color = Color4.DarkGreen;
            }
        }
Exemplo n.º 4
0
        //TODO: build action for POST: CalculateSpendLimit
        //TODO: build action for POST: BuyAdvances

        //TODO: Consider moving this to the GameLoop service class
        //Resolves the Move AST phase. Called from Index()
        private IActionResult MoveAST(ActiveCiv activeCiv)
        {
            //Move the AST
            GameLoop loop      = new GameLoop(_context, activeCiv.Id);
            int      direction = loop.ResolveMoveAst();

            //If the game ended, go to the detailed active civilization view
            if (loop.CheckForGameEnd())
            {
                return(RedirectToAction(
                           nameof(ActiveCivsController.Details),
                           "ActiveCivs",
                           new { id = activeCiv.Id }
                           ));
            }

            //If the game didn't end, present a message to the player about what happened to the AST
            switch (direction)
            {
            case -1:
                ViewBag.MovementMessage = ASTRegresses;
                break;

            case 1:
                ViewBag.MovementMessage = ASTAdvances;
                break;

            case 0:
            default:
                ViewBag.MovementMessage = ASTStuck;
                break;
            }

            return(View("MoveAST", activeCiv));
        }
Exemplo n.º 5
0
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (!firstRender)
            {
                return;
            }

            gameService = new GameService();

            if (gameService.Instance != null)
            {
                await gameService.Instance.DisposeAsync();
            }

            var         gameLoop   = new GameLoop(JSRuntime);
            var         graphics   = new Graphics(JSRuntime, canvas, SuperSampling);
            var         audio      = new Audio(JSRuntime);
            var         keyboard   = new Keyboard(JSRuntime, canvas);
            var         mouse      = new Mouse(JSRuntime, canvas);
            IFileSystem fileSystem = new FileSystem(JSRuntime);

            var game = gameService.CreateGame(Type, gameLoop, graphics, audio, keyboard, mouse, fileSystem);

            //var game = gameService.CreateGame(Name, gameLoop, graphics, audio, keyboard, mouse, fileSystem);

            game.Keyboard.KeyPressed += OnKeyPressed;

            Width  = game.VirtualWidth;
            Height = game.VirtualHeight;

            StateHasChanged();

            await game.Run();
        }
Exemplo n.º 6
0
        public PathMap(GameLoop gameLoop, int deepFind = 5)
        {
            _deepFind = deepFind;
            _gameLoop = gameLoop;

            _gameLoop.OnTick += Tick;
        }
Exemplo n.º 7
0
 public void TestInteractableNietAanwezig()
 {
     using (ShimsContext.Create())
     {
         ZorkBork.Fakes.ShimSettings.LeesXMLOf1String <Kaart>((_) =>
         {
             return(new Kaart
             {
                 SpeelVeldGrootte = 1,
                 KaartItemList = new List <KaartItem> {
                     new KaartItem {
                         Beschrijving = "1"
                     }
                 }
             });
         });
         using (var stringWriter = new StringWriter())
         {
             Console.SetOut(stringWriter);
             var gameLoop = new GameLoop(false);
             gameLoop.InteractMetHuidigeInteractable();
             Assert.IsTrue(stringWriter.ToString().Contains("E is hier geen geldige keuze"));
         }
     }
 }
Exemplo n.º 8
0
        //[TestCase("o 2 0", 1, ExpectedResult = 6)]
        public int ProperFloorSegmentsFromRoomSegments(string input, int floorIndex)
        {
            var gameLoop    = new GameLoop();
            var isProcessed = gameLoop.ProcessInput(input);

            return(gameLoop.tower.Floors[floorIndex].GetSegments());
        }
Exemplo n.º 9
0
        public void DealerShouldHaveTwoCardsAtStartOfGame()
        {
            var gameLoop = new GameLoop();

            gameLoop.InitialiseGameState();
            gameLoop.GameState.DealerHand.Cards.Count.ShouldBe(2);
        }
Exemplo n.º 10
0
        /*public override void otherUpdate()
         * {
         *  if (MenuManager.anyInput.actionPressed(InputAction.MenuUp) || MenuManager.anyInput.actionTapped(InputAction.PadUp))
         *  {
         *      //decreaseShipHue(2.5f);
         *      //Race.humanRacers[0].setColour((int)shipHue);
         *  }
         *  if (MenuManager.anyInput.actionPressed(InputAction.MenuDown) || MenuManager.anyInput.actionTapped(InputAction.PadDown))
         *  {
         *      //increaseShipHue(2.5f);
         *      //Race.humanRacers[0].setColour((int)shipHue);
         *  }
         * }*/

        private void startSinglePlayerGame()
        {
            Race.humanRacers[0].setupRacingControls(((AnyInputManager)MenuManager.anyInput).useLastInputTappedToCreateNewIInputManager());
            SoundManager.PlayShipName(Race.humanRacers[0].shipName);
            GameLoop.setActiveControllers(true, 0);
            //BeatShift.bgm.play();
        }
Exemplo n.º 11
0
 private void Start()
 {
     GameManager = GameObject.Find("GameManager");
     loop        = GameManager.GetComponent <GameLoop>();
     player      = GameManager.GetComponent <Player>();
     day         = GameManager.GetComponent <DayCycle>();
 }
Exemplo n.º 12
0
        public IEnumerable<Player> Play()
        {
            var loop =
            new GameLoop(
               Board.Players,
               player =>
               {
                  using (Board.Flip(player))
                     return Heuristic.GetPossibleMoves(Board).Any();
               });

             var history = new List<IBoard>();
             foreach (var player in loop)
             {
            Board.Player = player;
            var box = new ThinkBox(loop.Round, Board.Clone(), history.ToArray());
            if (!player.MakeMove(box))
               break;

            Board.Commit(box.Result);
            history.Add(box.Result);
            yield return player;
             }

             yield return GetResult();
        }
Exemplo n.º 13
0
    //Take move that has been keyed in and charge for it
    public void pendingAction()
    {
        //always do move, bring heartPoints as low as 1, if need be
        Action pendingAction = listen();

        if (pendingAction == null)
        {
//			print("No valid keys pressed");
        }
        else if (pendingAction is Cancel)
        {
            GameLoop.endEvent(performing);
        }

        else if (pendingAction is Attack)
        {
            AttackEvent e = new AttackEvent((Attack)pendingAction, this, enemy);
            GameLoop.addToList(e);
            performing   = e;
            heartPoints -= performing.cost();
        }

        else if (pendingAction is Move)
        {
            MoveEvent e = new MoveEvent(this, (Move)pendingAction);
            GameLoop.addToList(e);
            performing   = e;
            heartPoints -= performing.cost();
        }

        if (heartPoints <= 0)
        {
            heartPoints = 1;
        }
    }
Exemplo n.º 14
0
        void setProlog()
        {
            this.MaximumSize    = new Size(700, 500);
            this.MinimumSize    = new Size(700, 500);
            this.DoubleBuffered = true;

            userDirection = new Directions();

            g          = this.CreateGraphics();
            backGround = Color.Bisque;
            background = new Bitmap(Resources.Background);
            cursX      = 0;
            cursY      = 0;

            player = new CPlayer {
                Left = 20, Top = 252
            };
            player.Update(player.Left, player.Top);
            playerSpeed = 10;
            jumpSpeed   = 55;
            jumpFrames  = 0;

            left  = false;
            right = false;
            jump  = false;

            setFoods();

            points = 0;

            GameLoop.Interval = 50;
            GameLoop.Start();
        }
Exemplo n.º 15
0
        public MapManager(GameLoop ctxGame)
        {
            CtxGame = ctxGame;

            CtxGame.FarmUI.FarmOptionsUI.MapPath.TryGetValue(( int )MapTypes.World, out string[] value);
            CurrentMap = new TileMap(value?[0], CtxGame);
        }
Exemplo n.º 16
0
        private static GameLoop CreateLoopGame(GameGroup group, int i, GameGroupMember member, int index, int indexOther)
        {
            var team1Id = group.MemberList[index].TeamId;
            var team2Id = group.MemberList[indexOther].TeamId;

            //排除轮空比赛
            if (team1Id.IsNullOrEmpty() || team2Id.IsNullOrEmpty())
            {
                return(null);
            }
            GameLoop loop = new GameLoop();

            loop.SetNewId();
            loop.SetCreateDate();
            loop.SetRowAdded();

            loop.OrderNo = i;//分组小轮次
            loop.OrderId = group.OrderId;
            loop.GameId  = member.GameId;
            loop.GroupId = member.GroupId;
            loop.Team1Id = team1Id;
            loop.Team2Id = team2Id;
            loop.IsTeam  = member.IsTeam;
            loop.State   = GameLoopState.NOTSTART.Id;
            loop.IsBye   = group.MemberList[index].TeamId.IsNullOrEmpty() || group.MemberList[indexOther].TeamId.IsNullOrEmpty();
            loop.JudgeId = group.LeaderId.GetId();
            return(loop);
        }
Exemplo n.º 17
0
 public void getColisions()
 {
     if (snakeHead.Left >= 430 || snakeHead.Left <= 0 || snakeHead.Top >= 448 || snakeHead.Top <= 0)
     {
         GameLoop.Stop();
         axDeathMusic.Ctlcontrols.play();
     }
     if (visitedFoods.Count() == foods.Length)
     {
         setFoods();
     }
     else
     {
         for (int x = 0; x < foods.Length; x++)
         {
             if (visitedFoods.Contains(x))
             {
                 continue;
             }
             else if (foods[x].isTouched(snakeHead.getColision()))
             {
                 axEatMusic.Ctlcontrols.play();
                 points++;
                 visitedFoods.Add(x);
             }
         }
     }
 }
Exemplo n.º 18
0
	// Use this for initialization
	void Start () {
        playerStatus = GetComponent<PlayerStatus>();
        playerStatus.player = this;
        hasMissed = false;
        //missedTimer = musicCore.tempoInterval;
        gameLoop = GameObject.Find("GameLogic").GetComponent<GameLoop>();
	}
Exemplo n.º 19
0
        private async void onUpdateFrame(object sender, FrameEventArgs e)
        {
            if (_updateFrameRetries > 3)
            {
                return;
            }
            try
            {
                _updateMessagePump.PumpMessages();
                _repeatArgs.DeltaTime = e.Time;
                await Events.OnRepeatedlyExecuteAlways.InvokeAsync(_repeatArgs);

                if (State.Paused)
                {
                    return;
                }
                adjustSpeed();
                GameLoop.Update();

                //Invoking repeatedly execute asynchronously, as if one subscriber is waiting on another subscriber the event will
                //never get to it (for example: calling ChangeRoom from within RepeatedlyExecute calls StopWalking which
                //waits for the walk to stop, only the walk also happens on RepeatedlyExecute and we'll hang.
                //Since we're running asynchronously, the next UpdateFrame will call RepeatedlyExecute for the walk cycle to stop itself and we're good.
                ///The downside of this approach is that we need to look out for re-entrancy issues.
                await Events.OnRepeatedlyExecute.InvokeAsync(_repeatArgs);

                _pipeline?.Update();
            }
            catch (Exception ex)
            {
                _updateFrameRetries++;
                Debug.WriteLine(ex.ToString());
                throw ex;
            }
        }
Exemplo n.º 20
0
        [Timeout(1000)] // comment this out if you want to debug
        public void SingleStepTest()
        {
            // TimeoutAttribute causes this to run on different thread on .NET Core,
            // which messes up IoC if we don't run this:
            BaseSetup();
            // Arrange
            var elapsedVal   = TimeSpan.FromSeconds(Math.PI);
            var newStopwatch = new Mock <IStopwatch>();

            newStopwatch.SetupGet(p => p.Elapsed).Returns(elapsedVal);
            var gameTiming = GameTimingFactory(newStopwatch.Object);
            var loop       = new GameLoop(gameTiming);

            var callCount = 0;

            loop.Tick   += (sender, args) => callCount++;
            loop.Render += (sender, args) => loop.Running = false; // break the endless loop for testing

            // Act
            loop.SingleStep = true;
            loop.Run();

            // Assert
            Assert.That(callCount, Is.EqualTo(1));
            Assert.That(gameTiming.CurTick, Is.EqualTo(new GameTick(2)));
            Assert.That(gameTiming.Paused, Is.True); // it will pause itself after running each tick
            Assert.That(loop.SingleStep, Is.True);   // still true
        }
Exemplo n.º 21
0
        public override Tuple <Point2D, Point2D> GetMove()
        {
            Stopwatch.Start();

            var pieces        = Board.GetAllColored(Color);
            var possibleMoves = Board.GetAllPossibleMoves();

            possibleMoves = possibleMoves.FindAll(tuple => tuple.Item1.Color == Color);

            Tuple <Point2D, Point2D> bestMove = null;
            //use any negative large number
            var bestValue = 0d;

            for (var i = 0; i < possibleMoves.Count; i++)
            {
                var newGameMove = possibleMoves[i];
                var tmpBoard    = Board.Clone();

                tmpBoard.Move(newGameMove.Item1, newGameMove.Item2);
                //take the negative as AI plays as black
                var games = GameLoop.Games(tmpBoard, new RandomAI(tmpBoard, Color.White),
                                           new RandomAI(tmpBoard, Color.Black), _MontyGames);
                var wins       = games.Count(a => a.Item1 == Color);
                var currentVal = wins / (double)_MontyGames;
                if (currentVal > bestValue)
                {
                    bestValue = currentVal;
                    bestMove  = new Tuple <Point2D, Point2D>(newGameMove.Item1.PositionPoint2D, newGameMove.Item2);
                }
            }

            _stopwatch.Stop();
            return(bestMove);
        }
Exemplo n.º 22
0
        public bool FloorAddInAscendingOrder(string input)
        {
            var tower = new Tower();
            var gameLoop = new GameLoop();

            return gameLoop.ProcessInput(input);
        }
Exemplo n.º 23
0
    //public bool forTesting = false;

    private void Awake()
    {
        colorHandler = FindObjectOfType <ColorHandler>();
        pauseBlocker = FindObjectOfType <PauseBlocker>();
        gameLoop     = FindObjectOfType <GameLoop>();
        grid         = GetComponent <CellsGrid>();
    }
Exemplo n.º 24
0
        protected override void Rent()
        {
            int rentMoney = _rents[_houses];

            GameLoop.GetCurrentPlayer().Charge(rentMoney);
            Owner.Pay(rentMoney);
        }
Exemplo n.º 25
0
        public override void Update(GameLoop gameLoop)
        {
            Program.TotalTime += (float)Glfw.GetTime();
            double delta = Glfw.GetTime();

            if (Program.TotalTime > 1f)
            {
                Glfw.SetTime(0.0);
            }
            if (currentKillPercentage < (int)(((double)totalKills / (double)totalPotentionalKills) * 100.0))
            {
                percentageCounter += delta;
                if (percentageCounter > percentageDelay)
                {
                    percentageCounter = 0;

                    currentKillPercentage++;
                }
            }
            else
            {
                if (Input.GetState(0).Keyboard[Key.Enter] && !Input.GetState(1).Keyboard[Key.Enter])
                {
                    ((GamePlayState)parent).rayCaster = new RayCaster();
                    gameLoop.ActiveGameState          = parent;
                }
            }
        }
Exemplo n.º 26
0
 public PauseScreen(GameLoop game)
     : base(game)
 {
     this.BlocksDraw = false;
     texture = Content.Load<Texture2D>("pausedialog");
     position = new Vector2((game.GraphicsDevice.Viewport.Width - texture.Width) / 2, (game.GraphicsDevice.Viewport.Height - texture.Height) / 2);
 }
Exemplo n.º 27
0
        public static void ChangeScene(ScenesType type)
        {
            CurrentScene?.Dispose();
            CurrentScene = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GameLoop game = Service.Get <GameLoop>();

            switch (type)
            {
            case ScenesType.Login:
                game.WindowWidth  = 640;
                game.WindowHeight = 480;
                CurrentScene      = new LoginScene();

                break;

            case ScenesType.Game:
                game.WindowWidth  = 1000;
                game.WindowHeight = 800;
                CurrentScene      = new GameScene();

                break;
            }

            CurrentScene.Load();
        }
        private void MainLoop()
        {
            _mainLoop = new GameLoop(_gameTimingHeadless)
            {
                SleepMode = Mode == DisplayMode.Headless ? SleepMode.Delay : SleepMode.None
            };

            _mainLoop.Tick += (sender, args) => Update(args.DeltaSeconds);

            if (Mode == DisplayMode.Clyde)
            {
                _mainLoop.Render += (sender, args) =>
                {
                    _gameTimingHeadless.CurFrame++;
                    _clyde.Render(new FrameEventArgs(args.DeltaSeconds));
                };
                _mainLoop.Input += (sender, args) => _clyde.ProcessInput(new FrameEventArgs(args.DeltaSeconds));
            }

            _mainLoop.Update += (sender, args) =>
            {
                _frameProcessMain(args.DeltaSeconds);
            };

            // set GameLoop.Running to false to return from this function.
            _mainLoop.Run();
        }
Exemplo n.º 29
0
    private void Start()
    {
        controls.UI.StartGame.performed += TransMenu;

        var lastDeathReason = GameLoop.lastDeathReason;

        try
        {
            showDeathScreen = GameLoop.isDeath;
            GameLoop.GetScore();
            gameScore.text = "Score: " + GameLoop.GetScore();
        }
#pragma warning disable 168
        catch (UnityException e) {}
#pragma warning restore 168
        if (!showDeathScreen)
        {
            deathReason.text = "Get going and score some points!";
        }
        else
        {
            Debug.Log(lastDeathReason);
            switch (lastDeathReason)
            {
            case 1:
                deathReason.text = "Smashed into a bar";
                break;

            case 2:
                deathReason.text = "Bit your own tail";
                break;
            }
        }
    }
Exemplo n.º 30
0
        public void Start()
        {
            hasClosed        = false;
            gameLoop         = new DispatcherTimerGameLoop(1000 / 100);
            gameLoop.Update += Update;

            gameWindow         = new GameWindow(settings);
            gameWindow.Closed += (sender, args) => Stop();

            SocketFactory socketGame = new SocketFactory(settings);

            socketGame.Cancel += Stop;
            socketManager      = socketGame.CreateSocketManager();

            GraphicManager graphicManager = new GraphicManager(gameWindow.Canvas);
            InputFactory   inputFactory   = new InputFactory(gameWindow.Canvas, socketManager);

            if (hasClosed)
            {
                return;
            }

            world = new World(settings, inputFactory, graphicManager);
            CompositionTarget.Rendering += (sender, args) => world.Draw();
            world.Start();
            gameWindow.Show();
            gameLoop.Start();
        }
Exemplo n.º 31
0
    private IEnumerator Animate()
    {
        float target = -10.5f;

        _puzzleElements.ForEach(p =>
        {
            p.Completed = true;
            p.ClearConnection();
        });

        while (transform.localPosition.y > target)
        {
            var pos = transform.localPosition;
            pos.y = Mathf.MoveTowards(pos.y, target, Time.deltaTime * _wallSpeed);
            transform.localPosition = pos;
            yield return(null);
        }

        if (_hasPlaySound == false)
        {
            GameLoop gameLoop = GameObject.Find("GameLoop").GetComponent <GameLoop>();
            gameLoop.PlayGoodSound();

            _hasPlaySound = true;
        }
    }
Exemplo n.º 32
0
        public static void PlayGame(bool initialSetup)
        {
            if (initialSetup || !PlayingGame)
            {
                playingGame        = true;
                Program.ClearColor = Program.CLEAR_COLOR_PLAY;

                Scene scene = null;
                if (initialSetup)
                {
                    if (FileLoader.GetTextFileConents(Scene.MAIN_SCENE_FILENAME, out string existingSceneJson, true))
                    {
                        scene = Serialization.SerializationHelper.Deserialize <Scene>(existingSceneJson, null, true);
                    }
                    if (scene == null)
                    {
                        scene = EmptyScene.GetEmptyScene();
                        string sceneJson = Serialization.SerializationHelper.Serialize(scene);
                        FileLoader.SaveTextFile(Scene.MAIN_SCENE_FILENAME, sceneJson);
                    }
                }
                else
                {
                    // We're already all set up, so just save current state of game
                    scene = SaveScene();
                }

                GameLoop.Init(GameSystems, scene.Components, TargetFramesPerSecond);
            }
        }
        protected override void Rent()
        {
            int rentMoney = Owner.GetUtilitiesOwned() * GameLoop.GetCurrentDieSum();

            GameLoop.GetCurrentPlayer().Charge(rentMoney);
            Owner.Pay(rentMoney);
        }
Exemplo n.º 34
0
        public void StartGameBehavior()
        {
            var deck1 = new Deck();

            deck1.AddCard(TestCards.SleepyPanda, count: 10);
            deck1.AddCard(TestCards.BigDragon, count: 2);

            var deck2 = new Deck();

            deck2.AddCard(TestCards.RabidDog, count: 10);
            deck2.AddCard(TestCards.BigDragon, count: 2);

            var eventQueue = new List <AEvent>
            {
                new PlayerActionPlayCardEvent(Player.Player1, deck1.Cards.First(), new Id <CardMount>(new CardMount(1))),
                new PlayerActionEndTurnEvent(),
                new PlayerDrawCardEvent(Player.Player2),
                new PlayerActionPlayCardEvent(Player.Player2, deck1.Cards.First(), new Id <CardMount>(new CardMount(1))),
                new PlayerActionEndTurnEvent(),
                new PlayerActionForfeitGame(Player.Player1),
            };

            var eventProvider = new TestEventProvider(eventQueue);

            var gameLoop = new GameLoop(eventProvider, deck1, deck2);

            // PlayGame() will trigger the beginning of game card draw events
            gameLoop.PlayGame();
        }
Exemplo n.º 35
0
 public void PageLoaded(object o, EventArgs e)
 {
     // Required to initialize variables
     Focus();
     gameLoop = new GameLoop();
     gameLoop.Attach(parentCanvas);
     Page_SizeChanged(null, null);
 }
Exemplo n.º 36
0
 /// <summary>
 /// Start the system. This method must be called.
 /// </summary>
 /// <param name="Loop">The game loop called for each game.</param>
 public void Run(GameLoop Loop)
 {
     try
     {
         _Client = new System.Net.Sockets.TcpClient(_Server, _Port);
     }
     catch
     {
         System.Console.WriteLine("[ERROR] Impossible to join the server (FATAL)");
         System.Environment.Exit(1);
     }
     JSON.Object connect = new JSON.Object();
     connect["login"] = _Username;
     connect["password"] = _Password;
     _Write(connect);
     try
     {
         while (true)
         {
             JSON.Object newgame = _ReadObject();
             Game game = new Game();
             game._Parent = this;
             try
             {
                 if ((newgame["error"] as JSON.String).Value != "")
                 {
                     Console.WriteLine("[ERROR] Invalid connection check your login and your password");
                     System.Environment.Exit(1);
                 }
             }
             catch { }
             try { game.You._Name = (newgame["you"] as JSON.String).Value; }
             catch { game.You._Name = "noname"; }
             try { game.Challenger._Name = (newgame["challenger"] as JSON.String).Value; }
             catch { game.Challenger._Name = "noname"; }
             Loop(game);
             if (!game._Ended)
             {
                 System.Console.WriteLine("[ERROR] Game loop has ended before the end of the game (FATAL)");
                 System.Environment.Exit(1);
             }
             JSON.Object ready = new JSON.Object();
             ready["type"] = "ready";
             _Write(ready);
             System.Threading.Thread.Sleep(10);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("[INFO]  An exception occurs inside the game loop:\n" + e.ToString());
     }
     try
     {
         _Client.Close();
     }
     catch { }
 }
  public void LevelStage(GameLoop myGame){
    game = myGame;

    game.babeGenerateWord = false;
    game.devilGenerateWord = false;

    switch( PersistState.GetInstance().stage ){
    case 1:
      SetBabeDifficulty(1, 35f, 15f);
      game.matchPoint = 12f; // 2-second cost

      game.ingredientCount = 3;
      game.finisherCount = 1;
      break;
    case 2:
      SetBabeDifficulty(2, 32f, 10f);
      game.matchPoint = 12f; // 2-second cost

      game.ingredientCount = 3;
      game.finisherCount = 2;
      break;
    case 3:
      SetBabeDifficulty(1, 30f, 15f);
      SetDevilDifficulty(1, 40f, 15f);
      game.matchPoint = 12f; // 3-second cost

      game.ingredientCount = 3;
      game.finisherCount = 2;
      break;
    case 4:
      SetBabeDifficulty(1, 30f, 15f);
      SetDevilDifficulty(2, 60f, 20f);
      game.matchPoint = 18f; // 4-second cost

      game.ingredientCount = 5;
      game.finisherCount = 2;
      break;
    case 5:
      SetBabeDifficulty(2, 40f, 15f);
      SetDevilDifficulty(2, 60f, 20f);
      game.matchPoint = 20f; // 5-second cost

      game.ingredientCount = 5;
      game.finisherCount = 3;
      break;
    case 6:
      //SetBabeDifficulty(2, 40f, 15f);
      SetDevilDifficulty(4, 70f, 20f);
      game.matchPoint = 20f; // 8-second cost

      game.ingredientCount = 6;
      game.finisherCount = 3;
      break;
    }
      
  }
Exemplo n.º 38
0
 public Screen(GameLoop game)
 {
     this.Game = game;
     this.SpriteBatch = new SpriteBatch(game.GraphicsDevice);
     this.Visible = true;
     this.BlocksUpdate = true;
     this.BlocksInput = true;
     this.BlocksDraw = true;
     Content = game.Content;
 }
 public SurvivalModeScreen(GameLoop game)
     : base(game)
 {
     _mapHeight = game.GraphicsDevice.Viewport.Height;
     _mapWidth = game.GraphicsDevice.Viewport.Width;
     _blockTexture = Content.Load<Texture2D>(GameSettings.BlockName);
     _runnerTexture = Content.Load<Texture2D>(GameSettings.RunnerName);
     _blockMaxH = _mapHeight / GameSettings.BlockHeight;
     _blockMaxW = _mapWidth / GameSettings.BlockWidth;
 }
Exemplo n.º 40
0
	// Use this for initialization
	void Start () 
	{
		gLoop = Logic.GetComponent<GameLoop>(); 
		
		placement1 = new Vector3(-0.092743f,8.229965f,0);
		placement2 = new Vector3(-0.092743f,4.12f,0);
		placement3 = new Vector3(-0.092743f,-.02f,0);

		transform.Find("btn_Okay").gameObject.active = false; 		
	}
Exemplo n.º 41
0
	void Start () {
		GameObject gc = GameObject.FindGameObjectWithTag ("GameController");
		board = gc.GetComponent<Board> ();
		gameLoop = gc.GetComponent<GameLoop> ();

		boardWidth = board.GetWidth ();

		blockColor = transform.GetChild(0).GetComponent<SpriteRenderer> ().color;

		nextMove = Time.time + moveRate;

		blockSFX = GetComponent<AudioSource> ();
	}
Exemplo n.º 42
0
        static void Main(string[] args)
        {
            Window2D window = new Window2D(ScreenWidth, ScreenHeight, true, "Pew Pew - VikingStein 2.5D - By Metaldemon", ScreenWidth, ScreenHeight);
            MainGameLoop = new GameLoop(new LoadState());

            

            Glfw.SwapInterval(false);

            new Thread(_LoadMusic).Start();
            MainGameLoop.Start(window);

            ContentManager.DisposeAll();
        }
Exemplo n.º 43
0
 public override void Update(GameLoop gameLoop)
 {
     for (int x = 0; x < 640; x++)
     {
         for (int y = 0; y < 480 - 72; y++)
         {
             ScreenBuffer.screenBuffer[y * 640 + x] = ScreenBuffer.GetUintFromARGB(255, 120, 120, 120);
         }
     }
     if (Input.GetState(0).Keyboard[Key.Enter] && !Input.GetState(1).Keyboard[Key.Enter])
     {
         Loader.CurrentMap = "Map00";
         Loader.NextMap = "Map01";
         gameLoop.ActiveGameState = new MenuState();
     }
 }
Exemplo n.º 44
0
 public override void Update(GameLoop gameLoop)
 {
     if (begin)
     {
         alpha += 0.0005f;
         if (alpha >= 1)
         {
             gameLoop.ActiveGameState = new MenuState();
         }
     }
     else
     {
         alpha -= 0.0005f;
         begin = (alpha <= 0);
     }
 }
Exemplo n.º 45
0
	void Start () {
		// Get the component scripts
		CL = GameObject.Find ("CardLoader").GetComponent<CardLoader> ();
		GL = GameObject.Find ("GamePlay").GetComponent<GameLoop> ();

		//These are the objects which each card will be displayed in
		Player1Hand = GameObject.Find("Player1Hand"); // this is the players hand, cards when drawn will be displayed here
		Player1Tactics = GameObject.Find("Player1Tactics"); // this is the player's tactics zone, when a spell/arms card is played it goes here
		Player1Creatures = GameObject.Find("Player1Creatures"); // this is the player's creatures zone, when a creature is played it goes here
		Player1Stack = GameObject.Find("Player1Stack"); // this is player1's view of the stack

		// this is the player2's view of the cards player1 has
		Player2ViewTactics = GameObject.Find ("Player2ViewTactics"); // player2's view of player1's tactics zone
		Player2ViewCreatures = GameObject.Find ("Player2ViewCreatures"); // player2's view of player1's creature zone
		Player2ViewHand = GameObject.Find ("Player2ViewHand"); // player2's view of player1's hand
		Player2Stack = GameObject.Find ("Player2Stack"); // player2's view of the stack

		// The positions to display the cards at
		Player1HandPos = Player1Hand.transform.position; // the hand position 
		Player1HandPos.z -= 1f; // move the position to be just infront of the gameobject
		Player1TacticsPos = Player1Tactics.transform.position;
		// position the card in the correct place in relation to the gameobject
		Player1TacticsPos.z -= 1f; 
		Player1TacticsPos.y += 3f; 
		Player1CreaturesPos = Player1Creatures.transform.position;
		// position the card in the correct place in relation to the game object
		Player1CreaturesPos.z -= 1f;
		Player1CreaturesPos.y += 3f;
		Player1StackPos.z = -1f;

		// the positions to display the cards player 2 can see
		Player2HandViewPos = Player2ViewHand.transform.position;
		Player2HandViewPos.z -= 1f; // move the position to be just in front of the game object
		Player2TacticsViewPos = Player2ViewTactics.transform.position;
		// position the card in the correct place in relation to the game object
		Player2TacticsViewPos.z -= 1f;
		Player2TacticsViewPos.y += 3f;
		Player2CreatureViewPos = Player2ViewCreatures.transform.position;
		// position the card in the correct place in relation to the game object
		Player2CreatureViewPos.z -= 1f;
		Player2CreatureViewPos.y += 3f;
		Player2StackPos = Player2Stack.transform.position;
		// position the card in the correct place in relation to the game object
		Player2StackPos.z -= 1f;
		Player2StackPos.x -= 21f;
		Player2StackPos.y += 9f;
	}
Exemplo n.º 46
0
        public void Should_Call_Execute_On_Command()
        {
            //Arrange
            var cmdList = new List<ICommand>();
            ICommand mockCmd = MockRepository.GenerateMock<ICommand>();
            mockCmd.Stub(m => m.IsValid(Arg<string>.Is.Anything)).Return(true);
            cmdList.Add(mockCmd);
            IConsoleFacade console = MockRepository.GenerateMock<IConsoleFacade>();
            console.Stub(m => m.ReadLine()).Return("exit");
            game = new GameLoop(console, cmdList);

            //Act
            game.RunLoop();

            //Assert
            mockCmd.AssertWasCalled(m => m.Execute(Arg<string>.Is.Anything));
        }
Exemplo n.º 47
0
        public GameVc(Game theGame, string contentDirectory = "Content")
        {
            _theGame = theGame;
            _theGame.Content.RootDirectory = contentDirectory;
            _renderingContext = new RenderingContext { Game = _theGame, GraphicsDevice = new GraphicsDeviceManager(theGame)};

            DependencyResolver = new ActivationShim(Activator.CreateInstance);

            SceneRouteTable = new SceneRouteTable();
            SceneRegistrar = new SceneRegistrar(SceneRouteTable);
            Router = new SceneRouter(SceneRouteTable, new SceneCache(DependencyResolver.CreateInstance));

            _gameLoop = new GameLoop(theGame, Router,
                t => CurrentScene.PreUpdate(),
                t => CurrentScene.Update(t),
                t => CurrentScene.PostUpdate()
                );
        }
Exemplo n.º 48
0
	// Use this for initialization
	void Start () {
        gameLogicObj = GameObject.Find("GameLogic");
        if(gameLogicObj)
        {
            gameLoop = gameLogicObj.GetComponent<GameLoop>();
        }        
        if(gameLoop)
        {
            timeLimit = gameLoop.timeLimit;
            passedTime = 0.0f;
        }
        // get screen resolution
        
        screenWidth = Screen.width;
        screenHeight = Screen.height;
        
        fullBarstartPos = new Vector2((screenWidth - fullBarSize.x) / 2, fullBarHeightRatio * screenHeight);

        emptyBarstartPos = new Vector2((screenWidth - emptyBarSize.x) / 2, emptyBarHeightRatio * screenHeight);
    }
Exemplo n.º 49
0
 public void Page_Loaded(object o, EventArgs e)
 {
     // Required to initialize variables
     _splash = new Splash();
     canvas.Children.Add(_splash);
     _splash.SetValue(Canvas.ZIndexProperty, 20000);
     KeyHandler = new KeyHandler();
     KeyHandler.Attach(this);
     Focus();
     gameLoop = new GameLoop();
     gameLoop.Attach(parentCanvas);
     gameLoop.Update += gameLoop_Update;
     Fps fps = new Fps();
     canvas.Children.Add(fps);
     fps.SetValue(Canvas.ZIndexProperty, 1000);
     _mainMenu = new MainMenu();
     canvas.Children.Add(_mainMenu);
     _mainMenu.MenuItemSelected += mainMenu_MenuItemSelected;
     Page_SizeChanged(null, null);
 }
Exemplo n.º 50
0
        private void msgTicker_Tick(object sender, EventArgs e)
        {
            //Console.WriteLine(gameTime.TotalGameTime.TotalSeconds+" server");
            if (server != null)
            {
                NetIncomingMessage msg;
                NetOutgoingMessage response;
                NetConnection msgCon;
                string msgString;
                int msgInt;

                // check for new messages (all messages in queu per update cycle)
                while ((msg = networkManager.getMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        // Client sucht nach einem Server
                        case NetIncomingMessageType.DiscoveryRequest:
                            this.WriteToLog("Discoveryanfrage von: " + msg.SenderEndpoint.Address.ToString());
                            // Create a response
                            response = networkManager.createMessage();

                            // Send the response to the sender of the request
                            try
                            {
                                server.SendDiscoveryResponse(response, msg.SenderEndpoint);
                                this.WriteToLog("Antwort an " + msg.SenderEndpoint + " geschickt");
                            }
                            catch (Exception)
                            {
                                this.WriteToLog("Antwort an " + msg.SenderEndpoint + " konnte nicht gesendet werden");
                            }
                            break;

                        // Es handelt sich um ein Datenpaket
                        case NetIncomingMessageType.Data:
                            msgString = msg.ReadString();

                            switch (msgString)
                            {
                                // Client startete Spiel und wartet nun auf Initialisierung vom Server
                                case "startGame":
                                    string fileName = @"\Levels\level1.csv";
                                    gameStateManager.Level = new LevelProcessor().LoadMap(fileName);
                                    this.WriteToLog("Level " + fileName + " loaded");

                                    msgInt = msg.ReadInt32();
                                    foreach (Client c in connectedClients)
                                    {
                                        if (c.getConnection() == msg.SenderConnection)
                                        {
                                            c.setFigureType(msgInt);

                                            switch (c.getFigureType())
                                            {
                                                case 1:
                                                    NetworkController networkController =
                                                        new NetworkController(c.getUID(), EmptyController.Empty(c.getUID()),
                                                                              networkManager);

                                                    PacMan pacMan = new PacMan(string.Empty,
                                                                               gameStateManager.Level.getCell(1, 1),
                                                                               gameStateManager.Level, EmptyController.Empty(c.getUID()),
                                                                               Direction.None, 0.9f, new Point(49, 49));

                                                    gameStateManager.AddPlayers(pacMan);
                                                    break;

                                                default:
                                                    WriteToLog("Ghost isn't implemented yet");
                                                    break;
                                            }

                                            // Remove Client from pending list
                                            pendingClients.Remove(c.getConnection());
                                            //gameStateManager.AddPlayers(new PacMan());
                                            this.WriteToLog("Set figureType " + msgInt + " to Client " + c.getConnection().RemoteEndpoint.Address);
                                        }
                                    }

                                    gameLoop = new GameLoop(5000);

                                    gameLoop.StartingSimulation += StartSimulation;
                                    gameLoop.FinishedSimulation += FinishedSimulation;

                                    //gameTime.Start();

                                    break;

                                // Got direction update from client deploy it to the rest
                                case "newDirection":
                                    msgInt = msg.ReadInt32();
                                    long msgLong = msg.ReadInt64();
                                    msgCon = msg.SenderConnection;

                                    // calculate the UID from the sender of the message
                                    string msgUID = msgCon.RemoteUniqueIdentifier.ToString().Substring(msgCon.RemoteUniqueIdentifier.ToString().Length - 5);

                                    MovableObject toChange = gameStateManager.getFromId(Convert.ToInt32(msgUID));

                                    WriteToLogDebug("UID " + toChange.ID + "s current direction: " + (Direction)msgInt);

                                    inputQueue.Add(new Command((Direction)msgInt, Convert.ToInt32(msgUID),
                                                               gameTime.TotalGameTime.Milliseconds));

                                    //toChange.Direction = (Direction)msgInt;

                                    // send direction updates to all clients except the sender
                                    foreach (Client c in connectedClients)
                                    {
                                        if (c.getConnection() != msgCon)
                                        {
                                            response = networkManager.createMessage();
                                            response.Write("updateDirection;" + msgUID + ";" + msgInt);
                                            networkManager.sendMessage(response, c.getConnection());
                                            this.WriteToLog("Sent direction update for uid " + msgUID + " to " + c.getConnection().RemoteEndpoint.Address + "Time: " + gameTime.TotalGameTime.TotalMilliseconds);
                                        }
                                    }

                                    MovableObject changed = gameStateManager.getFromId(Convert.ToInt32(msgUID));

                                    //WriteToLogDebug("UID " + changed.ID + "s current direction: " + changed.Direction);

                                    break;

                                    // client is asking for the list of connected clients
                                case "getPlayers":
                                    this.WriteToLog("Client asked for Players");
                                    string players = "";
                                    // create a string with all connected clients (example 15482/1;56847/2)
                                    foreach (Client c in connectedClients)
                                    {
                                        if (players == "")
                                        {
                                            players = c.getUID() + "/" + c.getFigureType() + ";";
                                        }
                                        else
                                        {
                                            players = players + c.getUID() + "/" + c.getFigureType()+";";
                                        }
                                    }
                                    response = networkManager.createMessage();
                                    // add "getPlayser" to the string for message identification on the client and send the message
                                    response.Write("getPlayers;"+players);
                                    networkManager.sendMessage(response, msg.SenderConnection);
                                    this.WriteToLog("List of players " + players);
                                    break;

                                case "latencyTime":
                                    //this.WriteToLogDebug("Got timesync request");
                                    response = networkManager.createMessage();
                                    response.Write(msgString);
                                    networkManager.sendMessage(response, msg.SenderConnection);
                                    break;

                                case "syncTime":
                                    response = networkManager.createMessage();
                                    response.Write(msgString);
                                    // serialize the current servertime and send it to the requesting client
                                    response.Write(networkManager.Serialize(gameTime.TotalGameTime));
                                    this.WriteToLogDebug("Sent server time: " + gameTime.TotalGameTime.TotalSeconds);
                                    networkManager.sendMessage(response, msg.SenderConnection);
                                    break;
                            }

                            break;
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.StatusChanged:
                            msgString = msg.ReadString();
                            msgCon = msg.SenderConnection;
                            // Weil bei der connect-Nachricht vom Client spezielle escape-Zeichen
                            // mitgesendet werden, muss der String angepasst werden, damit er
                            // verglichen werden kann
                            string corrString = msgString.Substring(msgString.Length - 2);
                            if (corrString.CompareTo("Co") == 0)
                            {
                                try
                                {
                                    response = networkManager.createMessage();
                                    response.Write("connected");
                                    networkManager.sendMessage(response, msgCon);
                                    // create new client
                                    Client c = new Client(msgCon);
                                    // add new client to the list of connected clients
                                    connectedClients.Add(c);
                                    // add new client to the list of pending clients (clients in this list are still configuring their game options)
                                    pendingClients.Add(msgCon);

                                    this.WriteToLog("Sent connection approval to" + msg.SenderEndpoint + " with UID: "+c.getUID());
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine(ex.ToString());
                                }
                            }
                            break;
                        case NetIncomingMessageType.ErrorMessage:
                            this.WriteToLog("Error: " + msg.ReadString());
                            break;
                        default:
                            this.WriteToLog("Unhandled type: " + msg.MessageType + " -> " + msg.ReadString());
                            break;
                    }
                    server.Recycle(msg);
                }

                // All Players are ready, send start message to all connected clients
                if (pendingClients.Count == 0 && gameRunning == false && connectedClients.Count > 0)
                {
                    response = networkManager.createMessage();
                    response.Write("start");

                    foreach (Client c in connectedClients)
                    {
                        networkManager.sendMessage(response, c.getConnection());
                    }
                    gameRunning = true;
                }
            }

            gameTime.Reset();
        }
Exemplo n.º 51
0
	// Use this for initialization
	void Start () 
	{
		gLoop = Logic.GetComponent<GameLoop>(); 
	}
Exemplo n.º 52
0
 void Start()
 {
     vomitSpawn = transform.Find("vomitSpawn");
     groundCheck = transform.Find("groundCheckCop");
     mainLoop = (GameLoop) FindObjectOfType(typeof(GameLoop));
     //AudioSource.PlayClipAtPoint(zombieGroan, transform.position);
     gis = (GameInfoScript)GameObject.Find("GameWorld").GetComponent<GameInfoScript>() as GameInfoScript;
 }
Exemplo n.º 53
0
	void Start() {
		score = GetComponent<Scoring> ();
		gl = GetComponent<GameLoop> ();
		boardSFX = GetComponent<AudioSource> ();
	}
Exemplo n.º 54
0
 public MenuScreen(GameLoop game)
     : base(game)
 {
 }
Exemplo n.º 55
0
 public ScoreScreen(GameLoop game)
     : base(game)
 {
     fontscore = Content.Load<SpriteFont>("LargeFont");
     fonttext = Content.Load<SpriteFont>("ScoreFont");
 }
Exemplo n.º 56
0
 public CreditScreen(GameLoop game)
     : base(game)
 {
 }
Exemplo n.º 57
0
    void Start()
    {
        gis = (GameInfoScript)GameObject.Find("GameWorld").GetComponent<GameInfoScript>() as GameInfoScript;
        mainLoop = (GameLoop) FindObjectOfType(typeof(GameLoop));
        health = (PlayerHealth) FindObjectOfType(typeof(PlayerHealth));
        //AudioSource.PlayClipAtPoint(zombieGroan, transform.position);

        groundCheck = transform.Find("groundCheckFlood");
        beginTimer();
    }
Exemplo n.º 58
0
    // Use this for initialization
    void Start()
    {
        gameLoop = GameObject.Find("_Game").GetComponent<GameLoop>();
        spriteManagerBlocks = GameObject.Find("InitElementSpriteManager").GetComponent<LinkedSpriteManager>();

        spriteManagerGlass = GameObject.Find("InitBackGroundSpriteManager").GetComponent<LinkedSpriteManager>();
        spriteManagerGlass.AddSprite(gameObject, BackgroundWidth, BackgroundHeight,
                        new Vector2(0, 0),
                        new Vector2(1, 1),
                        new Vector3(BackgroundWidth / 2, BackgroundHeight / 2, 0),
                        false);

        glassSprites = new Sprite[VerticalBlocks, HorizontalBlocks];
    }
Exemplo n.º 59
0
	GameLoop GL;// Main game script, knows whose turn it is
	void Start () {
		GL = GameObject.Find ("GamePlay").GetComponent<GameLoop> ();
	}
Exemplo n.º 60
0
 void Start()
 {
     gis = (GameInfoScript)GameObject.Find("GameWorld").GetComponent<GameInfoScript>() as GameInfoScript;
     facingRight = false;
     mainLoop = (GameLoop) FindObjectOfType(typeof(GameLoop));
     groundCheck = transform.Find("groundCheckWalker");
     beginTimer();
     //AudioSource.PlayClipAtPoint(zombieGroan, transform.position);
 }