public ControlPage()
        {
            this.InitializeComponent();

            turn = Turn.none;
            direction = Direction.none;

            accelerometer = App.accelerometer;
            bluetooth = App.bluetooth;
            arduino = App.arduino;

            if (accelerometer == null || bluetooth == null || arduino == null)
            {
                Frame.Navigate(typeof(MainPage));
                return;
            }

            startButton.IsEnabled = true;
            stopButton.IsEnabled = true;
            disconnectButton.IsEnabled = true;

            keepScreenOnRequest = new DisplayRequest();
            keepScreenOnRequest.RequestActive();

            App.arduino.pinMode(enableA, PinMode.OUTPUT);
            App.arduino.pinMode(MotorA1, PinMode.OUTPUT);
            App.arduino.pinMode(MotorA2, PinMode.OUTPUT);

            App.arduino.pinMode(enableB, PinMode.OUTPUT);
            App.arduino.pinMode(MotorB1, PinMode.OUTPUT);
            App.arduino.pinMode(MotorB2, PinMode.OUTPUT);

            arduino.digitalWrite(enableA, PinState.HIGH);
            arduino.digitalWrite(enableB, PinState.HIGH);
        }
Example #2
0
 public Category(string title, IRule rule, Turn turn, Dice dice)
 {
     Title = title;
     _rule = rule;
     _turn = turn;
     _dice = dice;
 }
Example #3
0
 public void AddTurn(Turn _turn)
 {
     if (m_trns == null) {
         m_trns = new List<Turn> ();
     }
     m_trns.Add (_turn);
 }
 public Connect4Board()
 {
     columns = new Connect4Column[COLUMNS];
     for (int i = 0; i < columns.Length; i++)
         columns[i] = new Connect4Column();
     turn = Turn.NOT_IN_SESSION;
 }
Example #5
0
 public void SetUp()
 {
     _turn = Substitute.For<Turn>();
     _dice = Substitute.For<Dice>();
     _onesRule = Substitute.For<IRule>();
     _category = new Category("Ones", _onesRule, _turn, _dice);
 }
        public DefaultMoveExecutor(string board, string newMove, Turn turn,
            GameState gameState, string whiteKingPosition, string blackKingPosition, string lastMove,
            bool whiteCanCastleKingSide, bool whiteCanCastleQueenSide, bool blackCanCastleKingSide,
            bool blackCanCastleQueenSide)
        {
            FieldPosition whiteKing = FieldPosition.ParsePosition(whiteKingPosition);
            FieldPosition blackKing = FieldPosition.ParsePosition(blackKingPosition);

            this.oldState = new BoardModel(GetBoard(board), turn, gameState, whiteKing, blackKing,
                whiteCanCastleKingSide, whiteCanCastleQueenSide, blackCanCastleKingSide, blackCanCastleQueenSide);

            this.newState = new BoardModel(GetBoard(board), turn, gameState, whiteKing, blackKing,
                whiteCanCastleKingSide, whiteCanCastleQueenSide, blackCanCastleKingSide, blackCanCastleQueenSide);

            // Parse new move
            string[] splt = newMove.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            this.source = FieldPosition.ParsePosition(splt[0]);
            this.dest = FieldPosition.ParsePosition(splt[1]);

            if (lastMove != null)
            {
                // Parse last move
                splt = lastMove.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                this.lastMoveSource = FieldPosition.ParsePosition(splt[0]);
                this.lastMoveDest = FieldPosition.ParsePosition(splt[1]);
            }

            this.sourcePiece = this.newState.Board[source.Row, source.Col];
        }
        public ControlPage()
        {
            this.InitializeComponent();

            turn = Turn.none;
            direction = Direction.none;

            accelerometer = App.accelerometer;
            bluetooth = App.bluetooth;
            arduino = App.arduino;

            if( accelerometer == null || bluetooth == null || arduino == null )
            {
                Frame.Navigate( typeof( MainPage ) );
                return;
            }

            startButton.IsEnabled = true;
            stopButton.IsEnabled = true;
            disconnectButton.IsEnabled = true;

            bluetooth.ConnectionLost += Bluetooth_ConnectionLost;

            keepScreenOnRequest = new DisplayRequest();
            keepScreenOnRequest.RequestActive();

            App.arduino.pinMode( LR_DIRECTION_CONTROL_PIN, PinMode.OUTPUT );
            App.arduino.pinMode( FB_DIRECTION_CONTROL_PIN, PinMode.OUTPUT );
            App.arduino.pinMode( LR_MOTOR_CONTROL_PIN, PinMode.PWM );
            App.arduino.pinMode( FB_MOTOR_CONTROL_PIN, PinMode.PWM );

            App.arduino.pinMode(HEARTBEAT_LED_PIN, PinMode.OUTPUT);
        }
Example #8
0
    void Start () {
        runeBucket = new List<Rune>();
		currentEffects = new List<StatusEffect>();
		turn = new Turn();
		animator = GetComponent<Animator>();
        sprRend = GetComponent<SpriteRenderer>();
	}
Example #9
0
	public void TurnCleanup() {
		turn = new Turn();
		currentEffects.Remove(StatusEffect.Confuse);
        currentEffects.Remove(StatusEffect.Paralyse);
		currentEffects.Remove(StatusEffect.Shield);

	}
Example #10
0
        public GoldRush()
        {
            m_currentTurn = Turn.Start;
            m_numbersLeft = new List<short>[3];
            m_board = new short[Players, N];

            for (int i = 0; i < Players; i++)
            {
                m_numbersLeft[i] = new List<short>();
            }
            for (short i = 1; i <= N; i++)
            {
                m_numbersLeft[User].Add(i);
                m_numbersLeft[Opponent].Add(i);
                m_numbersLeft[Computer].Add(i);
            }

            m_history = new Dictionary<string, List<short[]>>();
            m_guaranteedPerson = new List<string>();
            m_dateToPlayers = new Dictionary<DateTime, List<string>>();
            m_isGuaranteedPerson = false;
            m_joinDate = DateTime.MinValue;
            Load();
             //   OptimalBet();
            Go();
        }
Example #11
0
        private static void BerzerkMovement(Turn gameLogTurn, int distance, Combatant active,
            int speedNotFiring, int speedFiring, int direction, int enemyPos, int oldPos)
        {
            if (distance > 0)
            {
                // run to enemy!
                gameLogTurn.Movement.Add(new Phase { Actor = active.Template, Message = active.Name + " runs towards the enemy in blind fury!", Relevance = Relevance.Medium, Icon = moveIcon});

                var movement = speedNotFiring*direction;
                int newPos = active.Position + (movement <= distance ? movement : distance);
                if (newPos == enemyPos)
                {
                    gameLogTurn.Movement.Add(new Phase { Actor = active.Template, Message = active.Name + " enters close combat!", Relevance = Relevance.High, Icon = chargeIcon });
                    active.Melee = true;
                }

                if (speedFiring <= Math.Abs(oldPos - newPos))
                    active.CanFire = true;
                else
                    active.CanFire = false;

                active.Position = newPos;
            }
            else
            {
                gameLogTurn.Movement.Add(new Phase { Actor = active.Template, Message = active.Name + " hurls himself into the melee!", Relevance = Relevance.Medium, Icon = chargeIcon });
                active.CanFire = true;
            }
        }
        public ControlPageMaisto()
        {
            this.InitializeComponent();

            turn = Turn.none;
            direction = Direction.none;

            accelerometer = App.accelerometer;
            bluetooth = App.bluetooth;
            arduino = App.arduino;

            if( accelerometer == null || bluetooth == null || arduino == null )
            {
                Frame.Navigate( typeof( MainPage ) );
                return;
            }

            startButton.IsEnabled = true;
            stopButton.IsEnabled = true;
            disconnectButton.IsEnabled = true;

            bluetooth.ConnectionLost += Bluetooth_ConnectionLost;

            keepScreenOnRequest = new DisplayRequest();
            keepScreenOnRequest.RequestActive();

            App.arduino.pinMode( FORWARD_CONTROL_PIN, PinMode.OUTPUT );
            App.arduino.pinMode( REVERSE_CONTROL_PIN, PinMode.OUTPUT );
            App.arduino.pinMode( LEFT_CONTROL_PIN, PinMode.OUTPUT );
            App.arduino.pinMode( RIGHT_CONTROL_PIN, PinMode.OUTPUT );
        }
Example #13
0
 private static bool CheckForPairs(Turn thisGame)
 {
     var isPairs = false;
     var firstValue = thisGame.CurrentDice[0].Value;
     var quantityOfFirstValue = CountQuantityOfAValue(firstValue, thisGame);
     var secondValue = firstValue;
     var i = 0;
     while (firstValue == secondValue && i < 6)
     {
         secondValue = thisGame.CurrentDice[i].Value;
         i++;
     }
     var quantityOfSecondValue = CountQuantityOfAValue(secondValue, thisGame);
     var thirdValue = firstValue;
     var quantityOfThirdValue = 0;
     i = 0;
     while ((firstValue == thirdValue || secondValue == thirdValue) && i < 6)
     {
         thirdValue = thisGame.CurrentDice[i].Value;
         i++;
     }
     if (i != 7)
         quantityOfThirdValue = CountQuantityOfAValue(thirdValue, thisGame);
     if (quantityOfFirstValue == 2 && quantityOfSecondValue == 2 && quantityOfThirdValue == 2)
         isPairs = true;
     return isPairs;
 }
Example #14
0
 internal GlobalBoardTurn(Turn turn, Card draw)
 {
     PlayCard = turn.Card;
     PlayIsDiscard = turn.Discard;
     DrawCard = draw;
     DrawLocation = turn.Draw;
 }
Example #15
0
 void SetActionToFree()
 {
     actionTurn = Turn.free;
     if(FreeAction != null){
         FreeAction();
     }
 }
Example #16
0
        public void ExpectCanExecuteAlwaysFalseIfIfTurnNotStarted(GameCommand command)
        {
            var player = new Mock<IPlayer>();
            var provider = new Mock<IStateProvider>();

            var turn = new Turn(player.Object, provider.Object);
            Assert.False(turn.CanExecute(command));
        }
 public TimerEventArgs(int seconds, int playerSeconds, int opponentSeconds, bool running, Turn turn)
 {
     Seconds = seconds;
     Running = running;
     PlayerSeconds = playerSeconds;
     OpponentSeconds = opponentSeconds;
     CurrentTurn = turn;
 }
Example #18
0
        public void CreateTurnTest()
        {
            var player = new Mock<IPlayer>();
            var provider = new Mock<IStateProvider>();

            var turn = new Turn(player.Object, provider.Object);
            Assert.Equal(player.Object, turn.Player);
        }
Example #19
0
 private static bool CheckForSingles(Turn thisGame)
 {
     for (var i = 0; i < 6; i++)
         if (thisGame.CurrentDice[i].State.Equals(DieState.Unclicked)
             && (thisGame.CurrentDice[i].Value == 1 || thisGame.CurrentDice[i].Value == 5))
             return true;
     return false;
 }
Example #20
0
 // Use this for initialization
 void Start()
 {
     Pturn = true;
     AIturn = false;
     instance = this;
     endgamecanvas = GameObject.Find ("WinnerCanvas");
     endgamecanvas.GetComponent<Canvas> ().enabled=false;
 }
Example #21
0
 protected BaseSolver Add(Turn turn, string description = null)
 {
     if (description != null)
     {
         this.Description.Add(description);
     }
     this.Turns.Add(turn);
     return this;
 }
Example #22
0
File: Game.cs Project: britg/Troped
	public void Init () {
    level = new Level();
    level.Init();
		player = new Player();
    player.pos = level.playerTile;
    player.rotation = level.playerRotation;
		turn = Turn.None;
    enemies = new List<Enemy>();
	}
Example #23
0
File: Game.cs Project: britg/Troped
	public void NextTurn () {
		if (turn == Turn.Player) {
			turn = Turn.Enemies;
      TakeEnemyTurns();
		} else {
			turn = Turn.Player;
      player.NewTurn();
		}
	}
Example #24
0
 public static void endPlayerTurn()
 {
     current_turn = Turn.Enemy;
     //		entityManagerS.getMech().current_ap =  entityManagerS.getMech().max_ap;
     entityManagerS.getMech().destroySelectionHexes();
     entityManagerS.getMech().allowSelectionHexesDraw();
     enemy_enumerator = entityManagerS.getEnemies().GetEnumerator();
     entityManagerS.getMech().current_ap =  0;
 }
Example #25
0
 void nextTurn()
 {
     //restore all moved/used units to their prior colors.
     Recolor();
     //swap turns
     turn = (turn == Turn.PLAYER) ? Turn.ENEMY : Turn.PLAYER;
     turnDisplayScript.updateTurn(turn == Turn.PLAYER ? 0 : 1);
     if (turn == Turn.PLAYER) nextRound(); //this should always be true. if we have first changed turns, and now are on the (primary) player's turn again, then we have completed a round.
     //maybe do some graphical stuff here.
 }
    //-----END OF CONSTRUCTORS-----
    //-----START OF MUTATOR METHODS-----
    public void AddTurn(Turn newTurn)
    {
        int i = 0;
        for (; i < turns.Count && newTurn.GetTime() < turns[i].GetTime(); i++)
        {
            //Most of the logic of incrementation and whatnot is done by the for above.
        }

        turns.Insert(i, newTurn);
    }
Example #27
0
    // Update is called once per frame
    void Update()
    {
        if(bIsFirstUpdate)
        {
            Player	= GameObject.FindGameObjectWithTag("Player") as GameObject;
            TheVoid = GameObject.FindGameObjectWithTag("TheVoid") as GameObject;

            PlayerScript	=	Player.GetComponent<PlayerMovement>();
            TheVoidScript	=	TheVoid.GetComponent<VoidAI>();

        }

        //print ("GameLoop UPDATE");

        print ("Is Player Turn? : "+PlayerScript.GetIsPlayerTurn());
        print ("Is Void's Turn? : "+TheVoidScript.GetIsVoidsTurn());

        if(!PlayerScript.GetIsPlayerTurn() && !TheVoidScript.GetIsVoidsTurn())
        {
            //print ("+++++++++++++++++++++++VOID TURN++++++++++++++++++++++");
            if(bIsFirstUpdate)
            {
                TheVoidScript.SetIsVoidsTurn(true);
                bIsFirstUpdate=false;
                lastTurn=Turn.VoidTurn;
            }
            else
                if(lastTurn==Turn.VoidTurn)
                {
                print ("Player Turn");
                //PASSE LE TOUR AU JOUEUR
                    TheVoidScript.SetIsVoidsTurn(false);
                    PlayerScript.SetIsPlayerTurn(true);
                    lastTurn=Turn.PlayerTurn;
                }
            else
                if(lastTurn==Turn.PlayerTurn)
                {
                print ("Void Turn");
                //PASSE LE TOUR A L'ENNEMI
                    TheVoidScript.SetIsVoidsTurn(true);
                    PlayerScript.SetIsPlayerTurn(false);
                    lastTurn=Turn.VoidTurn;
                }
        }

        bHasPlayerWon=PlayerScript.GetHasWon();
        bHasTheVoidWon=TheVoidScript.GetHasWon();

        if(bHasPlayerWon || bHasTheVoidWon)
        {
            print ("============------------+++++++++GAME OVER+++++++++------------================");
            Application.LoadLevel("gameOver");
        }
    }
Example #28
0
 public static Turn StringToTurn( string str)
 {
     //TODO...
     //		Debug.Log("Turn: string recieved: "+str);
     Turn ret = new Turn();
     string[] splitStr = str.Split(';');
     foreach( string s in splitStr){
         ret.Add(Order.StringToOrder(s));
     }
     return ret;
 }
        public BandController( RemoteDevice device ) : base( device )
        {
            connected = false;
            turn = Turn.none;
            direction = Direction.none;

            Device.pinMode( LR_DIRECTION_CONTROL_PIN, PinMode.OUTPUT );
            Device.pinMode( FB_DIRECTION_CONTROL_PIN, PinMode.OUTPUT );
            device.pinMode( LR_MOTOR_CONTROL_PIN, PinMode.PWM );
            device.pinMode( FB_MOTOR_CONTROL_PIN, PinMode.PWM );
        }
Example #30
0
 public static bool CheckIfThereIsSomethingToScore(Turn thisGame)
 {
     if (NumberToBeChecked(thisGame) == 6)
     {
         if (CheckForSixOfAKind(thisGame) || CheckForPairs(thisGame) || CheckForRunOfSix(thisGame))
             return true;
     }
     if (NumberToBeChecked(thisGame) >= 3)
         if (CheckForThreeOfAKind(thisGame))
             return true;
     return CheckForSingles(thisGame);
 }
Example #31
0
        public void It_Should_ReturnScoreForPairs_When_PlacedOnPairs_And_PairsIsValid()
        {
            //Arrange
            var fiveMockDice = new List <IDie>
            {
                new EchoDie(1),
                new EchoDie(1),
                new EchoDie(2),
                new EchoDie(3),
                new EchoDie(4),
            };


            var turn = new Turn(fiveMockDice);
            //turn.RollDice();
            var scoreCard = new ScoreCard();

            //Act
            scoreCard.UpdateScoreCard(ScoreCategory.Pairs, turn.Dice);

            //Assert
            Assert.Equal(2, scoreCard.Total);
        }
Example #32
0
        public LevelWithTurns(string[] words, int numberOfTurns, float time)
        {
            if (numberOfTurns <= 0)
            {
                throw new System.ArgumentOutOfRangeException(numberOfTurns + " is out of range.");
            }

            if (time <= 0.0f)
            {
                throw new System.ArgumentOutOfRangeException(time + " is out of range.");
            }

            turns = new Turn[numberOfTurns];

            for (int i = 0; i < numberOfTurns; i++)
            {
                turns[i] = new Turn(words[i]);
            }

            indexCurrentTurn    = 0;
            this.time           = time;
            currentTurnTimeLeft = time;
        }
Example #33
0
        public void It_Should_ReturnFiveValues_When_DiceAreRolled()
        {
            //arrange
            var fiveMockDice = new List <IDie>
            {
                new RandomDie(),
                new RandomDie(),
                new RandomDie(),
                new RandomDie(),
                new RandomDie(),
            };
            var turn = new Turn(fiveMockDice);


            //act
            turn.RollDice();

            //assert
            foreach (var die in turn.Dice)
            {
                Assert.NotEqual(0, die.Value);
            }
        }
Example #34
0
 public static Turn Update(Turn turn, IPlayer blackPlayer, IPlayer whitePlayer, List <Step> steps)
 {
     if (steps.Count == 0)
     {
         if (turn == Turn.Black)
         {
             if (whitePlayer.PlayerState == PlayerState.Blocked)
             {
                 turn = Turn.Black;
             }
             turn = Turn.White;
         }
         else// white turn
         {
             if (blackPlayer.PlayerState == PlayerState.Blocked)
             {
                 turn = Turn.White;
             }
             turn = Turn.Black;
         }
     }
     return(turn);
 }
Example #35
0
 public static Step ConvertToStep(int slotIdSource, int slotIdDestination, Turn turn)
 {
     if (turn == Turn.White)
     {
         if (slotIdSource == int.MinValue)
         {
             slotIdSource = RulesContainer.FinishedSlotBlack;
         }
         return(new Step {
             Value = slotIdDestination - slotIdSource
         });
     }
     else // black turn
     {
         if (slotIdSource == int.MinValue)
         {
             slotIdSource = RulesContainer.FinishedSlotWhite;
         }
         return(new Step {
             Value = slotIdSource - slotIdDestination
         });
     }
 }
Example #36
0
 //↑
 //↓创建棋子,被此脚本中Update ()调用
 public void CreateChess(int i, int j, Turn which)
 {
     Last_x[Lasts]         = i;
     Last_y[Lasts]         = j;
     Lasts                += 1;
     CHess_UIM.ChessNumber = Lasts;
     D_Time                = 20;
     StopDJS(true, true);
     if (which == Turn.white)
     {
         Whites[Whites_i] = (GameObject)GameObject.Instantiate(White, new Vector3(ChessPos[i, j].x, ChessPos[i, j].y, -0.5f), White.transform.rotation);
         Whites_i        += 1;
         chessTurn        = Turn.black;
         CHess_UIM.AddChessRoad(i, j, "白");
     }
     else if (which == Turn.black)
     {
         Blacks[Blacks_i] = (GameObject)GameObject.Instantiate(Black, new Vector3(ChessPos[i, j].x, ChessPos[i, j].y, -0.5f), Black.transform.rotation);
         Blacks_i        += 1;
         chessTurn        = Turn.white;
         CHess_UIM.AddChessRoad(i, j, "黑");
     }
 }
Example #37
0
 protected virtual void FinishTurn()
 {
     if (currentTurn.objectivesFilled.Count > 0)
     {
         if (NotifyObjectivesFilled != null)
         {
             NotifyObjectivesFilled.Invoke(currentTurn.objectivesFilled);
         }
         // Not listened at the moment. Could replace the commands way
         //else
         //    Debug.LogError("This should be listened to");
     }
     if (state == State.PLAYING_TURN && currentTurn.WasUseful())
     {
         history.Push(currentTurn);
     }
     state       = State.IDLE;
     currentTurn = null;
     if (!CheckLevelFinished() && inputs.Count > 0)
     {
         ExecuteCommand(inputs.Dequeue());
     }
 }
        public void It_Should_Return_SumOfFours_When_PlacedOnFours_And_GivenFours()
        {
            //Arrange
            var fiveMockDice = new List <IDie>
            {
                new EchoDie(1),
                new EchoDie(1),
                new EchoDie(2),
                new EchoDie(4),
                new EchoDie(4),
            };

            var turn = new Turn(fiveMockDice);

            turn.RollDice();


            //Act
            var foursCalculator = CategoryCalculatorFactory.CreateCalculator(ScoreCategory.Fours, turn.Dice);

            //Assert
            Assert.Equal(8, foursCalculator.Calculate());
        }
Example #39
0
 IEnumerator displayDialog()
 {
     while (dialogueGenerator.hasNextOutput())
     {
         Turn   turn      = dialogueGenerator.getOutput();
         string utterance = turn.utterance;
         utterance = utterance.Replace("<agent1>", agent1.gameObject.GetComponent <AgentScript>().name);
         utterance = utterance.Replace("<agent2>", agent2.gameObject.GetComponent <AgentScript>().name);
         if ((string)(turn.participant) == "<agent1>")
         {
             agent1.gameObject.GetComponent <AgentScript>().SetCurrentPhrase(utterance);
             agent2.gameObject.GetComponent <AgentScript>().SetCurrentPhrase("");
         }
         else
         {
             agent1.gameObject.GetComponent <AgentScript>().SetCurrentPhrase("");
             agent2.gameObject.GetComponent <AgentScript>().SetCurrentPhrase(utterance);
         }
         yield return(new WaitForSeconds(turnTime));
     }
     agent1.gameObject.GetComponent <AgentScript>().SetCurrentPhrase("");
     agent2.gameObject.GetComponent <AgentScript>().SetCurrentPhrase("");
 }
Example #40
0
        private void AddToGreen()
        {
            if (_inputValue == -1)
            {
                return;
            }

            var turn = new Turn();

            if (Settings.Instance.ColorScheme.RightToLeft)
            {
                turn.PointsRight = Convert.ToByte(_inputValue);
            }
            else
            {
                turn.PointsLeft = Convert.ToByte(_inputValue);
            }

            this.Match.AddTurn(turn);


            _inputValue = -1;
        }
Example #41
0
    private void OnEnterTurn(Turn oldturn, Turn newturn)
    {
        switch (newturn)
        {
        case Turn.Invalid:
            break;

        case Turn.Attacker:
        {
            m_attackerTeam.DoAttack();
        }
        break;

        case Turn.Defender:
        {
            m_defenderTeam.DoAttack();
        }
        break;

        default:
            break;
        }
    }
Example #42
0
        public BoardState Apply(BoardState state, Turn turn)
        {
            if (turn is Move move)
            {
                var(f, c) = state[move.From] ?? throw new UserError($"There are no figure at {move.From}");

                if (move.From == move.To)
                {
                    throw new RuleViolationError(new RuleViolation("Figure can't move to the same cell"));
                }

                state = state.Without(move.From);

                if (state[move.To].HasValue)
                {
                    state = state.Without(move.To);
                }

                return(state.With(f, c, move.To));
            }

            throw new NotSupportedException();
        }
Example #43
0
        public IPlayer NextTurn()
        {
            switch (_playerTurnAction)
            {
            case Turn.None:
                _playerTurnAction = Turn.Roll;
                break;

            case Turn.Roll:
                _playerTurnAction = Turn.Advance;
                break;

            case Turn.Advance:
                _playerTurn       = (_playerTurn + 1) % _players.Count();
                _playerTurnAction = Turn.Roll;
                break;

            default:
                throw new Exception("Unknown turn");
            }

            return(_players.ElementAt(_playerTurn));
        }
Example #44
0
    public async Task ExecuteTurn(Turn turn)
    {
        Debug.Log($"Executando o turno de {BattlerName}.");

        if (turn == null)
        {
            return;
        }

        if (turn.Skill.ApCost > CurrentAp)
        {
            Debug.LogError(
                $"{BattlerName} tentou usar uma skill com custo maior que o EP Atual. SkillName: {turn.Skill.SkillName}, SkillCost: {turn.Skill.ApCost}, CurrentAp: {CurrentAp}");
        }

        CurrentAp -= turn.Skill.ApCost;

        QueueAction(() => { BattleController.Instance.battleCanvas.battleInfoPanel.ShowInfo(turn.Skill.SkillName); });

        await AnimateTurn(turn);

        QueueAction(() => { BattleController.Instance.battleCanvas.battleInfoPanel.HideInfo(); });
    }
Example #45
0
    public void Calculate()
    {
        int       index = 0;
        int       count = vertices.Count;
        Direction turn;

        for (index = 0; index < count - 1; index++)
        {
            try
            {
                turn = Turn.GetDirection(vertices[index - 1], vertices[index], vertices[index + 1]);
            }
            catch
            {
                turn = Direction.FORWARD;
            }

            if (!withPrepend || index > 0)
            {
                waypoints.AddRange(new Segment(vertices[index], vertices[index + 1], turn).GetPath());
            }
        }
    }
 public void NextTurn()
 {
     //Called By the Next Turn Button
     if (currentTurn.Equals(Turn.team1))
     {
         team1Done   = true;
         currentTurn = Turn.team2;
     }
     else
     {
         team2Done   = true;
         currentTurn = Turn.team1;
     }
     if (team1Done && team2Done)
     {
         textUpdate.UpdateTurnCountText();
         team1Done = false;
         team2Done = false;
     }
     actionBlocked = false;
     ResetHighLights();
     gameState = GameState.startTurn;
 }
Example #47
0
        public void NewTurn()
        {
            if (!Game.GetCities().Any(x => this == x.Owner) && !Game.Instance.GetUnits().Any(x => this == x.Owner))
            {
                GameTask.Enqueue(Turn.GameOver(this));
            }

            if (_anarchy == 0 && Government is Anarchy)
            {
                if (Human == Game.CurrentPlayer)
                {
                    GameTask.Enqueue(Show.ChooseGovernment);
                }
                else
                {
                    Government = new Despotism();
                }
            }
            if (_anarchy > 0)
            {
                _anarchy--;
            }
        }
Example #48
0
        public TimeSpan isEmpty(DateTime time, int DoctorId, int TypeId, int clinicId)
        {
            List <Turn> list = context.Doctors.Include("Turns").Include("Turns.TurnType").FirstOrDefault(d => d.Id == DoctorId && d.ClinicId == clinicId).Turns.OrderBy(d => d.StartDate).ToList();
            Turn        next = list.Where(a => a.StartDate > time).FirstOrDefault();

            if (list.Where(a => a.StartDate == time).FirstOrDefault() == null)
            {
                if (next == null || next.StartDate >= time + context.TurnTypes.FirstOrDefault(t => t.Id == TypeId).Duration)
                {
                    return(new TimeSpan());
                }
                else
                {
                    TimeSpan distance;
                    distance = next.StartDate - time + next.TurnType.Duration;
                    return(distance);
                }
            }
            else
            {
                return(list.Where(a => a.StartDate == time).FirstOrDefault().TurnType.Duration);
            }
        }
Example #49
0
        public void ConfirmTurnAlreadyConfirmed()
        {
            var returnTurn = new Turn(It.IsAny <Guid>(), It.IsAny <DateTime>(), It.IsAny <string>(), new List <int>())
            {
                Confirmed = true
            };
            var model = new ConfirmTurnModel()
            {
                TurnId = Guid.NewGuid()
            };

            _turnRepo.Setup(x => x.Get(It.IsAny <Guid>()))
            .Returns(returnTurn)
            .Verifiable();
            //_turnRepo.Setup(x => x.Update(It.Is<Turn>(t => t.Confirmed == true)))
            //    .Verifiable();
            //_uow.Setup(x => x.Save()).Verifiable();


            Assert.Throws <TurnExceptionAlreadyEXist>(() => _service.Execute(model));
            _turnRepo.VerifyAll();
            _uow.VerifyAll();
        }
Example #50
0
        private async void CompDrawAsync(object obj, Turn first)
        {
            MyPictureBox compClicked = obj as MyPictureBox;

            await Task.Delay(1000);

            if (first == Turn.Human)
            {
                for (int i = 0; i < 12; i++)
                {
                    Invoke(new Action(() => compClicked.Image = imageCircle[i]));
                    await Task.Delay(50);
                }
            }
            else
            {
                for (int i = 0; i < 12; i++)
                {
                    Invoke(new Action(() => compClicked.Image = imageCross[i]));
                    await Task.Delay(50);
                }
            }
        }
Example #51
0
        private static double GetAlternativeMatchScore(Turn eTurn, IList <ComparableItem> arComparableItemsA, IList <ComparableItem> arComparableItemsB, int iIndexInA, int iIncrementA, int iIndexInB, int iIncrementB)
        /* suppose we find a similar element. are we sure this is the right one ? maybe the similarity is a chance similarity and doesn't originate from a common ancestor ?*/
        /* so here  is the part where we try to match the forced matched element with its best match in its vicinity*/
        {
            double dScore = 0;
            int    ii     = 0;

            if (eTurn == Turn.A)
            {
                for (ii = 0; ii < iIncrementB + 100 && ii + iIndexInA < arComparableItemsA.Count; ii++)
                {
                    dScore = Math.Max(dScore, GetMatchScore(arComparableItemsA[ii].Node, arComparableItemsB[iIndexInB + iIncrementB].Node));
                }
            }
            else if (eTurn == Turn.B)
            {
                for (ii = 0; ii < iIncrementA + 100 && ii + iIndexInB < arComparableItemsB.Count; ii++)
                {
                    dScore = Math.Max(dScore, GetMatchScore(arComparableItemsA[iIndexInA + iIncrementA].Node, arComparableItemsB[ii].Node));
                }
            }
            return(dScore);
        }
Example #52
0
    // Updates the score, determines the trick winner, updates
    // the states for the next trick, hides the played cards and
    // deals a new card each.
    private IEnumerator EndTrick()
    {
        yield return(new WaitForSeconds(endTrickWaitTime));

        int trickPoints = GetTrickPoints();
        int newScore    = int.Parse(scoreDisplay.text) + trickPoints;

        scoreDisplay.text = newScore.ToString();

        bool playerWon = DidPlayerWin();

        HideMovedCards();
        if (!deck.IsEmpty())
        {
            DealCardEach(playerWon);
        }

        if (!playerHand.IsEmpty())
        {
            SetTurnOrder(playerWon);
        }
        refState = Turn.Finish;
    }
Example #53
0
    /// <summary>
    /// Called when a unit is destroyed to remove it from the turn list.
    /// </summary>
    /// <param name="unit">The unit that has been destroyed.</param>
    public void UnitDestroyed(BattleUnit unit)
    {
        _livingUnits.Remove(unit);

        Turn deadTurn = _turnOrder.FirstOrDefault(s => s.Unit == unit);

        if (deadTurn != null)
        {
            Queue <Turn> restructure = new Queue <Turn>();

            while (_turnOrder.Count > 0)
            {
                Turn turn = _turnOrder.Dequeue();

                if (turn != deadTurn)
                {
                    restructure.Enqueue(turn);
                }
            }

            _turnOrder = restructure;
        }
    }
Example #54
0
        private void TimerTick(object sender, EventArgs e)
        {
            if (space == null)
            {
                return;
            }
            Turn control =
                left
                ? Turn.Left
                : right
                ? Turn.Right
                : autopilotEnabled
                ? Autopilot(space.Rocket, space.Target)
                : Turn.None;

            space.Move(ClientRectangle, control);
            if ((space.Rocket.Location - space.Target).Length < 40)
            {
                timer.Stop();
            }
            Invalidate();
            Update();
        }
Example #55
0
 private void selectAction()
 {
     if (Input.GetButtonDown("Horizontal"))
     {
         if (Input.GetAxis("Horizontal") > 0)
         {
             if (menuIndex == menuOptions.Length - 1)
             {
                 menuIndex = 0;
             }
             else
             {
                 menuIndex++;
             }
         }
         else
         {
             if (menuIndex == 0)
             {
                 menuIndex = menuOptions.Length - 1;
             }
             else
             {
                 menuIndex--;
             }
         }
         playSound(0);
     }
     else if (Input.GetKeyDown(KeyCode.X))
     {
         if (turn == Turn.P2Choice)
         {
             turn = Turn.P1Choice;
             playSound(0);
         }
     }
 }
Example #56
0
    private void setUp()
    {
        //Sets up the players and enemies
        GameObject character1 = Instantiate(player1) as GameObject;
        GameObject character2 = Instantiate(player2) as GameObject;

        p1 = character1.GetComponent <Character> ();
        p2 = character2.GetComponent <Character> ();
        GameObject boss1 = Instantiate(bossObject) as GameObject;

        boss      = boss1.GetComponent <Enemy>();
        boss.Slot = 1;
        boss.setSlot();
        boss.data().setMaxHealth(400);
        boss.data().setAttack(50);
        turnOrder = new GameObject[3];

        //Manages enemy selection
        selectedSlot = 0;
        GameObject theCursor = Instantiate(cursor) as GameObject;

        theCursor.GetComponent <Renderer>().enabled = false;
        selector = theCursor.GetComponent <AnimationOffset>();
        selector.setParent(boss.gameObject);

        menuOptions    = new string[4];
        menuOptions[0] = "Attack";
        menuOptions[1] = "Magic";
        menuOptions[2] = "Items";
        menuOptions[3] = "Flee";
        menuIndex      = 0;

        turn     = Turn.P1Choice;
        nextTurn = Turn.P1Choice;

        totalExpReward = 0;
    }
        /// <summary>
        /// Шифр "Поворотная решетка".
        /// </summary>
        /// <param name="message"> Открытое сообщение. </param>
        /// <param name="grid"> Трафарет. </param>
        /// <param name="turn1"> Первый поворот. </param>
        /// <param name="turn2"> Второй поворот. </param>
        /// <param name="turn3"> Третий поворот. </param>
        /// <param name="route"> Маршрут выписывания. </param>
        /// <returns> Закрытое сообщение. </returns>
        public static string RotaryGrid(string message, bool[,] grid, Turn turn1, Turn turn2, Turn turn3, Route route)
        {
            int n = grid.GetLength(0);
            int m = grid.GetLength(1);

            if (n * m < message.Length)
            {
                throw new ArgumentException("Недопустимый размер матрицы.");
            }

            message       = message.Replace(' ', '_');
            message       = message.PadRight(n * m, '_');
            char[,] table = new char[n, m];
            int[] keyN = new int[n];
            for (int i = 0; i < n; i++)
            {
                keyN[i] = n - i - 1;
            }
            int[] keyM = new int[m];
            for (int i = 0; i < m; i++)
            {
                keyM[i] = m - i - 1;
            }

            table = InscribeWithGrid(table, grid, ref message);
            grid  = (turn1 == Turn.Vertically) ? PermutationTablesColumns(grid, keyM) :
                    PermutationTablesRows(grid, keyN);
            table = InscribeWithGrid(table, grid, ref message);
            grid  = (turn2 == Turn.Vertically) ? PermutationTablesColumns(grid, keyM) :
                    PermutationTablesRows(grid, keyN);
            table = InscribeWithGrid(table, grid, ref message);
            grid  = (turn3 == Turn.Vertically) ? PermutationTablesColumns(grid, keyM) :
                    PermutationTablesRows(grid, keyN);
            table = InscribeWithGrid(table, grid, ref message);

            return(GetStringFromTableByRoute(table, route));
        }
Example #58
0
    /**
     * Turns the wolf so now they are running in a new direction based on current inputs
     * and the turnTrigger we're currently inside.
     * @see Turn.cs for more information.
     */
    private void turn()
    {
        if (turnTrigger == null)
        {
            Debug.LogWarning("A call to turn, but no turnTrigger object is set!");
            return;
        }

        FacingDir newDirection = FacingDir.UP_RIGHT;

        switch (facingDirection)
        {
        case FacingDir.UP_RIGHT:   newDirection = leftPressed ? FacingDir.UP_LEFT : FacingDir.DOWN_RIGHT; break;

        case FacingDir.UP_LEFT:    newDirection = leftPressed ? FacingDir.DOWN_LEFT : FacingDir.UP_RIGHT; break;

        case FacingDir.DOWN_RIGHT: newDirection = leftPressed ? FacingDir.UP_RIGHT : FacingDir.DOWN_LEFT; break;

        case FacingDir.DOWN_LEFT:  newDirection = leftPressed ? FacingDir.DOWN_RIGHT : FacingDir.UP_LEFT; break;
        }

        if (!turnTrigger.allowsDirection(newDirection))
        {
            return;
        }

        setFacingDirection(newDirection);
        if (turnTrigger.centerOnTurn)
        {
            setPosition(turnTrigger.transform.position, true);
        }

        if (turnTrigger.onlyTurnOnce)
        {
            turnTrigger = null;
        }
    }
        private void handleTurn(double lr)
        {
            //left and right turns work best using digital signals

            if (lr < -LR_MAG)
            {
                //if we've switched directions, we need to be careful about how we switch
                if (turn != Turn.left)
                {
                    //make sure we aren't turning right
                    arduino.digitalWrite(RIGHT_CONTROL_PIN, PinState.LOW);
                }

                //start the motor by setting the pin high
                arduino.digitalWrite(LEFT_CONTROL_PIN, PinState.HIGH);
                turn = Turn.left;
            }
            else if (lr > LR_MAG)
            {
                if (turn != Turn.right)
                {
                    //make sure we aren't turning left
                    arduino.digitalWrite(LEFT_CONTROL_PIN, PinState.LOW);
                }

                //start the motor by setting the pin high
                arduino.digitalWrite(RIGHT_CONTROL_PIN, PinState.HIGH);
                turn = Turn.right;
            }
            else
            {
                //stop any pins that may be high
                arduino.digitalWrite(LEFT_CONTROL_PIN, PinState.LOW);
                arduino.digitalWrite(RIGHT_CONTROL_PIN, PinState.LOW);
                turn = Turn.none;
            }
        }
Example #60
0
        public void Input(string input, ulong userId = 1)
        {
            if (State != State.Active)
            {
                return;
            }
            LastPlayed = DateTime.Now;

            int column = int.Parse(StripPrefix(input)) - 1;

            if (!AvailableColumns(board).Contains(column))
            {
                return;                                            // Column is full
            }
            DropPiece(board, column, Turn);

            Time++;

            if (FindWinner(board, Turn, Time, highlighted))
            {
                Winner = Turn;
            }
            else if (IsTie(board, Turn, Time))
            {
                Winner = Player.Tie;
            }

            if (Winner == Player.None)
            {
                Turn = Turn.OtherPlayer();
            }
            else
            {
                State = State.Completed;
                Turn  = Winner;
            }
        }