Ejemplo n.º 1
0
 private void OnAddressChange(string input)
 {
     address = input;
     setAddressField.Value = address;
     RefreshStartButtonInteractable();
     BalugaDebug.Log("Address " + address);
 }
        private void DoPromote(PromoteCommand command)
        {
            int pieceOnStart = board.PieceOnSpace(command.piecePos);

            if (pieceOnStart >= 0)
            {
                Piece piece     = board.Pieces[pieceOnStart];
                int   promoteTo = command.promoteTo;
                if (promoteTo >= 0 && promoteTo < db.PiecePrototypes.Count && promoteTo != piece.PrototypeID)
                {
                    BalugaDebug.Log(string.Format("Piece {0} promoted to prototype {1}", pieceOnStart, promoteTo));
                    piece.PrototypeID = promoteTo;
                    piecePromotionDone.Send(pieceOnStart);
                }
                else
                {
                    throw new TurnActionExcecutionException(
                              string.Format("Cannot promote piece at ({0}, {1})! It is already the promotion type.",
                                            command.piecePos.x + 1, command.piecePos.y + 1));
                }
            }
            else
            {
                throw new TurnActionExcecutionException(
                          string.Format("No piece to promote at position ({0}, {1})", command.piecePos.x + 1, command.piecePos.y + 1));
            }
        }
Ejemplo n.º 3
0
        private void DoMovePiece(MoveCommand command)
        {
            int pieceOnTarget = board.PieceOnSpace(command.moveTo);

            if (pieceOnTarget < 0)
            {
                int pieceOnStart = board.PieceOnSpace(command.startPosition);
                if (pieceOnStart >= 0)
                {
                    Piece movedPiece = board.Pieces[pieceOnStart];
                    movedPiece.BoardPosition = command.moveTo;
                    movedPiece.NumberOfMoves++;
                    BalugaDebug.Log(string.Format("Moved piece {0} to {1}", pieceOnStart, command.moveTo));
                    pieceChangePos.Send(pieceOnStart);
                }
                else
                {
                    throw new TurnActionExcecutionException(
                              string.Format("No piece to move at position ({0}, {1})", command.moveTo.x + 1, command.moveTo.y + 1));
                }
            }
            else
            {
                throw new TurnActionExcecutionException(
                          string.Format("Cannot move! Piece exists on ({0}, {1}) already. Capture first?", command.moveTo.x + 1, command.moveTo.y + 1));
            }
        }
Ejemplo n.º 4
0
        private void EnterScreen()
        {
            BalugaDebug.Log("Set defaults");
            hasPort                    = true;
            port                       = 1000;
            password                   = "";
            setPortField.Value         = port.ToString();
            setPasswordField.Value     = "";
            statusText.Value           = "";
            setInputInteractable.Value = true;

            if (screen.State == (int)LobbyScreen.SetupHost)
            {
                setAddressInteractable.Value = false;
                setAddressField.Value        = "localhost";
                titleText.Value       = "Host Game";
                startButtonText.Value = "Start host";
            }
            else if (screen.State == (int)LobbyScreen.SetupClient)
            {
                setAddressInteractable.Value = true;
                address = "localhost";
                setAddressField.Value = address;
                titleText.Value       = "Join Game";
                startButtonText.Value = "Join";
            }

            RefreshStartButtonInteractable();
        }
Ejemplo n.º 5
0
        public static Quaternion FromToRotation(Vector3 from, Vector3 to, Vector3 fallbackAxis)
        {
            BalugaDebug.Assert(from.IsUnit());
            BalugaDebug.Assert(to.IsUnit());
            // from https://bitbucket.org/sinbad/ogre/src/9db75e3ba05c/OgreMain/include/OgreVector3.h?fileviewer=file-view-default#cl-651
            // Based on Stan Melax's article in Game Programming Gems

            float d = Vector3.Dot(from, to);

            // If dot == 1, vectors are the same
            if (d >= 1.0f)
            {
                return(Quaternion.Identity);
            }
            else if (d < 1e-6f - 1.0f)
            {
                if (fallbackAxis.ApproximatelyEquals(Vector3.Zero))
                {
                    // Generate an axis
                    fallbackAxis = Vector3.Cross(Vector3.Right, from);
                    if (fallbackAxis.ApproximatelyEquals(Vector3.Zero))  // pick another if colinear
                    {
                        fallbackAxis = Vector3.Cross(Vector3.Up, from);
                    }
                }
                return(Quaternion.RotationOnAxis(fallbackAxis, (float)Math.PI));
            }
            else
            {
                float   s = (float)Math.Sqrt((1 + d) * 2);
                Vector3 c = Vector3.Cross(from, to);
                return(new Quaternion(s * 0.5f, c / s).Normalize());
            }
        }
Ejemplo n.º 6
0
 private void OnPortChange(string input)
 {
     hasPort            = !string.IsNullOrEmpty(input) && int.TryParse(input, out port);
     setPortField.Value = port.ToString();
     RefreshStartButtonInteractable();
     BalugaDebug.Log("Port " + port);
 }
Ejemplo n.º 7
0
        public static Quaternion Slerp(Quaternion from, Quaternion to, float t)
        {
            BalugaDebug.Assert(from.IsUnit());
            BalugaDebug.Assert(to.IsUnit());
            float dot = Quaternion.Dot(from, to);

            /*	dot = cos(theta)
             *          if (dot < 0), q1 and q2 are more than 90 degrees apart,
             *          so we can invert one to reduce spinning	*/
            if (dot < 0)
            {
                dot = -dot;
                to  = -to;
            }

            if (dot < 0.95f)
            {
                float angle = (float)Math.Acos(dot);
                return(SlerpNoChecks(from, to, t, angle));
            }
            else     // if the angle is small, use linear interpolation
            {
                return(Quaternion.Lerp(from, to, t));
            }
        }
Ejemplo n.º 8
0
        private bool Calculate(CheckCalcArgs args)
        {
            Piece king = board.Pieces[args.kingIndex];

            for (int p = 0; p < board.Pieces.Count; p++)
            {
                Piece enemy = board.Pieces[p];
                if (enemy.OwnerPlayer != king.OwnerPlayer)
                {
                    TurnOptions moveOptions = moveOptionQuery.Send(new TurnOptionCalculatorArgs()
                    {
                        pieceIndex = p,
                        luaState   = LuaTranslator.GetMoveCalcState(p, board, db),
                    });
                    foreach (var option in moveOptions.options)
                    {
                        if (option.components[0].target == args.testPosition)
                        {
                            BalugaDebug.Log(string.Format("King {0} in check from {1} at {2}", args.kingIndex, p, enemy.BoardPosition));
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
 public T Register <T>(int key, T comp) where T : class
 {
     BalugaDebug.Assert(!Contains(key));
     components[key] = comp;
     registerChange.Send(key, comp);
     return(comp);
 }
        private void OnToggleChange(int toggleIndex, bool isOn)
        {
            bool change = false;

            if (selectedToggle == toggleIndex)
            {
                if (!isOn)
                {
                    selectedToggle = -1;
                    change         = true;
                }
            }
            else
            {
                if (isOn)
                {
                    selectedToggle = toggleIndex;
                    change         = true;
                }
            }
            BalugaDebug.Log(string.Format("Toggle change {0} is {1}, selected {2}", toggleIndex, isOn, selectedToggle));
            toggleValues[toggleIndex].Value = isOn;
            if (change)
            {
                tickHelper.Active = true;
                selected.Value    = (int)GetChoiceFromButtons();
            }
        }
Ejemplo n.º 11
0
        private void ExitAndDisconnect()
        {
            BalugaDebug.Log("Exit loading from network error");
            connHelper.StopConnection();

            Game.Controller = new Lobby.LobbyScene((ModdableChessGame)Game);
        }
Ejemplo n.º 12
0
        private void OnStartPress()
        {
            if (hasPort)
            {
                if (screen.State == (int)LobbyScreen.SetupHost)
                {
                    BalugaDebug.Log("Start host command");
                    bool success = netHelper.StartHost(port, password, false);

                    if (success)
                    {
                        statusText.Value           = "Waiting for connection...";
                        state                      = State.Connecting;
                        setInputInteractable.Value = false;
                    }
                    else
                    {
                        statusText.Value = "Error creating host. Port already in use?";
                    }
                }
                else if (screen.State == (int)LobbyScreen.SetupClient)
                {
                    state = State.Connecting;
                    netHelper.StartClient(address, port, password, false);
                    statusText.Value             = "Waiting for connection...";
                    setInputInteractable.Value   = false;
                    setAddressInteractable.Value = false;
                }
            }
            RefreshStartButtonInteractable();
        }
        private void OnPortChange(string input)
        {
            hasPort = !string.IsNullOrEmpty(input) && int.TryParse(input, out port);
            startBtnEnabled.Value = hasPort;
            setPortField.Value    = port.ToString();

            BalugaDebug.Log("Port " + port);
        }
Ejemplo n.º 14
0
 public void Tick(float deltaTime)
 {
     BalugaDebug.Assert(!disposed, "Disposed LockSafeMessenger still in tick list");
     if (callAgain)
     {
         Send();
     }
 }
Ejemplo n.º 15
0
 private void OnCancelPress()
 {
     BalugaDebug.Log(state);
     if (state == State.Connecting)
     {
         BalugaDebug.Log("Stop host command");
         netHelper.StopConnection();
     }
     screen.State = (int)LobbyScreen.PickHostOrClient;
 }
 private void OnStartPress()
 {
     BalugaDebug.Log("Start pressed");
     if (hasPort)
     {
         state = State.Connecting;
         startClientCommand.Send(address, port);
         statusText.Value           = "Waiting for connection...";
         setInputInteractable.Value = false;
         startBtnEnabled.Value      = false;
     }
 }
Ejemplo n.º 17
0
        private void OnEnterChoosingState()
        {
            State s = (State)states.State;

            BalugaDebug.Log(string.Format("Chooser state enter {0}", s));
            tickHelper.ForceInactive = s != State.PieceChosenWait;
            if (s == State.Inactive)
            {
                chosenPiece.Value = -1;
                //chosenAction.Value = null;
            }
        }
Ejemplo n.º 18
0
 public void Send()
 {
     BalugaDebug.Assert(!subs.IsIterationLocked, "Callback iteration locked");
     if (!subs.IsIterationLocked)
     {
         foreach (var ob in subs)
         {
             if (disposed)
             {
                 break;
             }
             ob.Notify();
         }
     }
 }
Ejemplo n.º 19
0
        public Vector3 Rotate(Vector3 v)
        {
            BalugaDebug.Assert(IsUnit());
            //https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles#Vector_Rotation
            Vector3 qv = Vector;
            Vector3 t  = 2 * Vector3.Cross(qv, v);

            /*UnityEngine.Debug.Log(qv);
             * UnityEngine.Debug.Log(t);
             * UnityEngine.Debug.Log(v);
             * UnityEngine.Debug.Log(q.real * t);
             * UnityEngine.Debug.Log(Vector3.Cross(qv, t));*/
            return(v + real * t + Vector3.Cross(qv, t));

            /*Quaternion p = new Quaternion(0, v);
             * return (q * (p * q.Conjugate())).Vector;*/
        }
Ejemplo n.º 20
0
 private void OnReconnectionReplyReceived(NetworkGameState gameState)
 {
     if (state.State == (int)ReconnectionState.WaitingForServerReply)
     {
         state.State = (int)ReconnectionState.SignaledReady;
         if (gameState == null)
         {
             BalugaDebug.Log("Server replied no game state");
             ExitToLobby();
         }
         else
         {
             Board board = createBoard.Send(gameState);
             scene.Game.Components.Remove((int)ComponentKeys.GameBoard);
             scene.Game.Components.Register((int)ComponentKeys.GameBoard, board);
             newBoardMessage.Send(board);
             sendReady.Send(true);
         }
     }
 }
Ejemplo n.º 21
0
        public static Quaternion RotateTowards(Quaternion current, Quaternion target, float maxAngle)
        {
            BalugaDebug.Assert(current.IsUnit());
            BalugaDebug.Assert(target.IsUnit());

            if (maxAngle < 0.001f)
            {
                return(current);
            }

            float cosTheta = Quaternion.Dot(current, target);

            // q1 and q2 are already equal.
            // Force q2 just to be sure
            if (cosTheta > 0.9999f)
            {
                return(target);
            }

            // Avoid taking the long path around the sphere
            if (cosTheta < 0)
            {
                current   = current * -1.0f;
                cosTheta *= -1.0f;
            }

            float angle = (float)Math.Acos(cosTheta);

            // If there is only a 2&deg; difference, and we are allowed 5&deg;,
            // then we arrived.
            if (angle <= maxAngle)
            {
                return(target);
            }

            float fT = maxAngle / angle;

            return(SlerpNoChecks(current, target, fT, maxAngle));
        }
 private void SetPickedMod(ComboModInfo mod)
 {
     pickedMod = mod;
     if (screen.State == (int)LobbyScreen.HostGamePrefs)
     {
         if (pickedMod != null)
         {
             pickedModTop.Value = pickedMod.displayName;
         }
         else
         {
             pickedModTop.Value = "Pick a mod!";
         }
     }
     else
     {
         if (pickedMod != null)
         {
             pickedModBottom.Value = pickedMod.displayName;
         }
         else
         {
             pickedModBottom.Value = "Pick a mod!";
         }
     }
     SendPickedModOverNetwork();
     if (mod == null || mod.networkStatus != ModNetworkStatus.Playable)
     {
         selectedModName.Value = null;
     }
     else
     {
         selectedModName.Value = mod.filePath;
     }
     BalugaDebug.Log("Mod picked: " + (mod == null ? "none" : mod.modName + " " + mod.networkStatus));
 }
Ejemplo n.º 23
0
        private void OnReceivedEndOfTurnState(ServerEndOfTurnState serverState)
        {
            board.TurnState = TurnState.Choosing;
            turnStateChange.Send();

            BalugaDebug.Log("Server end of turn reply: " + serverState);
            if (serverState == ServerEndOfTurnState.Undecided)
            {
                startTurnCommand.Send(true);
            }
            else
            {
                GameEndType endType;
                switch (serverState)
                {
                case ServerEndOfTurnState.HostWin:
                    endType = localInfo.IsHost ? GameEndType.Win : GameEndType.Loss;
                    break;

                case ServerEndOfTurnState.ClientWin:
                    endType = localInfo.IsHost ? GameEndType.Loss : GameEndType.Win;
                    break;

                case ServerEndOfTurnState.Tie:
                    endType = GameEndType.Tie;
                    break;

                default:
                    endType = GameEndType.Error;
                    break;
                }
                BalugaDebug.Log("End of game type: " + endType);
                gameOverMessage.Send(endType);
                matchState.State = (int)MatchState.End;
            }
        }
Ejemplo n.º 24
0
 public void OnError(int connectionID, UnityEngine.Networking.NetworkError errorCode)
 {
     BalugaDebug.Log("Server connection error " + errorCode);
 }
Ejemplo n.º 25
0
 public void Subscribe(IListener listener)
 {
     BalugaDebug.Assert(!disposed);
     subs.Add(listener);
 }
 private void OnAddressChange(string input)
 {
     address = input;
     setAddressField.Value = address;
     BalugaDebug.Log("Address " + address);
 }
Ejemplo n.º 27
0
 public void Notify()
 {
     BalugaDebug.Assert(!disposed);
     callback();
 }
Ejemplo n.º 28
0
        public void OnValidationRequest(int connectionID, ValidationInfo val)
        {
            ValidationResponse response = null;

            // if connectionID is zero, just accept, it's the host local client
            if (connectionID == 0)
            {
                response = new ValidationResponse()
                {
                    isHost   = true,
                    accepted = true,
                };
            }
            else
            {
                if (info.ClientConnectionID >= 0)
                {
                    BalugaDebug.Log(string.Format("Third player tried to connect! {0} \"{1}\"", connectionID, val.password));
                    response = new ValidationResponse()
                    {
                        accepted = false,
                    };
                }
                else
                {
                    BalugaDebug.Log(string.Format("New try connect, mine: \"{0}\" {3}, theirs \"{1}\" {2}",
                                                  info.Password, val.password, val.inProgressGame, info.WantsInProgressGame));
                    bool validPassword  = connectionID == 0 || string.IsNullOrEmpty(info.Password) || info.Password == val.password;
                    bool validGameState = connectionID == 0 || info.WantsInProgressGame == val.inProgressGame;

                    if (validPassword && validGameState)
                    {
                        info.ClientConnectionID = connectionID;
                        BalugaDebug.Log(string.Format("Newly connected client {0} \"{1}\" {2}", connectionID, val.password, val.inProgressGame));
                        info.Connection.State = (int)ServerConnectionState.Connected;
                        response = new ValidationResponse()
                        {
                            isHost   = false,
                            accepted = true,
                        };
                    }
                    else
                    {
                        BalugaDebug.Log(string.Format("Player tried to connect with bad password/state! {0} \"{1}\" {2}",
                                                      connectionID, val.password, val.inProgressGame));
                        response = new ValidationResponse()
                        {
                            accepted = false,
                        };
                    }
                }
            }

            if (response != null)
            {
                commandable.SendValidationResponse(connectionID, response);
                if (!response.accepted)
                {
                    disconnectNextFrame.Enqueue(connectionID);
                }
            }
        }
Ejemplo n.º 29
0
        private void SendEndOfTurnState()
        {
            EoTScriptState overType;

            switch (lastActionResult)
            {
            case TurnActionExecutionResult.Success:
                overType = checkGameOver.Send();
                break;

            case TurnActionExecutionResult.Forfeit:
                overType = EoTScriptState.Forfeit;
                break;

            default:
                overType = EoTScriptState.Error;
                break;
            }

            BalugaDebug.Log("Game over type: " + overType);

            // Send win/loss/not-decided/error to server, and wait for reply
            EndOfTurnState eotState = EndOfTurnState.Error;

            switch (overType)
            {
            case EoTScriptState.FirstPlayerWins:
                if (board.LocalPlayerOrder == PlayerTurnOrder.First)
                {
                    eotState = EndOfTurnState.Win;
                }
                else
                {
                    eotState = EndOfTurnState.Loss;
                }
                break;

            case EoTScriptState.SecondPlayerWins:
                if (board.LocalPlayerOrder == PlayerTurnOrder.First)
                {
                    eotState = EndOfTurnState.Loss;
                }
                else
                {
                    eotState = EndOfTurnState.Win;
                }
                break;

            case EoTScriptState.Tie:
                eotState = EndOfTurnState.Tie;
                break;

            case EoTScriptState.Undecided:
                eotState = EndOfTurnState.Undecided;
                break;

            case EoTScriptState.Forfeit:
                eotState = EndOfTurnState.Forfeit;
                break;

            default:
                eotState = EndOfTurnState.Error;
                break;
            }

            BalugaDebug.Log("End of turn state: " + eotState);
            sendEoTState.Send(eotState);
        }
Ejemplo n.º 30
0
 public void RegisterCommandable(IServerCommandable commandable)
 {
     BalugaDebug.Assert(this.commandable == null);
     this.commandable = commandable;
 }