private IEnumerable<XY> GetPointCollection(Loc[] locations)
 {
     foreach (Loc location in locations)
     {
         yield return new XY(location.lon, location.lat);
     }
 }
Exemplo n.º 2
0
 public Move(Unit actor, Loc start, Loc end, int mvConsumed)
 {
     this.actor = actor;
     this.start = start;
     this.end = end;
     this.mvConsumed = mvConsumed;
 }
Exemplo n.º 3
0
 /// <summary>
 /// Adjust wait time until next movement allowed and check if can move currently.
 /// </summary>
 /// <returns><c>true</c>, if can move, <c>false</c> otherwise.</returns>
 /// <param name="dLoc">Attempted change in location.</param>
 private bool updateWaitTime(Loc dLoc)
 {
     if (dLoc.Equals (Loc.zero)) {
         cooldown = 0;
         return false;
     }
     if (cooldown > 0) {
         cooldown -= Time.deltaTime;
         return false;
     }
     cooldown = waitTime;
     return true;
 }
Exemplo n.º 4
0
    private void updatePosition()
    {
        if (!canMove) { return; }

        Loc dLoc = determineOffset ();
        // Update wait time and see if cursor can move this tic
        if (!updateWaitTime (dLoc)) { return; }

        Loc potLoc = loc.plus (dLoc);
        if (World.current.isInBounds (potLoc)) {
            loc = potLoc;
            transform.position = World.current.onGround (potLoc);
        }
    }
Exemplo n.º 5
0
        /* The next best thing to a picture in the source code.

                       IsLegal()
                          ||
                          ||
                        IsKill
                      n/      \y
                 IsSuicide    IsKo
                 n/    \y    n/  \y
                PLAY    NO  PLAY  NO

         */
        public IsLegalResponse IsLegal(Loc proposedLoc)
        {
            IsLegalResponse response = new IsLegalResponse();

            if (isConflict(proposedLoc))
            {
                response.Reason = ReasonEnum.Conflict;
                return response;
            }

            response.Killed = determineKills(proposedLoc);

            if (response.Killed.Any())
            {   // IsKill
                if (isKo(proposedLoc, response.Killed))
                {
                    response.Reason = ReasonEnum.Ko;
                    return response;
                }
                else
                {   // Determine MergeResultant and AbsorbedByMerge for future use.
                    // Does proposedLoc have any friendly neighbors?
                    List<Chain> friendlyNeighborChains = findFriendlyNeighborChains(proposedLoc);

                    if (friendlyNeighborChains.Any())
                    {
                        // If so, merge
                        friendlyNeighborChains.Add(new Chain(new Stone(proposedLoc, IsWhiteMove),
                                                             this.findLiberties(proposedLoc)));
                        response.MergeResultant = this.merge(friendlyNeighborChains);
                        response.AbsorbedInMerge = friendlyNeighborChains;
                    }
                    else
                    {
                        response.MergeResultant = new Chain(new Stone(proposedLoc, IsWhiteMove), this.findLiberties(proposedLoc));
                        response.AbsorbedInMerge = new List<Chain>();
                    }

                    return response;
                }
            }
            else
            {   // !IsKill
                this.determineSuicide(proposedLoc, response);

                return response;
            }
        }
Exemplo n.º 6
0
    /// <summary>
    /// Determine change in loc caused by keypresses this tic.
    /// </summary>
    /// <returns>Potential offset of cursor.</returns>
    private Loc determineOffset()
    {
        Loc offset = new Loc ();

        // Add to offset based on keyboard input
        // Must take perspective (rotation) of camera into consideration
        if (Input.GetButton ("Up"))
            offset = offset.plus (new Loc (0, 1, Cam.main.perspective));
        if (Input.GetButton ("Down"))
            offset = offset.plus (new Loc (0, -1, Cam.main.perspective));
        if (Input.GetButton ("Left"))
            offset = offset.plus (new Loc (-1, 0, Cam.main.perspective));
        if (Input.GetButton ("Right"))
            offset = offset.plus (new Loc (1, 0, Cam.main.perspective));

        return offset;
    }
Exemplo n.º 7
0
    /// <summary>
    /// Check if given move is valid/possible.
    /// </summary>
    static bool isValid(Move move, Loc lastLoc)
    {
        // Check if space is in bounds
        if ( !World.current.isInBounds(move.end) )
            return false;

        // Check that space not hole
        if ( World.current.isHole(move.end) )
            return false;

        // Check that is not occupied already
        if ( Unit.get (move.end) != null )
            return false;

        // Check that height is not too great
        float dHeight = Mathf.Abs (World.current.getHeight (move.end)
                                    - World.current.getHeight (lastLoc));
        if ( dHeight > move.actor.jump )
            return false;

        // If none of above tests failed, is valid space to move to
        return true;
    }
Exemplo n.º 8
0
        /// <summary>
        ///     Attempt to force someone else to drink some of a drink. Returns true if any interaction took place,
        ///     including generation of pop-up messages.
        /// </summary>
        private bool TryForceDrink(EntityUid uid, EntityUid userUid, EntityUid targetUid,
                                   DrinkComponent?drink = null)
        {
            if (!Resolve(uid, ref drink))
            {
                return(false);
            }

            // cannot stack do-afters
            if (drink.CancelToken != null)
            {
                drink.CancelToken.Cancel();
                drink.CancelToken = null;
                return(true);
            }

            if (!EntityManager.HasComponent <SharedBodyComponent>(targetUid))
            {
                return(false);
            }

            if (!drink.Opened)
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-not-open",
                                                       ("owner", Name: EntityManager.GetComponent <MetaDataComponent>(drink.Owner).EntityName)), uid, Filter.Entities(userUid));
                return(true);
            }

            if (!_solutionContainerSystem.TryGetDrainableSolution(uid, out var drinkSolution) ||
                drinkSolution.DrainAvailable <= 0)
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-is-empty",
                                                       ("entity", Name: EntityManager.GetComponent <MetaDataComponent>(drink.Owner).EntityName)), uid, Filter.Entities(userUid));
                return(true);
            }

            if (_foodSystem.IsMouthBlocked(targetUid, userUid))
            {
                return(true);
            }

            EntityManager.TryGetComponent(userUid, out MetaDataComponent? meta);
            var userName = meta?.EntityName ?? string.Empty;

            _popupSystem.PopupEntity(Loc.GetString("drink-component-force-feed", ("user", userName)),
                                     userUid, Filter.Entities(targetUid));

            drink.CancelToken = new();
            _doAfterSystem.DoAfter(new DoAfterEventArgs(userUid, drink.ForceFeedDelay, drink.CancelToken.Token, targetUid)
            {
                BreakOnUserMove         = true,
                BreakOnDamage           = true,
                BreakOnStun             = true,
                BreakOnTargetMove       = true,
                MovementThreshold       = 1.0f,
                TargetFinishedEvent     = new ForceDrinkEvent(userUid, drink, drinkSolution),
                BroadcastCancelledEvent = new ForceDrinkCancelledEvent(drink),
            });

            // logging
            _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{ToPrettyString(userUid):user} is forcing {ToPrettyString(targetUid):target} to drink {ToPrettyString(uid):drink} {SolutionContainerSystem.ToPrettyString(drinkSolution):solution}");

            return(true);
        }
Exemplo n.º 9
0
 public void Examine(FormattedMessage message, bool inDetailsRange)
 {
     message.AddMarkup(Loc.GetString("It's currently on {0} mode, and holds {1} charges.", _mode.ToString(), _ammo));
 }
Exemplo n.º 10
0
    /// <summary>
    /// Move unit to given space.
    /// Precondition: Space must be valid.
    /// Space should be on the ground for current map, so y must be raised from xz plane.
    /// </summary>
    public void move(Loc loc, int mvConsumed = 0)
    {
        // Change the stored and real location of unit
        this.loc = loc;
        self.transform.position = World.current.onGround (loc);

        // Consume movement
        mvCur -= mvConsumed;
    }
Exemplo n.º 11
0
        private async void PlaceActiveHandItemInHands(IEntity user, string hand)
        {
            var hands     = Owner.GetComponent <HandsComponent>();
            var userHands = user.GetComponent <HandsComponent>();
            var item      = userHands.GetActiveHand;

            bool Check()
            {
                if (!ActionBlockerSystem.CanInteract(user))
                {
                    return(false);
                }

                if (item == null)
                {
                    user.PopupMessageCursor(Loc.GetString("You aren't holding anything!"));
                    return(false);
                }

                if (!userHands.CanDrop(userHands.ActiveHand !))
                {
                    user.PopupMessageCursor(Loc.GetString("You can't drop that!"));
                    return(false);
                }

                if (!hands.HasHand(hand))
                {
                    return(false);
                }

                if (hands.TryGetItem(hand, out var _))
                {
                    user.PopupMessageCursor(Loc.GetString("{0:They} already {0:have} something there!", Owner));
                    return(false);
                }

                if (!hands.CanPutInHand(item, hand, false))
                {
                    user.PopupMessageCursor(Loc.GetString("{0:They} cannot put that there!", Owner));
                    return(false);
                }

                return(true);
            }

            var doAfterSystem = EntitySystem.Get <DoAfterSystem>();

            var doAfterArgs = new DoAfterEventArgs(user, StripDelay, CancellationToken.None, Owner)
            {
                ExtraCheck        = Check,
                BreakOnStun       = true,
                BreakOnDamage     = true,
                BreakOnTargetMove = true,
                BreakOnUserMove   = true,
                NeedHand          = true,
            };

            var result = await doAfterSystem.DoAfter(doAfterArgs);

            if (result != DoAfterStatus.Finished)
            {
                return;
            }

            userHands.Drop(hand, false);
            hands.PutInHand(item !, hand, false, false);
            UpdateSubscribed();
        }
Exemplo n.º 12
0
 private void UpdateRemainingFlammability(Structure structure, float delta)
 {
     structure.Flammability -= delta / 2;
     if (structure.Flammability <= 0)
     {
         Loc.GetStructureController().SpawnStructure("Debris", structure.Cell, Loc.GetFactionController().WorldFaction);
         Loc.GetStructureController().DestroyStructure(structure);
     }
 }
Exemplo n.º 13
0
        private void determineSuicide(Loc proposedLoc, IsLegalResponse response)
        {
            // Does proposedLoc have any friendly neighbors?
            List<Chain> friendlyNeighborChains = findFriendlyNeighborChains(proposedLoc);

            if (friendlyNeighborChains.Any())
            {
                // If so, merge
                friendlyNeighborChains.Add(new Chain(new Stone(proposedLoc, IsWhiteMove), this.findLiberties(proposedLoc)));
                Chain mergeResultant = this.merge(friendlyNeighborChains);

                if (!mergeResultant.Liberties.Any())
                {
                    response.Reason = ReasonEnum.Suicide;
                    return;
                }
                else
                {
                    response.MergeResultant = mergeResultant;
                    response.AbsorbedInMerge = friendlyNeighborChains;
                    return;
                }
            }
            else
            {
                // If not, if there are any liberties, it's playable
                if (this.findLiberties(proposedLoc).Any())
                {
                    response.MergeResultant = new Chain(new Stone(proposedLoc, IsWhiteMove),
                        this.findLiberties(proposedLoc));
                    response.AbsorbedInMerge = new List<Chain>();
                    return;
                }
            }

            // else, it's suicide
            response.Reason = ReasonEnum.Suicide;
        }
Exemplo n.º 14
0
        // TODO: Can also do a quick scan of neighbors if there are any foes, so see if even need to look for kills.
        private List<Chain> determineKills(Loc proposedLoc)
        {
            List<Chain> kills = new List<Chain>();

            // Iterate through chains of opposite color.
            // if any have 1 liberty, it's a kill and is returned in List<Chain>
            if (IsWhiteMove)
                foreach (Chain chain in Game.blackChains)
                {
                    if (chain.Liberties.Count == 1 && chain.Liberties[0].Equals(proposedLoc))
                        kills.Add(chain);
                }
            else
                foreach (Chain chain in Game.whiteChains)
                {
                    if (chain.Liberties.Count == 1 && chain.Liberties[0].Equals(proposedLoc))
                        kills.Add(chain);
                }

            return kills;
        }
Exemplo n.º 15
0
        private static bool isConflictHelper(List<Chain> chainsOfLikeColor, Loc proposedLoc)
        {
            foreach (Chain chain in chainsOfLikeColor)
                foreach (Stone stone in chain.Stones)
                    if (proposedLoc.Equals(stone.Loc))
                        return true;

            return false;
        }
Exemplo n.º 16
0
        // Updates lists accordingly with correct location and color.
        public RequestResponse PlaceStone(Loc loc, IsLegalResponse isLegalResponse)
        {
            // By this point, we have MergeResult and KilledChains
            this.Game.PossibleKoLoc = new Loc(-1, -1);

            // Update logical groups of Chains by adding the mergeResult and removing what went into the merge
            this.enactMerge(isLegalResponse.MergeResultant, isLegalResponse.AbsorbedInMerge);
            // Update logical groups of Chains by removing the killed ones.
            this.deadifyKilledChains(isLegalResponse.Killed);

            if (IsWhiteMove)
            {
                this.Game.PrisonersTakenByWhite += isLegalResponse.Killed.Sum(chain => chain.Stones.Count);

                foreach (Chain chain in this.Game.whiteChains)
                    this.reCalcLiberties(chain);
            }
            else
            {
                this.Game.PrisonersTakenByBlack += isLegalResponse.Killed.Sum(chain => chain.Stones.Count);

                foreach (Chain chain in this.Game.blackChains)
                    this.reCalcLiberties(chain);
            }

            // Update logical groups of Opponent's Chains by removing breath for current Loc
            this.takeMyBreathAwaaaaay(loc);

            // Set possibleKoLoc.
            if (isLegalResponse.Killed.Count == 1
                && isLegalResponse.Killed[0].Stones.Count == 1)
            {
                this.Game.PossibleKoLoc = isLegalResponse.Killed[0].Stones[0].Loc;
            }

            RequestResponse response = new RequestResponse(new Move(new Stone(loc, IsWhiteMove), isLegalResponse.Killed));

            this.ChangeTurn();

            return response;
        }
Exemplo n.º 17
0
 public Stone(Loc loc, bool isWhite)
 {
     Loc = loc;
     IsWhite = isWhite;
 }
Exemplo n.º 18
0
 public static Vector3 Loc2Pos(Loc loc)
 {
     return new Vector3 ((float)((loc.x - 3) * 2), (float)((loc.y - 2) * 2));
 }
Exemplo n.º 19
0
        public RequestResponse ProposedPlay(Loc loc)
        {
            // if it's ==, then it's a PASS
            if (loc.X == this.boardSize)
            {
                if (this.LastWasPass)
                {
                    this.IsOver = true;
                    // TODO: game-ending logic goes here.
                }

                this.LastWasPass = true;
                this.Logic.ChangeTurn();
                return new RequestResponse(ReasonEnum.Pass);
            }
            else
                this.LastWasPass = false;

            IsLegalResponse isLegalResponse = this.Logic.IsLegal(loc);

            if (isLegalResponse.Reason == ReasonEnum.Fine)
            {
                RequestResponse response = this.Logic.PlaceStone(loc, isLegalResponse);
                this.Log.Add(new MoveForLog { Move = response.Move });//, Id = this.Log.LastOrDefault().Id + 1 });
                return response;
            }
            else
                return new RequestResponse(isLegalResponse.Reason);
        }
 protected override void CreamedEntity(EntityUid uid, CreamPiedComponent creamPied, ThrowHitByEvent args)
 {
     creamPied.Owner.PopupMessage(Loc.GetString("cream-pied-component-on-hit-by-message", ("thrower", args.Thrown)));
     creamPied.Owner.PopupMessageOtherClients(Loc.GetString("cream-pied-component-on-hit-by-message-others", ("owner", creamPied.Owner), ("thrower", args.Thrown)));
 }
Exemplo n.º 21
0
        public ParticleAcceleratorControlMenu(ParticleAcceleratorBoundUserInterface owner)
        {
            SetSize          = (400, 300);
            _greyScaleShader = IoCManager.Resolve <IPrototypeManager>().Index <ShaderPrototype>("Greyscale").Instance();

            Owner = owner;
            _drawNoiseGenerator = new NoiseGenerator(NoiseGenerator.NoiseType.Fbm);
            _drawNoiseGenerator.SetFrequency(0.5f);

            var resourceCache = IoCManager.Resolve <IResourceCache>();
            var font          = resourceCache.GetFont("/Fonts/Boxfont-round/Boxfont Round.ttf", 13);
            var panelTex      = resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");

            MouseFilter = MouseFilterMode.Stop;

            _alarmControlAnimation = new Animation
            {
                Length          = TimeSpan.FromSeconds(1),
                AnimationTracks =
                {
                    new AnimationTrackControlProperty
                    {
                        Property  = nameof(Control.Visible),
                        KeyFrames =
                        {
                            new AnimationTrackProperty.KeyFrame(true,      0),
                            new AnimationTrackProperty.KeyFrame(false, 0.75f),
                        }
                    }
                }
            };

            var back = new StyleBoxTexture
            {
                Texture  = panelTex,
                Modulate = Color.FromHex("#25252A"),
            };

            back.SetPatchMargin(StyleBox.Margin.All, 10);

            var back2 = new StyleBoxTexture(back)
            {
                Modulate = Color.FromHex("#202023")
            };

            AddChild(new PanelContainer
            {
                PanelOverride = back,
                MouseFilter   = MouseFilterMode.Pass
            });

            _stateSpinBox = new SpinBox
            {
                Value = 0,
            };
            _stateSpinBox.IsValid = StrengthSpinBoxValid;
            _stateSpinBox.InitDefaultButtons();
            _stateSpinBox.ValueChanged    += PowerStateChanged;
            _stateSpinBox.LineEditDisabled = true;

            _offButton = new Button
            {
                ToggleMode   = false,
                Text         = "Off",
                StyleClasses = { StyleBase.ButtonOpenRight },
            };
            _offButton.OnPressed += args => owner.SendEnableMessage(false);

            _onButton = new Button
            {
                ToggleMode   = false,
                Text         = "On",
                StyleClasses = { StyleBase.ButtonOpenLeft },
            };
            _onButton.OnPressed += args => owner.SendEnableMessage(true);

            var closeButton = new TextureButton
            {
                StyleClasses        = { "windowCloseButton" },
                HorizontalAlignment = HAlignment.Right,
                Margin = new Thickness(0, 0, 8, 0)
            };

            closeButton.OnPressed += args => Close();

            var serviceManual = new Label
            {
                HorizontalAlignment = HAlignment.Center,
                StyleClasses        = { StyleBase.StyleClassLabelSubText },
                Text = Loc.GetString("Refer to p.132 of service manual")
            };

            _drawLabel = new Label();
            var imgSize = new Vector2(32, 32);

            AddChild(new VBoxContainer
            {
                Children =
                {
                    new Control
                    {
                        Margin   = new Thickness(2, 2, 0, 0),
                        Children =
                        {
                            new Label
                            {
                                Text              = Loc.GetString("Mark 2 Particle Accelerator"),
                                FontOverride      = font,
                                FontColorOverride = StyleNano.NanoGold,
                            },
                            closeButton
                        }
                    },
                    new PanelContainer
                    {
                        PanelOverride = new StyleBoxFlat        {
                            BackgroundColor = StyleNano.NanoGold
                        },
                        MinSize = (0, 2),
                    },
Exemplo n.º 22
0
        private List<Chain> findFriendlyNeighborChains(Loc loc)
        {
            List<Chain> friendlyChains = new List<Chain>();

            if (IsWhiteMove)
                foreach (Chain chain in Game.whiteChains)
                    foreach (Loc liberty in chain.Liberties)
                    {
                        if (liberty.Equals(loc))
                            friendlyChains.Add(chain);
                    }
            else
                foreach (Chain chain in Game.blackChains)
                    foreach (Loc liberty in chain.Liberties)
                    {
                        if (liberty.Equals(loc))
                            friendlyChains.Add(chain);
                    }

            return friendlyChains;
        }
Exemplo n.º 23
0
 /// <summary>
 /// For given location, return vector which is that locations position atop ground.
 /// Effectively taking location, which is in xz plane, and projecting it such that it is atop ground.
 /// </summary>
 public Vector3 onGround(Loc l)
 {
     return l.asVect () + new Vector3(0, map.getHeight(l), 0);
 }
Exemplo n.º 24
0
        private List<Loc> findLiberties(Loc loc)
        {
            List<Loc> liberties = new List<Loc>();

            // Check Left.
            Loc left = new Loc(loc.X - 1, loc.Y);
            if (loc.X > 0 && !Game.LocsPlayed.Contains(left))
                liberties.Add(left);

            // Check Right.
            Loc right = new Loc(loc.X + 1, loc.Y);
            if (loc.X < Game.BoardSize - 1 && !Game.LocsPlayed.Contains(right))
                liberties.Add(right);

            // Check Up.
            Loc up = new Loc(loc.X, loc.Y - 1);
            if (loc.Y > 0 && !Game.LocsPlayed.Contains(up))
                liberties.Add(up);

            // Check Down.
            Loc down = new Loc(loc.X, loc.Y + 1);
            if (loc.Y < Game.BoardSize - 1 && !Game.LocsPlayed.Contains(down))
                liberties.Add(down);

            return liberties;
        }
Exemplo n.º 25
0
        public ActionsUI(ClientActionsComponent actionsComponent)
        {
            SetValue(LayoutContainer.DebugProperty, true);
            _actionsComponent = actionsComponent;
            _actionManager    = IoCManager.Resolve <ActionManager>();
            _entityManager    = IoCManager.Resolve <IEntityManager>();
            _gameTiming       = IoCManager.Resolve <IGameTiming>();
            _gameHud          = IoCManager.Resolve <IGameHud>();
            _menu             = new ActionMenu(_actionsComponent, this);

            LayoutContainer.SetGrowHorizontal(this, LayoutContainer.GrowDirection.End);
            LayoutContainer.SetGrowVertical(this, LayoutContainer.GrowDirection.Constrain);
            LayoutContainer.SetAnchorTop(this, 0f);
            LayoutContainer.SetAnchorBottom(this, 0.8f);
            LayoutContainer.SetMarginLeft(this, 13);
            LayoutContainer.SetMarginTop(this, 110);

            HorizontalAlignment = HAlignment.Left;
            VerticalExpand      = true;

            var resourceCache = IoCManager.Resolve <IResourceCache>();

            // everything needs to go within an inner panel container so the panel resizes to fit the elements.
            // Because ActionsUI is being anchored by layoutcontainer, the hotbar backing would appear too tall
            // if ActionsUI was the panel container

            var panelContainer = new PanelContainer()
            {
                StyleClasses        = { StyleNano.StyleClassHotbarPanel },
                HorizontalAlignment = HAlignment.Left,
                VerticalAlignment   = VAlignment.Top
            };

            AddChild(panelContainer);

            var hotbarContainer = new BoxContainer
            {
                Orientation         = LayoutOrientation.Vertical,
                SeparationOverride  = 3,
                HorizontalAlignment = HAlignment.Left
            };

            panelContainer.AddChild(hotbarContainer);

            var settingsContainer = new BoxContainer
            {
                Orientation      = LayoutOrientation.Horizontal,
                HorizontalExpand = true
            };

            hotbarContainer.AddChild(settingsContainer);

            settingsContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 1
            });
            _lockTexture   = resourceCache.GetTexture("/Textures/Interface/Nano/lock.svg.192dpi.png");
            _unlockTexture = resourceCache.GetTexture("/Textures/Interface/Nano/lock_open.svg.192dpi.png");
            _lockButton    = new TextureButton
            {
                TextureNormal         = _unlockTexture,
                HorizontalAlignment   = HAlignment.Center,
                VerticalAlignment     = VAlignment.Center,
                SizeFlagsStretchRatio = 1,
                Scale        = (0.5f, 0.5f),
                ToolTip      = Loc.GetString("ui-actionsui-function-lock-action-slots"),
                TooltipDelay = CustomTooltipDelay
            };
            settingsContainer.AddChild(_lockButton);
            settingsContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 2
            });
            _settingsButton = new TextureButton
            {
                TextureNormal         = resourceCache.GetTexture("/Textures/Interface/Nano/gear.svg.192dpi.png"),
                HorizontalAlignment   = HAlignment.Center,
                VerticalAlignment     = VAlignment.Center,
                SizeFlagsStretchRatio = 1,
                Scale        = (0.5f, 0.5f),
                ToolTip      = Loc.GetString("ui-actionsui-function-open-abilities-menu"),
                TooltipDelay = CustomTooltipDelay
            };
            settingsContainer.AddChild(_settingsButton);
            settingsContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 1
            });

            // this allows a 2 column layout if window gets too small
            _slotContainer = new GridContainer
            {
                MaxGridHeight = CalcMaxHeight()
            };
            hotbarContainer.AddChild(_slotContainer);

            _loadoutContainer = new BoxContainer
            {
                Orientation      = LayoutOrientation.Horizontal,
                HorizontalExpand = true,
                MouseFilter      = MouseFilterMode.Stop
            };
            hotbarContainer.AddChild(_loadoutContainer);

            _loadoutContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 1
            });
            var previousHotbarIcon = new TextureRect()
            {
                Texture               = resourceCache.GetTexture("/Textures/Interface/Nano/left_arrow.svg.192dpi.png"),
                HorizontalAlignment   = HAlignment.Center,
                VerticalAlignment     = VAlignment.Center,
                SizeFlagsStretchRatio = 1,
                TextureScale          = (0.5f, 0.5f)
            };

            _loadoutContainer.AddChild(previousHotbarIcon);
            _loadoutContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 2
            });
            _loadoutNumber = new Label
            {
                Text = "1",
                SizeFlagsStretchRatio = 1
            };
            _loadoutContainer.AddChild(_loadoutNumber);
            _loadoutContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 2
            });
            var nextHotbarIcon = new TextureRect
            {
                Texture               = resourceCache.GetTexture("/Textures/Interface/Nano/right_arrow.svg.192dpi.png"),
                HorizontalAlignment   = HAlignment.Center,
                VerticalAlignment     = VAlignment.Center,
                SizeFlagsStretchRatio = 1,
                TextureScale          = (0.5f, 0.5f)
            };

            _loadoutContainer.AddChild(nextHotbarIcon);
            _loadoutContainer.AddChild(new Control {
                HorizontalExpand = true, SizeFlagsStretchRatio = 1
            });

            _slots = new ActionSlot[ClientActionsComponent.Slots];

            _dragShadow = new TextureRect
            {
                MinSize = (64, 64),
                Stretch = TextureRect.StretchMode.Scale,
                Visible = false,
                SetSize = (64, 64)
            };
            UserInterfaceManager.PopupRoot.AddChild(_dragShadow);

            for (byte i = 0; i < ClientActionsComponent.Slots; i++)
            {
                var slot = new ActionSlot(this, _menu, actionsComponent, i);
                _slotContainer.AddChild(slot);
                _slots[i] = slot;
            }

            DragDropHelper = new DragDropHelper <ActionSlot>(OnBeginActionDrag, OnContinueActionDrag, OnEndActionDrag);

            MinSize = (10, 400);
        }
Exemplo n.º 26
0
 private bool isConflict(Loc proposedLoc)
 {
     return GameLogic.isConflictHelper(this.Game.blackChains, proposedLoc)
         || GameLogic.isConflictHelper(this.Game.whiteChains, proposedLoc);
 }
Exemplo n.º 27
0
 /// <summary>
 /// Check if given location on current map is a hole.
 /// </summary>
 /// <returns><c>true</c>, if location is a hole, <c>false</c> otherwise.</returns>
 /// <param name="l">Location to check for hole status.</param>
 public bool isHole(Loc l)
 {
     return map.isHole (l);
 }
Exemplo n.º 28
0
 private bool isKo(Loc proposedLoc, List<Chain> killed)
 {
     return proposedLoc.Equals(Game.PossibleKoLoc)
         && killed.Count == 1
         && killed[0].Stones.Count == 1;
 }
Exemplo n.º 29
0
 /// <summary>
 /// Get the height of a given space on the current map.
 /// </summary>
 /// <returns>The height of given location.</returns>
 public float getHeight(Loc loc)
 {
     return map.getHeight (loc);
 }
Exemplo n.º 30
0
 private void takeMyBreathAwaaaaay(Loc loc)
 {
     if (IsWhiteMove)
         foreach (Chain chain in Game.blackChains)
             chain.Liberties.Remove(loc);
     else
         foreach (Chain chain in Game.whiteChains)
             chain.Liberties.Remove(loc);
 }
Exemplo n.º 31
0
        private bool IsRCDStillValid(AfterInteractEventArgs eventArgs, IMapGrid mapGrid, TileRef tile, MapIndices snapPos, RcdMode startingMode)
        {
            //Less expensive checks first. Failing those ones, we need to check that the tile isn't obstructed.
            if (_ammo <= 0)
            {
                Owner.PopupMessage(eventArgs.User, Loc.GetString("The RCD is out of ammo!"));
                return(false);
            }

            if (_mode != startingMode)
            {
                return(false);
            }

            var coordinates = mapGrid.GridTileToLocal(tile.GridIndices);

            if (coordinates == GridCoordinates.InvalidGrid || !eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true))
            {
                return(false);
            }

            switch (_mode)
            {
            //Floor mode just needs the tile to be a space tile (subFloor)
            case RcdMode.Floors:
                if (!tile.Tile.IsEmpty)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("You can only build a floor on space!"));
                    return(false);
                }

                return(true);

            //We don't want to place a space tile on something that's already a space tile. Let's do the inverse of the last check.
            case RcdMode.Deconstruct:
                if (tile.Tile.IsEmpty)
                {
                    return(false);
                }

                //They tried to decon a turf but the turf is blocked
                if (eventArgs.Target == null && tile.IsBlockedTurf(true))
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("That tile is obstructed!"));
                    return(false);
                }
                //They tried to decon a non-turf but it's not in the whitelist
                if (eventArgs.Target != null && !eventArgs.Target.TryGetComponent(out RCDDeconstructWhitelist rcd_decon))
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("You can't deconstruct that!"));
                    return(false);
                }

                return(true);

            //Walls are a special behaviour, and require us to build a new object with a transform rather than setting a grid tile, thus we early return to avoid the tile set code.
            case RcdMode.Walls:
                if (tile.Tile.IsEmpty)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("You cannot build a wall on space!"));
                    return(false);
                }

                if (tile.IsBlockedTurf(true))
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("That tile is obstructed!"));
                    return(false);
                }
                return(true);

            case RcdMode.Airlock:
                if (tile.Tile.IsEmpty)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Cannot build an airlock on space!"));
                    return(false);
                }
                if (tile.IsBlockedTurf(true))
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("That tile is obstructed!"));
                    return(false);
                }
                return(true);

            default:
                return(false);    //I don't know why this would happen, but sure I guess. Get out of here invalid state!
            }
        }
Exemplo n.º 32
0
 public AnimalViewModel GetAnimalAtLoc(InGameRootViewModel viewModel, Loc loc)
 {
     return viewModel.AnimalCollections.Where (vm => vm.Loc == loc).SingleOrDefault ();
 }
Exemplo n.º 33
0
        /// <summary>
        ///     Attempt to drink some of a drink. Returns true if any interaction took place, including generation of
        ///     pop-up messages.
        /// </summary>
        private bool TryUseDrink(EntityUid uid, EntityUid userUid, DrinkComponent?drink = null)
        {
            if (!Resolve(uid, ref drink))
            {
                return(false);
            }

            // if currently being used to force-feed, cancel that action.
            if (drink.CancelToken != null)
            {
                drink.CancelToken.Cancel();
                drink.CancelToken = null;
                return(true);
            }

            if (!drink.Opened)
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-not-open",
                                                       ("owner", Name: EntityManager.GetComponent <MetaDataComponent>(drink.Owner).EntityName)), uid, Filter.Entities(userUid));
                return(true);
            }

            if (!EntityManager.TryGetComponent(userUid, out SharedBodyComponent? body))
            {
                return(false);
            }

            if (!_solutionContainerSystem.TryGetDrainableSolution((drink).Owner, out var drinkSolution) ||
                drinkSolution.DrainAvailable <= 0)
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-is-empty",
                                                       ("entity", Name: EntityManager.GetComponent <MetaDataComponent>(drink.Owner).EntityName)), uid, Filter.Entities(userUid));
                return(true);
            }

            if (!_bodySystem.TryGetComponentsOnMechanisms <StomachComponent>(userUid, out var stomachs, body))
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-cannot-drink"),
                                         userUid, Filter.Entities(userUid));
                return(true);
            }

            if (_foodSystem.IsMouthBlocked(userUid, userUid))
            {
                return(true);
            }

            var transferAmount = FixedPoint2.Min(drink.TransferAmount, drinkSolution.DrainAvailable);
            var drain          = _solutionContainerSystem.Drain(uid, drinkSolution, transferAmount);
            var firstStomach   = stomachs.FirstOrNull(
                stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, drain));

            // All stomach are full or can't handle whatever solution we have.
            if (firstStomach == null)
            {
                _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-had-enough"),
                                         userUid, Filter.Entities(userUid));

                if (EntityManager.HasComponent <RefillableSolutionComponent>(uid))
                {
                    _spillableSystem.SpillAt(userUid, drain, "PuddleSmear");
                    return(true);
                }

                _solutionContainerSystem.Refill(uid, drinkSolution, drain);
                return(true);
            }

            SoundSystem.Play(Filter.Pvs(userUid), drink.UseSound.GetSound(), userUid,
                             AudioParams.Default.WithVolume(-2f));

            _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-success-slurp"), userUid,
                                     Filter.Pvs(userUid));

            drain.DoEntityReaction(userUid, ReactionMethod.Ingestion);
            _stomachSystem.TryTransferSolution((firstStomach.Value.Comp).Owner, drain, firstStomach.Value.Comp);

            return(true);
        }
Exemplo n.º 34
0
    /// <summary>
    /// Move actor to given location if move to location is valid.
    /// </summary>
    void potMoveActor(Loc targetLoc)
    {
        // Determine which move gets actor to given position, if any
        Move move = null;
        foreach (Move m in validMoves)
            if (m.end.Equals (targetLoc))
                move = m;

        // Move actor to given loc if a valid exists
        if ( move != null ) {

            move.perform ();

            // Record move in log
            Log.current.push(move);

            // Remove all markers
            foreach (GameObject o in markers)
                Destroy(o);

            // Reselect actor
            job = Job.SelectingActor;
            selectActor ();
        }
    }
Exemplo n.º 35
0
        public override void Apply(T map)
        {
            if (!ItemThemes.CanPick)
            {
                return;
            }

            if (!MobThemes.CanPick)
            {
                return;
            }

            Rect bounds = new Rect(0, 0, map.Width, map.Height);

            //determine the number of free tiles to put items on; trim the maximum item spawn accordingly (maximum <= 1/2 of free tiles)
            //determine the number of free tiles to put mobs on; trim the maximum mob spawn accordingly (maximum <= 1/2 of free tiles)
            List <Loc> itemTiles = new List <Loc>();
            int        mobSpace  = 0;

            for (int x = bounds.X; x < bounds.X + bounds.Size.X; x++)
            {
                for (int y = bounds.Y; y < bounds.Y + bounds.Size.Y; y++)
                {
                    Loc testLoc = new Loc(x, y);
                    if (!map.TileBlocked(testLoc))
                    {
                        if (!map.HasTileEffect(new Loc(x, y)) && !map.PostProcGrid[x][y].Status[(int)PostProcType.Panel] && !map.PostProcGrid[x][y].Status[(int)PostProcType.Item])
                        {
                            bool hasItem = false;
                            foreach (MapItem item in map.Items)
                            {
                                if (item.TileLoc == testLoc)
                                {
                                    hasItem = true;
                                    break;
                                }
                            }
                            if (!hasItem)
                            {
                                itemTiles.Add(testLoc);
                            }
                        }
                        bool hasMob = false;
                        foreach (Team team in map.AllyTeams)
                        {
                            foreach (Character testChar in team.EnumerateChars())
                            {
                                if (testChar.CharLoc == testLoc)
                                {
                                    hasMob = true;
                                    break;
                                }
                            }
                        }
                        foreach (Team team in map.MapTeams)
                        {
                            foreach (Character testChar in team.EnumerateChars())
                            {
                                if (testChar.CharLoc == testLoc)
                                {
                                    hasMob = true;
                                    break;
                                }
                            }
                        }
                        if (!hasMob)
                        {
                            mobSpace++;
                        }
                    }
                }
            }

            //choose which item theme to work with
            ItemTheme chosenItemTheme = ItemThemes.Pick(map.Rand);

            //the item spawn list in this class dictates the items available for spawning
            //it will be queried for items that match the theme selected
            List <MapItem> chosenItems = chosenItemTheme.GenerateItems(map, Items);

            //place the items
            for (int ii = 0; ii < chosenItems.Count; ii++)
            {
                if (itemTiles.Count > 0)
                {
                    MapItem item      = new MapItem(chosenItems[ii]);
                    int     randIndex = map.Rand.Next(itemTiles.Count);
                    ((IPlaceableGenContext <MapItem>)map).PlaceItem(itemTiles[randIndex], item);
                    itemTiles.RemoveAt(randIndex);
                }
            }



            //the mob theme will be selected randomly
            MobTheme chosenMobTheme = MobThemes.Pick(map.Rand);

            //the mobs in this class are the ones that would be available when the game wants to spawn things outside of the floor's spawn list
            //it will be queried for monsters that match the theme provided
            List <MobSpawn> chosenMobs = chosenMobTheme.GenerateMobs(map, Mobs);

            //cover the room in a check that holds all of the monsters, and covers the room's bounds
            CheckIntrudeBoundsEvent check = new CheckIntrudeBoundsEvent();

            check.Bounds = bounds;
            {
                RevealAllEvent reveal = new RevealAllEvent();
                check.Effects.Add(reveal);

                GiveMapStatusSingleEvent statusEvent = new GiveMapStatusSingleEvent(30, 0);
                check.Effects.Add(statusEvent);

                MonsterHouseMapEvent house = new MonsterHouseMapEvent();
                house.Bounds = bounds;

                foreach (MobSpawn mob in chosenMobs)
                {
                    MobSpawn copyMob = mob.Copy();
                    if (map.Rand.Next(ALT_COLOR_ODDS) == 0)
                    {
                        copyMob.BaseForm.Skin = 1;
                    }
                    house.Mobs.Add(copyMob);
                }
                check.Effects.Add(house);
            }

            AddIntrudeStep(map, check);
        }
        public LatheQueueMenu(LatheBoundUserInterface owner)
        {
            Owner   = owner;
            SetSize = MinSize = (300, 450);
            Title   = Loc.GetString("lathequeue-menu-title");

            var vBox = new BoxContainer
            {
                Orientation = LayoutOrientation.Vertical
            };

            var hBox = new BoxContainer
            {
                Orientation           = LayoutOrientation.Horizontal,
                HorizontalExpand      = true,
                SizeFlagsStretchRatio = 2,
            };

            _icon = new TextureRect()
            {
                HorizontalExpand      = true,
                SizeFlagsStretchRatio = 2,
            };

            var vBoxInfo = new BoxContainer
            {
                Orientation           = LayoutOrientation.Vertical,
                VerticalExpand        = true,
                SizeFlagsStretchRatio = 3,
            };

            _nameLabel = new Label()
            {
                RectClipContent = true,
            };

            _description = new Label()
            {
                RectClipContent   = true,
                VerticalAlignment = VAlignment.Stretch,
                VerticalExpand    = true
            };

            _queueList = new ItemList()
            {
                VerticalExpand        = true,
                SizeFlagsStretchRatio = 3,
                SelectMode            = ItemList.ItemListSelectMode.None
            };

            vBoxInfo.AddChild(_nameLabel);
            vBoxInfo.AddChild(_description);

            hBox.AddChild(_icon);
            hBox.AddChild(vBoxInfo);

            vBox.AddChild(hBox);
            vBox.AddChild(_queueList);

            Contents.AddChild(vBox);

            ClearInfo();
        }
        private void TryCreatePackage(EntityUid user, UiAction action, string label, int pillAmount, int bottleAmount)
        {
            if (BufferSolution.TotalVolume == 0)
            {
                user.PopupMessageCursor(Loc.GetString("chem-master-window-buffer-empty-text"));
                return;
            }

            var handSys = _sysMan.GetEntitySystem <SharedHandsSystem>();
            var solSys  = _sysMan.GetEntitySystem <SolutionContainerSystem>();

            if (action == UiAction.CreateBottles)
            {
                var individualVolume = BufferSolution.TotalVolume / FixedPoint2.New(bottleAmount);
                if (individualVolume < FixedPoint2.New(1))
                {
                    user.PopupMessageCursor(Loc.GetString("chem-master-window-buffer-low-text"));
                    return;
                }

                var actualVolume = FixedPoint2.Min(individualVolume, FixedPoint2.New(30));
                for (int i = 0; i < bottleAmount; i++)
                {
                    var bottle = _entities.SpawnEntity("ChemistryEmptyBottle01", _entities.GetComponent <TransformComponent>(Owner).Coordinates);

                    //Adding label
                    LabelComponent labelComponent = bottle.EnsureComponent <LabelComponent>();
                    labelComponent.OriginalName = _entities.GetComponent <MetaDataComponent>(bottle).EntityName;
                    string val = _entities.GetComponent <MetaDataComponent>(bottle).EntityName + $" ({label})";
                    _entities.GetComponent <MetaDataComponent>(bottle).EntityName = val;
                    labelComponent.CurrentLabel = label;

                    var bufferSolution = BufferSolution.SplitSolution(actualVolume);
                    var bottleSolution = solSys.EnsureSolution(bottle, "drink");

                    solSys.TryAddSolution(bottle, bottleSolution, bufferSolution);

                    //Try to give them the bottle
                    handSys.PickupOrDrop(user, bottle);
                }
            }
            else //Pills
            {
                var individualVolume = BufferSolution.TotalVolume / FixedPoint2.New(pillAmount);
                if (individualVolume < FixedPoint2.New(1))
                {
                    user.PopupMessageCursor(Loc.GetString("chem-master-window-buffer-low-text"));
                    return;
                }

                var actualVolume = FixedPoint2.Min(individualVolume, FixedPoint2.New(50));
                for (int i = 0; i < pillAmount; i++)
                {
                    var pill = _entities.SpawnEntity("Pill", _entities.GetComponent <TransformComponent>(Owner).Coordinates);

                    //Adding label
                    LabelComponent labelComponent = pill.EnsureComponent <LabelComponent>();
                    labelComponent.OriginalName = _entities.GetComponent <MetaDataComponent>(pill).EntityName;
                    string val = _entities.GetComponent <MetaDataComponent>(pill).EntityName + $" ({label})";
                    _entities.GetComponent <MetaDataComponent>(pill).EntityName = val;
                    labelComponent.CurrentLabel = label;

                    var bufferSolution = BufferSolution.SplitSolution(actualVolume);
                    var pillSolution   = EntitySystem.Get <SolutionContainerSystem>().EnsureSolution(pill, "food");
                    solSys.TryAddSolution(pill, pillSolution, bufferSolution);

                    //Change pill Sprite component state
                    if (!_entities.TryGetComponent(pill, out SpriteComponent? sprite))
                    {
                        return;
                    }
                    sprite?.LayerSetState(0, "pill" + _pillType);

                    //Try to give them the bottle
                    handSys.PickupOrDrop(user, pill);
                }
            }

            if (_bufferSolution?.Contents.Count == 0)
            {
                _label = "";
            }

            UpdateUserInterface();
        }
 [Test] public void ReturnInput()
 {
     Assert.AreEqual("Blah", Loc.Resolve("Blah"));
 }
Exemplo n.º 39
0
 private static List <Cell> GetFlammableNeighbours(Cell cell)
 {
     return(Loc.GetMap().GetCircle(cell, 3)
            .Where(c => c.Structures.Any(s => s.Flammable()))
            .ToList());
 }
Exemplo n.º 40
0
        public void PopupDirections(EntityUid entity)
        {
            var directions = string.Join(", ", ConnectableDirections());

            Owner.PopupMessage(entity, Loc.GetString("disposal-tube-component-popup-directions-text", ("directions", directions)));
        }
 public void ClearInfo()
 {
     _icon.Texture     = Texture.Transparent;
     _nameLabel.Text   = "-------";
     _description.Text = Loc.GetString("lathequeue-menu-not-producing-text");
 }
Exemplo n.º 42
0
 /// <summary>
 /// Check if given location is within the bounds of the current map.
 /// </summary>
 /// <returns><c>true</c>, if location is in bounds, <c>false</c> otherwise.</returns>
 /// <param name="l">Location to check.</param>
 public bool isInBounds(Loc l)
 {
     return map.isInBounds (l);
 }
 [Test] public void SimpleString()
 {
     Assert.AreEqual("Resolve To Simple", Loc.Resolve("Simple"));
 }
Exemplo n.º 44
0
 private void ConnectionStateChanged(ClientConnectionState state)
 {
     ConnectStatus.Text = Loc.GetString($"connecting-state-{state}");
 }
Exemplo n.º 45
0
        /**
         * Static "constructors"
         */
        public static SPPMessage DecodeMessage(byte[] raw)
        {
            SPPMessage draft = new SPPMessage();

            if (raw.Length < 6)
            {
                Sentry.SentrySdk.AddBreadcrumb($"Message too small (Length: {raw.Length})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
                throw new InvalidDataException(Loc.GetString("sppmsg_too_small"));
            }

            if ((raw[0] != (byte)Constants.SOM && BluetoothService.Instance.ActiveModel == Model.Buds) ||
                (raw[0] != (byte)Constants.SOMPlus && BluetoothService.Instance.ActiveModel != Model.Buds))
            {
                Sentry.SentrySdk.AddBreadcrumb($"Invalid SOM (Received: {raw[0]})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
                throw new InvalidDataException(Loc.GetString("sppmsg_invalid_som"));
            }

            draft.Id = (MessageIds)Convert.ToInt32(raw[3]);
            int size;

            if (BluetoothService.Instance.ActiveModel != Model.Buds)
            {
                size       = raw[1] & 1023;
                draft.Type = (raw[2] & 16) == 0 ? MsgType.Request : MsgType.Response;
            }
            else
            {
                draft.Type = (MsgType)Convert.ToInt32(raw[1]);
                size       = Convert.ToInt32(raw[2]);
            }

            //Substract Id and CRC from size
            int rawPayloadSize = size - 3;

            byte[] payload = new byte[rawPayloadSize];

            byte[] crcData = new byte[size];
            crcData[0] = raw[3]; //Msg ID

            for (int i = 0; i < rawPayloadSize; i++)
            {
                //Start to read at byte 4
                payload[i]     = raw[i + 4];
                crcData[i + 1] = raw[i + 4];
            }

            byte crc1 = raw[4 + rawPayloadSize];
            byte crc2 = raw[4 + rawPayloadSize + 1];

            crcData[crcData.Length - 2] = crc2;
            crcData[crcData.Length - 1] = crc1;

            draft.Payload = payload;
            draft.CRC16   = util.CRC16.crc16_ccitt(crcData);

            if (size != draft.Size)
            {
                Sentry.SentrySdk.AddBreadcrumb($"Invalid size (Reported: {size}, Calculated: {draft.Size})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
                throw new InvalidDataException(Loc.GetString("sppmsg_size_mismatch"));
            }

            if (draft.CRC16 != 0)
            {
                Sentry.SentrySdk.AddBreadcrumb($"CRC checksum failed (ID: {draft.Id}, Size: {draft.Size})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
            }

            if (raw[4 + rawPayloadSize + 2] != (byte)Constants.EOM && BluetoothService.Instance.ActiveModel == Model.Buds)
            {
                Sentry.SentrySdk.AddBreadcrumb($"Invalid EOM (Received: {raw[4 + rawPayloadSize + 2]})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
                throw new InvalidDataException(Loc.GetString("sppmsg_invalid_eom"));
            }
            else if (raw[4 + rawPayloadSize + 2] != (byte)Constants.EOMPlus && BluetoothService.Instance.ActiveModel != Model.Buds)
            {
                Sentry.SentrySdk.AddBreadcrumb($"Invalid EOM (Received: {raw[4 + rawPayloadSize + 2]})", "spp", level: Sentry.Protocol.BreadcrumbLevel.Warning);
                throw new InvalidDataException(Loc.GetString("sppmsg_invalid_eom"));
            }

            return(draft);
        }
Exemplo n.º 46
0
        public CharacterSetupGui(IEntityManager entityManager,
                                 IResourceCache resourceCache,
                                 IClientPreferencesManager preferencesManager,
                                 IPrototypeManager prototypeManager)
        {
            _entityManager      = entityManager;
            _preferencesManager = preferencesManager;
            var margin = new MarginContainer
            {
                MarginBottomOverride = 20,
                MarginLeftOverride   = 20,
                MarginRightOverride  = 20,
                MarginTopOverride    = 20
            };

            AddChild(margin);

            var panelTex = resourceCache.GetTexture("/Nano/button.svg.96dpi.png");
            var back     = new StyleBoxTexture
            {
                Texture  = panelTex,
                Modulate = new Color(37, 37, 42)
            };

            back.SetPatchMargin(StyleBox.Margin.All, 10);

            var panel = new PanelContainer
            {
                PanelOverride = back
            };

            margin.AddChild(panel);

            var vBox = new VBoxContainer {
                SeparationOverride = 0
            };

            margin.AddChild(vBox);

            CloseButton = new Button
            {
                SizeFlagsHorizontal = SizeFlags.Expand | SizeFlags.ShrinkEnd,
                Text         = Loc.GetString("Save and close"),
                StyleClasses = { StyleNano.StyleClassButtonBig }
            };

            var topHBox = new HBoxContainer
            {
                CustomMinimumSize = (0, 40),
                Children          =
                {
                    new MarginContainer
                    {
                        MarginLeftOverride = 8,
                        Children           =
                        {
                            new Label
                            {
                                Text                = Loc.GetString("Character Setup"),
                                StyleClasses        = { StyleNano.StyleClassLabelHeadingBigger },
                                VAlign              = Label.VAlignMode.Center,
                                SizeFlagsHorizontal = SizeFlags.Expand | SizeFlags.ShrinkCenter
                            }
                        }
                    },
                    CloseButton
                }
            };

            vBox.AddChild(topHBox);

            vBox.AddChild(new PanelContainer
            {
                PanelOverride = new StyleBoxFlat
                {
                    BackgroundColor          = StyleNano.NanoGold,
                    ContentMarginTopOverride = 2
                }
            });

            var hBox = new HBoxContainer
            {
                SizeFlagsVertical  = SizeFlags.FillExpand,
                SeparationOverride = 0
            };

            vBox.AddChild(hBox);

            _charactersVBox = new VBoxContainer();

            hBox.AddChild(new MarginContainer
            {
                CustomMinimumSize   = (330, 0),
                SizeFlagsHorizontal = SizeFlags.Fill,
                MarginTopOverride   = 5,
                MarginLeftOverride  = 5,
                Children            =
                {
                    new ScrollContainer
                    {
                        SizeFlagsVertical = SizeFlags.FillExpand,
                        Children          =
                        {
                            _charactersVBox
                        }
                    }
                }
            });
Exemplo n.º 47
0
 public FieldObject(Loc loc, GameObject gobj)
 {
     Loc        = loc;
     _gobj      = gobj;
     _isVisible = true;
 }
Exemplo n.º 48
0
        public SandboxWindow()
        {
            Resizable = false;
            _gameHud  = IoCManager.Resolve <IGameHud>();

            Title = "Sandbox Panel";

            var vBox = new VBoxContainer {
                SeparationOverride = 4
            };

            Contents.AddChild(vBox);

            RespawnButton = new Button {
                Text = Loc.GetString("Respawn")
            };
            vBox.AddChild(RespawnButton);

            SpawnEntitiesButton = new Button {
                Text = Loc.GetString("Spawn Entities")
            };
            vBox.AddChild(SpawnEntitiesButton);

            SpawnTilesButton = new Button {
                Text = Loc.GetString("Spawn Tiles")
            };
            vBox.AddChild(SpawnTilesButton);

            GiveFullAccessButton = new Button {
                Text = Loc.GetString("Grant Full Access")
            };
            vBox.AddChild(GiveFullAccessButton);

            GiveAghostButton = new Button {
                Text = Loc.GetString("Ghost")
            };
            vBox.AddChild(GiveAghostButton);

            ToggleLightButton = new Button {
                Text = Loc.GetString("Toggle Lights"), ToggleMode = true
            };
            vBox.AddChild(ToggleLightButton);

            ToggleFovButton = new Button {
                Text = Loc.GetString("Toggle FOV"), ToggleMode = true
            };
            vBox.AddChild(ToggleFovButton);

            ToggleShadowsButton = new Button {
                Text = Loc.GetString("Toggle Shadows"), ToggleMode = true
            };
            vBox.AddChild(ToggleShadowsButton);

            ToggleSubfloorButton = new Button {
                Text = Loc.GetString("Toggle Subfloor"), ToggleMode = true
            };
            vBox.AddChild(ToggleSubfloorButton);

            SuicideButton = new Button {
                Text = Loc.GetString("Suicide")
            };
            vBox.AddChild(SuicideButton);

            ShowMarkersButton = new Button {
                Text = Loc.GetString("Show Spawns"), ToggleMode = true
            };
            vBox.AddChild(ShowMarkersButton);

            ShowBbButton = new Button {
                Text = Loc.GetString("Show BB"), ToggleMode = true
            };
            vBox.AddChild(ShowBbButton);

            MachineLinkingButton = new Button {
                Text = Loc.GetString("Link machines"), ToggleMode = true
            };
            vBox.AddChild(MachineLinkingButton);
        }
Exemplo n.º 49
0
        public GasAnalyzerWindow(GasAnalyzerBoundUserInterface owner)
        {
            var resourceCache = IoCManager.Resolve <IResourceCache>();

            Owner = owner;
            var rootContainer = new LayoutContainer {
                Name = "WireRoot"
            };

            AddChild(rootContainer);

            MouseFilter = MouseFilterMode.Stop;

            var panelTex = resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
            var back     = new StyleBoxTexture
            {
                Texture  = panelTex,
                Modulate = Color.FromHex("#25252A"),
            };

            back.SetPatchMargin(StyleBox.Margin.All, 10);

            var topPanel = new PanelContainer
            {
                PanelOverride = back,
                MouseFilter   = MouseFilterMode.Pass
            };
            var bottomWrap = new LayoutContainer
            {
                Name = "BottomWrap"
            };

            rootContainer.AddChild(topPanel);
            rootContainer.AddChild(bottomWrap);

            LayoutContainer.SetAnchorPreset(topPanel, LayoutContainer.LayoutPreset.Wide);
            LayoutContainer.SetMarginBottom(topPanel, -80);

            LayoutContainer.SetAnchorPreset(bottomWrap, LayoutContainer.LayoutPreset.VerticalCenterWide);
            LayoutContainer.SetGrowHorizontal(bottomWrap, LayoutContainer.GrowDirection.Both);

            var topContainerWrap = new VBoxContainer
            {
                Children =
                {
                    (_topContainer = new VBoxContainer()),
                    new Control {
                        MinSize    = (0, 110)
                    }
                }
            };

            rootContainer.AddChild(topContainerWrap);

            LayoutContainer.SetAnchorPreset(topContainerWrap, LayoutContainer.LayoutPreset.Wide);

            var font      = resourceCache.GetFont("/Fonts/Boxfont-round/Boxfont Round.ttf", 13);
            var fontSmall = resourceCache.GetFont("/Fonts/Boxfont-round/Boxfont Round.ttf", 10);

            Button refreshButton;
            var    topRow = new HBoxContainer
            {
                Margin   = new Thickness(4, 4, 12, 2),
                Children =
                {
                    (_nameLabel           = new Label
                    {
                        Text              = Loc.GetString("gas-analyzer-window-name"),
                        FontOverride      = font,
                        FontColorOverride = StyleNano.NanoGold,
                        VerticalAlignment = VAlignment.Center
                    }),
                    new Control
                    {
                        MinSize          = (20,                                    0),
                        HorizontalExpand = true,
                    },
Exemplo n.º 50
0
 public virtual void SetMapLoc(Loc loc)
 {
     MapLoc = loc;
 }
Exemplo n.º 51
0
 public override void DoExamine(FormattedMessage message, bool inDetailsRange)
 {
     message.AddMarkup(Loc.GetString("Next, add [color=yellow]{0}x[/color] [color=cyan]{1}[/color].", Amount, MaterialPrototype.Name));
 }
Exemplo n.º 52
0
 static ExamineSystem()
 {
     _entityNotFoundMessage = new FormattedMessage();
     _entityNotFoundMessage.AddText(Loc.GetString("examine-system-entity-does-not-exist"));
 }
Exemplo n.º 53
0
    void ShowMaze(Loc[,] Maze)
    {
        width = Maze.GetLength(0) - 1;
        height = Maze.GetLength(1) - 1;
        GameObject empty = new GameObject("Labyrinth");
        empty.isStatic = true;
        empty.transform.position = new Vector3(0, 0, 0);

        for (int x = 0; x < width; x++)
            for (int y = 0; y < height; y++)
            {
                //Если есть вертикальная стена - рисуем ее
                if (Maze[x, y].up_wall)
                    (Instantiate(up_wall, new Vector3(x * cellSize, 0, y * cellSize), Quaternion.identity) as Transform).SetParent(empty.transform);
                //Если есть горизонтальная стена - рисуем ее
                if (Maze[x, y].left_wall)
                    (Instantiate(left_wall, new Vector3(x * cellSize - 0.4f, 0, y * cellSize + 0.4f), Quaternion.identity) as Transform).SetParent(empty.transform);
            }
        //Рисуем стену снизу и справа от лабиринта
        for (int i = 0; i < width; i++)
            (Instantiate(up_wall, new Vector3(i * cellSize, 0, width * cellSize / 1.7f), Quaternion.identity) as Transform).SetParent(empty.transform);
        for (int i = 0; i < height; i++)
            (Instantiate(left_wall, new Vector3(height * cellSize * 1.7f - 0.4f, 0, i * cellSize + 0.4f), Quaternion.identity) as Transform).SetParent(empty.transform);

        //Рисуем пол
        GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
        plane.transform.localScale += new Vector3(1, 0, 1);
        plane.GetComponent<Renderer>().material = Resources.Load("planeMaterial", typeof(Material)) as Material;
        plane.transform.SetParent(empty.transform);
        //plane.transform.localScale += new Vector3(0.1f * (width - 11), 0, 0.1f * (height - 11));
        //Debug.Log(plane.transform.position);

        plane.transform.position = new Vector3(width * 0.4f, -0.5f, height * 0.4f);
        //empty.transform.SetParent(empty.transform);
    }
Exemplo n.º 54
0
        private void Cycle(bool manual = false)
        {
            if (BoltOpen)
            {
                return;
            }

            var chamberEntity = _chamberContainer.ContainedEntity;

            if (chamberEntity != null)
            {
                _chamberContainer.Remove(chamberEntity);
                var ammoComponent = chamberEntity.GetComponent <AmmoComponent>();
                if (!ammoComponent.Caseless)
                {
                    EjectCasing(chamberEntity);
                }
            }

            // Try and pull a round from the magazine to replace the chamber if possible
            var magazine  = _magazineContainer.ContainedEntity;
            var nextRound = magazine?.GetComponent <RangedMagazineComponent>().TakeAmmo();

            if (nextRound != null)
            {
                // If you're really into gunporn you could put a sound here
                _chamberContainer.Insert(nextRound);
            }

            var soundSystem = EntitySystem.Get <AudioSystem>();

            if (_autoEjectMag && magazine != null && magazine.GetComponent <RangedMagazineComponent>().ShotsLeft == 0)
            {
                if (_soundAutoEject != null)
                {
                    soundSystem.PlayAtCoords(_soundAutoEject, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-2));
                }

                _magazineContainer.Remove(magazine);
                SendNetworkMessage(new MagazineAutoEjectMessage());
            }

            if (nextRound == null && !BoltOpen)
            {
                if (_soundBoltOpen != null)
                {
                    soundSystem.PlayAtCoords(_soundBoltOpen, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-5));
                }

                if (ContainerHelpers.TryGetContainer(Owner, out var container))
                {
                    Owner.PopupMessage(container.Owner, Loc.GetString("Bolt open"));
                }
                BoltOpen = true;
                Dirty();
                UpdateAppearance();
                return;
            }

            if (manual)
            {
                if (_soundRack != null)
                {
                    soundSystem.PlayAtCoords(_soundRack, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-2));
                }
            }

            Dirty();
            UpdateAppearance();
        }
Exemplo n.º 55
0
 // Move cursor to origin and set starting location
 void Awake()
 {
     transform.position = Vector3.zero;
     loc = new Loc (0, 0);
 }
Exemplo n.º 56
0
        public override bool InteractUsing(InteractUsingEventArgs eventArgs)
        {
            // Insert magazine
            if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent magazineComponent))
            {
                if ((MagazineTypes & magazineComponent.MagazineType) == 0)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Wrong magazine type"));
                    return(false);
                }

                if (magazineComponent.Caliber != _caliber)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Wrong caliber"));
                    return(false);
                }

                if (_magNeedsOpenBolt && !BoltOpen)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Need to open bolt first"));
                    return(false);
                }

                if (_magazineContainer.ContainedEntity == null)
                {
                    if (_soundMagInsert != null)
                    {
                        EntitySystem.Get <AudioSystem>().PlayAtCoords(_soundMagInsert, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-2));
                    }
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Magazine inserted"));
                    _magazineContainer.Insert(eventArgs.Using);
                    Dirty();
                    UpdateAppearance();
                    return(true);
                }

                Owner.PopupMessage(eventArgs.User, Loc.GetString("Already holding a magazine"));
                return(false);
            }

            // Insert 1 ammo
            if (eventArgs.Using.TryGetComponent(out AmmoComponent ammoComponent))
            {
                if (!BoltOpen)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Cannot insert ammo while bolt is closed"));
                    return(false);
                }

                if (ammoComponent.Caliber != _caliber)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Wrong caliber"));
                    return(false);
                }

                if (_chamberContainer.ContainedEntity == null)
                {
                    Owner.PopupMessage(eventArgs.User, Loc.GetString("Ammo inserted"));
                    _chamberContainer.Insert(eventArgs.Using);
                    Dirty();
                    UpdateAppearance();
                    return(true);
                }

                Owner.PopupMessage(eventArgs.User, Loc.GetString("Chamber full"));
                return(false);
            }

            return(false);
        }
Exemplo n.º 57
0
 static ExamineSystem()
 {
     _entityNotFoundMessage = new FormattedMessage();
     _entityNotFoundMessage.AddText(Loc.GetString("That entity doesn't exist"));
 }
 public void Examine(FormattedMessage message, bool inDetailsRange)
 {
     message.AddMarkup(Loc.GetString($"There are { Count } slices remaining."));
 }
Exemplo n.º 59
0
        /*
         * Attempt to allocate a random monster in the dungeon.
         *
         * Place the monster at least "dis" distance from the player.
         *
         * Use "slp" to choose the initial "sleep" status
         *
         * Use "depth" for the monster level
         */
        public static bool pick_and_place_distant_monster(Cave c, Loc loc, int dis, bool slp, int depth)
        {
            int py = loc.y;
            int px = loc.x;

            int y = 0, x = 0;
            int	attempts_left = 10000;

            Misc.assert(c != null);

            /* Find a legal, distant, unoccupied, space */
            while (--attempts_left != 0)
            {
                /* Pick a location */
                y = Random.randint0(c.height);
                x = Random.randint0(c.width);

                /* Require "naked" floor grid */
                if (!Cave.cave_isempty(c, y, x)) continue;

                /* Accept far away grids */
                if (Cave.distance(y, x, py, px) > dis) break;
            }

            if (attempts_left == 0)
            {
                if (Option.cheat_xtra.value || Option.cheat_hear.value)
                {
                    Utilities.msg("Warning! Could not allocate a new monster.");
                }

                return false;
            }

            /* Attempt to place the monster, allow groups */
            if (pick_and_place_monster(c, y, x, depth, slp, true, Object.Origin.DROP)) return (true);

            /* Nope */
            return (false);
        }
Exemplo n.º 60
0
    /// <summary>
    /// Deploy this unit to a given location on the map.
    /// </summary>
    /// <param name="loc">The location that the unit is being deployed to.</param>
    /// <param name="ready">If the unit is ready to act upon being deployed.</param>
    public void deploy(Loc loc, bool ready = false)
    {
        if ( deployed )
            throw new System.Exception("Unit you attempted to deploy is already deployed");

        // Make an object of unit's type at origin, then move it to current loc
        self = Object.Instantiate (Resources.Load (type),
                                    Vector3.zero,
                                    Quaternion.identity) as GameObject;
        self.transform.Rotate (Vector3.up, 180 * team);
        move (loc);
        deployed = true;

        if (!ready)
            actCur = mvCur = 0;

        activeUnits.Add (this);
    }