Exemple #1
0
        public int Part1()
        {
            var lines = InputUtils.GetDayInputLines(1).Select(p => int.Parse(p));

            int total = 0;

            foreach (int line in lines)
            {
                total += (line / 3) - 2;
            }

            return(total);
        }
Exemple #2
0
        public long Part2()
        {
            var lines = InputUtils.GetDayInputLines(22);

            var ops = lines.Select(p => Shuffler.Parse(p, bigDeckSize));
            var agg = ops.Aggregate((a, b) => a.Merge(b));

            var pow = agg.Power(bigRepeat);
            var inv = pow.Invert();
            var app = inv.Apply(2020);

            return(app);
        }
Exemple #3
0
        public int Part1()
        {
            var lines = InputUtils.GetDayInputLines(2018, 1);

            int result = 0;

            foreach (var line in lines)
            {
                result += int.Parse(line);
            }

            return(result);
        }
        public void CreateTokensFromInputTest()
        {
            string input = "2+4-4";

            InputToken[] result = InputUtils.CreateTokensFromInput(input);
            CollectionAssert.AreEquivalent(new InputToken[] {
                new InputToken("2", InputTokenType.Operand),
                new InputToken("+", InputTokenType.Operator),
                new InputToken("4", InputTokenType.Operand),
                new InputToken("+", InputTokenType.Operator),
                new InputToken("-4", InputTokenType.Operand)
            }, result);
        }
Exemple #5
0
        public static void Eliminar()
        {
            Listar();
            Console.WriteLine("Seleccione Id:");
            int id = InputUtils.leerId();

            if (HabilidadesEspecialesDAO.obtener(id) == null)
            {
                Console.WriteLine("Id no existe.");
                return;
            }
            HabilidadesEspecialesDAO.eliminar(HabilidadesEspecialesDAO.obtener(id));
        }
Exemple #6
0
        public static void Crear()
        {
            Console.WriteLine("Nombre:");
            String nombre = InputUtils.leerString();

            Console.WriteLine("Descripcion:");
            String descripcion = InputUtils.leerString();

            HabilidadesEspecialesDAO.crear(new HabilidadEspecial {
                Nombre       = nombre,
                Descripccion = descripcion
            });
        }
        public static void Eliminar()
        {
            Listar();
            Console.WriteLine("Seleccione Id:");
            int id = InputUtils.leerId();

            if (CaracteristicasVariablesDAO.obtener(id) == null)
            {
                Console.WriteLine("Id no existe.");
                return;
            }
            CaracteristicasVariablesDAO.eliminar(CaracteristicasVariablesDAO.obtener(id));
        }
        public static void Eliminar()
        {
            ListarInformacionBasica();
            Console.WriteLine("Seleccione Id:");
            int id = InputUtils.leerId();

            if (PersonajeDAO.obtener(id) == null)
            {
                Console.WriteLine("Id no existe.");
                return;
            }
            PersonajeDAO.eliminar(PersonajeDAO.obtener(id));
        }
Exemple #9
0
 void setDirection()
 {
     if (!InputUtils.MovingHorizontaly())
     {
         return;
     }
     this.Direction = InputUtils.GoingRight() ? Direction2D.Right : Direction2D.Left;
     if ((Direction == Direction2D.Left || Direction == Direction2D.Right) && direction != Direction)
     {
         skinSpriteRenderer.flipX = !skinSpriteRenderer.flipX;
         direction = Direction;
     }
 }
    private void UpdateInputToMoveAndStretchNotes(EKeyboardModifier modifier)
    {
        Vector2 arrowKeyDirection = InputUtils.GetArrowKeyDirection();

        if (arrowKeyDirection == Vector2.zero)
        {
            return;
        }

        List <Note> selectedNotes = selectionController.GetSelectedNotes();

        if (selectedNotes.IsNullOrEmpty())
        {
            return;
        }

        if (modifier == EKeyboardModifier.None)
        {
            return;
        }

        List <Note> followingNotes = GetFollowingNotesOrEmptyListIfDeactivated(selectedNotes);

        // Move with Shift
        if (modifier == EKeyboardModifier.Shift && arrowKeyDirection.x != 0)
        {
            moveNotesAction.MoveNotesHorizontalAndNotify((int)arrowKeyDirection.x, selectedNotes, followingNotes);
        }
        if (modifier == EKeyboardModifier.Shift && arrowKeyDirection.y != 0)
        {
            moveNotesAction.MoveNotesVerticalAndNotify((int)arrowKeyDirection.y, selectedNotes, followingNotes);
        }

        // Move notes one octave up / down via Ctrl+Shift
        if (modifier == EKeyboardModifier.CtrlShift)
        {
            moveNotesAction.MoveNotesVerticalAndNotify((int)arrowKeyDirection.y * 12, selectedNotes, followingNotes);
        }

        // Extend right side with Alt
        if (modifier == EKeyboardModifier.Alt)
        {
            extendNotesAction.ExtendNotesRightAndNotify((int)arrowKeyDirection.x, selectedNotes, followingNotes);
        }

        // Extend left side with Ctrl
        if (modifier == EKeyboardModifier.Ctrl)
        {
            extendNotesAction.ExtendNotesLeftAndNotify((int)arrowKeyDirection.x, selectedNotes);
        }
    }
        private OptionResult CreateStudent(string command, IList <string> args)
        {
            Regex matricNumberRegex = new Regex("/^U[0-9]{7}[A-Z]");

            Console.Write("Enter matric number (valid format): ");
            string matricNumber = Console.ReadLine();

            if (!matricNumberRegex.IsMatch(matricNumber))
            {
                Log.Error(3);
                return(OptionResult.Break);
            }

            Console.Write("Enter full name: ");
            string fullName = Console.ReadLine();

            Console.Write("Enter study year (1-7): ");
            int studyYear;

            if (!int.TryParse(Console.ReadLine(), out studyYear))
            {
                Log.Error(2);
                return(OptionResult.Break);
            }
            if (studyYear < 1 || studyYear > 7)
            {
                Log.Error(4);
                return(OptionResult.Break);
            }

            Console.Write("Sex types: ");
            Sex sex;

            if (!InputUtils.ReadEnumChoice <Sex>(out sex))
            {
                Log.Error(1);
                return(OptionResult.Break);
            }

            Console.Write("Nationality types: ");
            Nationality nationality;

            if (!InputUtils.ReadEnumChoice <Nationality>(out nationality))
            {
                Log.Error(1);
                return(OptionResult.Break);
            }

            //System.Instance.Database.StudentManager.Create(matricNumber, fullName, studyYear, sex, nationality);
            return(OptionResult.Break);
        }
 void Update()
 {
     if (InputUtils.OnPressed())
     {
         _touchStartPoint = InputUtils.GetTouchPosition();
     }
     else if (InputUtils.OnReleased())
     {
         if (EnableDrag || (InputUtils.GetTouchPosition() - _touchStartPoint).sqrMagnitude < 225 && Event != null)
         {
             Event.Shoot();
         }
     }
 }
 void Update()
 {
     if (InputUtils.OnPressed())
     {
         GameObject go = EventSystem.current.currentSelectedGameObject;
         if (go == null)
         {
             if (LandlordsModel.Instance.IsInFight)
             {
                 Interaction.Instance.Chongxuan();
             }
         }
     }
 }
Exemple #14
0
        private void DirectionCheck()
        {
            m_rawDirection = new Vector3(_input.Move.x, 0, _input.Move.y);

            if (InputUtils.ValidMove(_input.Move))
            {
                m_direction = m_rawDirection.normalized;
            }

            if (!m_idle)
            {
                m_lookDirection = m_direction + new Vector3(0, 0.2f, 0);
            }
        }
Exemple #15
0
        /// <summary>
        /// 更新输入
        /// </summary>
        void updateInputting()
        {
            freezeTime += Time.deltaTime;

            var down = false;

            if (freezeTime >= freezeDuration)
            {
                down = InputUtils.getKeyDown(KeyCode.DownArrow, KeyCode.S);
                if (down)
                {
                    freezeTime = 0;
                }
                //var ver = Input.GetAxisRaw("Vertical");
            }

            bool left  = InputUtils.getKeyDown(KeyCode.LeftArrow, KeyCode.A);
            bool right = InputUtils.getKeyDown(KeyCode.RightArrow, KeyCode.D);

            if (right)
            {
                fallingX++;
            }
            if (left)
            {
                fallingX--;
            }
            //if (right || left) freezeTime = 0;

            var w = currentMap.mapX; fallingX = (w + fallingX) % w;

            var rotate = InputUtils.getKeyDown(KeyCode.UpArrow, KeyCode.W, KeyCode.Space);

            if (rotate)
            {
                currentGrids.rotate();
            }
            if (down)
            {
                placeGrids(currentGrids, fallingX);
            }
            else if (!currentMap.isPlacePointValid(currentGrids, fallingX, fallingY - 1))
            {
                placeGrids(currentGrids, fallingX, fallingY);
            }
            else
            {
                placeGrids(currentGrids, fallingX, fallingY, true);
            }
        }
        private void DirectionCheck(ControlProperty control, InputProperty input)
        {
            control.m_rawDirection = new Vector3(input.Move.x, 0, input.Move.y);

            if (InputUtils.ValidMove(input.Move))
            {
                control.m_direction = control.m_rawDirection.normalized;
            }

            if (!control.m_idle)
            {
                control.m_lookDirection = control.m_direction + new Vector3(0, 0.2f, 0);
            }
        }
Exemple #17
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Advent Of Code 2016, day 9");

            var input = InputUtils.GetInput(args).ReadToEnd().Trim();

            var decompressedFileLength = GetDecompressedFileLength(input, recurse: false);

            Console.WriteLine($"Decompressed file length: {decompressedFileLength}");

            var decompressedFileV2Length = GetDecompressedFileLength(input);

            Console.WriteLine($"Decompressed file v2 length: {decompressedFileV2Length}");
        }
Exemple #18
0
        void Start()
        {
            // Clear selection so we can't manipulate things
            Selection.activeGameObject = null;

            SetupPreferences();

            m_SmoothInput.Reset(0.0f);

            if (primary)
            {
                this.AddRayVisibilitySettings(rayOrigin, this, false, false);
                SetupBrushUI();
                HandleBrushSize(m_Preferences.brushSize);

                m_ToolMenu = this.InstantiateMenuUI(rayOrigin, m_MenuPrefab);
                var contextMenu = m_ToolMenu.GetComponent <AnnotationContextMenu>();
                this.ConnectInterfaces(contextMenu, rayOrigin);
                contextMenu.close        = Close;
                contextMenu.colorChanged = OnAnnotationColorChanged;
                OnAnnotationColorChanged(m_Preferences.annotationColor);
                contextMenu.preferences   = m_Preferences;
                contextMenu.toolRayOrigin = rayOrigin;

                var controls = new BindingDictionary();
                InputUtils.GetBindingDictionaryFromActionMap(m_ActionMap, controls);

                foreach (var control in controls)
                {
                    var tooltipText      = control.Key;
                    var suppressExisting = control.Key == "Vertical" || control.Key == "StickButton";
                    if (suppressExisting)
                    {
                        tooltipText = null;
                    }

                    foreach (var id in control.Value)
                    {
                        var request = (ProxyFeedbackRequest)this.GetFeedbackRequestObject(typeof(ProxyFeedbackRequest));
                        request.node             = node;
                        request.control          = id;
                        request.priority         = 1;
                        request.tooltipText      = tooltipText;
                        request.suppressExisting = suppressExisting;
                        this.AddFeedbackRequest(request);
                    }
                }
            }
        }
        protected override void OnMouseMove(MouseMoveEventArgs e)
        {
            base.OnMouseMove(e);
            try
            {
                InputUtils.UpdateMouse(e.Mouse);
                if (linerider.IO.TrackRecorder.Recording)
                {
                    return;
                }
                var r = _input.ProcessMouseMessage(e);
                _uicursor = _input.MouseCaptured;
                if (Canvas.GetOpenWindows().Count != 0)
                {
                    UpdateCursor();
                    return;
                }
                if (_dragRider)
                {
                    var pos     = new Vector2d(e.X, e.Y);
                    var gamepos = ScreenPosition + (pos / Track.Zoom);
                    Track.Stop();
                    using (var trk = Track.CreateTrackWriter())
                    {
                        trk.Track.StartOffset = gamepos;
                        Track.Reset();
                        Track.NotifyTrackChanged();
                    }
                    Invalidate();
                }
                if (CurrentTools.SelectedTool.RequestsMousePrecision)
                {
                    CurrentTools.SelectedTool.OnMouseMoved(new Vector2d(e.X, e.Y));
                }

                if (r)
                {
                    Invalidate();
                }
                UpdateCursor();
            }
            catch (Exception ex)
            {
                // SDL2 backend eats exceptions.
                // we have to manually crash.
                Program.Crash(ex, true);
                Close();
            }
        }
Exemple #20
0
        public override void choose(T item)
        {
            Assert.isNotNull(item, "item cannot be null");
            if (_isDisabled)
            {
                return;
            }

            var index = array.IndexOf(item);

            if (selected.Count > 0 && rangeSelect && multiple && InputUtils.isShiftDown())
            {
                int oldRangeState = rangeStart;
                snapshot();

                // Select new range.
                int start = rangeStart, end = index;
                if (start > end)
                {
                    var temp = end;
                    end   = start;
                    start = temp;
                }

                if (!InputUtils.isControlDown())
                {
                    selected.Clear();
                }
                for (int i = start; i <= end; i++)
                {
                    selected.Add(array[i]);
                }

                if (fireChangeEvent())
                {
                    rangeStart = oldRangeState;
                    revert();
                }

                cleanup();
                return;
            }
            else
            {
                rangeStart = index;
            }

            base.choose(item);
        }
        public Vector2 GetPointBetweenFingers_Gui()
        {
            if (Input.touches == null || Input.touches.Length == 0)
            {
                return(ScreenPosToGui(InputUtils.GetInputPosition()));
            }
            if (Input.touches.Length < 2)
            {
                return(ScreenPosToGui(Input.GetTouch(0).position));
            }
            var poin1 = Input.GetTouch(0).position;
            var poin2 = Input.GetTouch(1).position;

            return(ScreenPosToGui((poin1 + poin2) / 2));
        }
Exemple #22
0
    void PointerDown()
    {
        if (InputUtils.OnReleased())
        {
            m_PointerStatus = PointerStatus.Idle;
            m_SelectArea.ClearNodeList();
        }

        Vector2 vec = InputUtils.GetTouchPosition() - m_StartPos;

        if (vec.magnitude > StartDragValve)
        {
            m_PointerStatus = PointerStatus.Dragging;
        }
    }
Exemple #23
0
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !InputUtils.CheckMouseOnUI())
        {
            mIsDown = true;

            bridgeInfo.GetComponent <Image>().DOFade(0, .8f);
        }

        if (Input.GetMouseButton(0) && mIsDown)
        {
            if (mLastPos != Vector3.zero)
            {
                var delta = RATIO * (Input.mousePosition - mLastPos);

                mSphericalPos.phi   -= delta.x;
                mSphericalPos.theta += delta.y;

                if (mSphericalPos.theta < 0.15f * Mathf.PI)
                {
//                    Debug.LogError("Cs");
                    mSphericalPos.theta = Mathf.PI * 0.15f;
                }

//                Debug.Log(delta + "   " + mSphericalPos);
            }

            mLastPos = Input.mousePosition;
            var a = camera.transform.localPosition;
            var b = SphericalCoordinateSystem.ToCartesian(mSphericalPos) + mCurrentFocus;

            if (b.y <= mCurrentFocus.y)
            {
                b = new Vector3(b.x, mCurrentFocus.y, b.z);
            }
//            camera.transform.localPosition = b;
            camera.transform.localPosition = Vector3.Lerp(a, b, Time.deltaTime * 4);
            camera.transform.LookAt(mCurrentFocus);
        }

        if (Input.GetMouseButtonUp(0))
        {
            mLastPos = Vector3.zero;
            mIsDown  = false;
        }

        UpdateUI();
    }
        public ActionMapInput CreateActionMapInput(ActionMap map, InputDevice device)
        {
            // Check for improper use of action maps first
            if (device != null && !IsValidActionMapForDevice(map, device))
            {
                return(null);
            }

            var devices = device == null?GetSystemDevices() : new List <InputDevice>
            {
                device
            };

            var actionMapInput = ActionMapInput.Create(map);

            // It's possible that there are no suitable control schemes for the device that is being initialized,
            // so ActionMapInput can't be marked active
            var successfulInitialization = false;

            if (actionMapInput.TryInitializeWithDevices(devices))
            {
                successfulInitialization = true;
            }
            else
            {
                // For two-handed tools, the single device won't work, so collect the devices from the action map
                devices = InputUtils.CollectInputDevicesFromActionMaps(new List <ActionMap>()
                {
                    map
                });
                if (actionMapInput.TryInitializeWithDevices(devices))
                {
                    successfulInitialization = true;
                }
            }

            if (successfulInitialization)
            {
                actionMapInput.autoReinitialize = false;

                // Resetting AMIs cause all AMIs (active or not) that use the same sources to be reset, which causes
                // problems (e.g. dropping objects because wasJustPressed becomes true when reset)
                actionMapInput.resetOnActiveChanged = false;
                actionMapInput.active = true;
            }

            return(actionMapInput);
        }
Exemple #25
0
        public int Part2()
        {
            List <int> results = new List <int>();

            List <int> values = new List <int> {
                5, 6, 7, 8, 9
            };
            var permutations = values.Permute();

            foreach (var permutation in permutations)
            {
                IntcodeComputer a = new IntcodeComputer(InputUtils.GetFileName(7));
                IntcodeComputer b = new IntcodeComputer(InputUtils.GetFileName(7));
                IntcodeComputer c = new IntcodeComputer(InputUtils.GetFileName(7));
                IntcodeComputer d = new IntcodeComputer(InputUtils.GetFileName(7));
                IntcodeComputer e = new IntcodeComputer(InputUtils.GetFileName(7));

                a.EnqueueInput(permutation.ToList()[0]);
                b.EnqueueInput(permutation.ToList()[1]);
                c.EnqueueInput(permutation.ToList()[2]);
                d.EnqueueInput(permutation.ToList()[3]);
                e.EnqueueInput(permutation.ToList()[4]);

                long eOutput = 0;

                while (!a.IsHalted && !b.IsHalted && !c.IsHalted && !d.IsHalted && !e.IsHalted)
                {
                    a.EnqueueInput(eOutput);
                    long aOutput = a.RunUntilNextOutput();

                    b.EnqueueInput(aOutput);
                    long bOutput = b.RunUntilNextOutput();

                    c.EnqueueInput(bOutput);
                    long cOutput = c.RunUntilNextOutput();

                    d.EnqueueInput(cOutput);
                    long dOutput = d.RunUntilNextOutput();

                    e.EnqueueInput(dOutput);
                    eOutput = e.RunUntilNextOutput();
                }

                results.Add((int)eOutput);
            }

            return(results.Max());
        }
        public void GameUpdate()
        {
            GameUpdateHandleInput();
            var updates = Track.Scheduler.UnqueueUpdates();

            if (updates > 0)
            {
                Invalidate();
                if (Track.Playing)
                {
                    if (InputUtils.Check(Hotkey.PlaybackZoom))
                    {
                        Track.ZoomBy(0.08f);
                    }
                    else if (InputUtils.Check(Hotkey.PlaybackUnzoom))
                    {
                        Track.ZoomBy(-0.08f);
                    }
                }
            }
            if (_autosavewatch.Elapsed.TotalMinutes >= 5)
            {
                _autosavewatch.Restart();
                new Thread(() => { Track.BackupTrack(false); }).Start();
            }


            if (Track.Playing)
            {
                if (ReversePlayback)
                {
                    for (int i = 0; i < updates; i++)
                    {
                        Track.PreviousFrame();
                        Track.UpdateCamera(true);
                    }
                }
                else
                {
                    Track.Update(updates);
                }
            }
            AudioService.EnsureSync();
            if (Program.NewVersion != null)
            {
                Canvas.ShowOutOfDate();
            }
        }
Exemple #27
0
        public static void Crear()
        {
            Console.WriteLine("Nombre:");
            String nombre = InputUtils.leerString();

            Console.WriteLine("Descripcion:");
            String descripcion = InputUtils.leerString();

            ClasesDAO.crear(new Clase
            {
                Nombre                = nombre,
                Descripcion           = descripcion,
                habilidadesEspeciales = new List <HabilidadEspecial>(),
                personajes            = new List <Personaje>()
            });
        }
Exemple #28
0
    public static void LoadWorldState(World world)
    {
        // Tryo to load from file.
        string path = OutputUtils.RealitySaveDirectory + world.RealityName + OutputUtils.WorldStateSaveFile;
        WorldSaveState sd = InputUtils.FileToObject<WorldSaveState>(path);

        if(sd != null)
        {
            sd.Apply(world);
            Debug.Log("Applied loaded world state...");
        }
        else
        {
            Debug.LogError("Null world state save file, no world state data applied.");
        }
    }
Exemple #29
0
 private void OnDestroy()
 {
     // Remove this ContextMenu from the list of opened ContextMenus only after all Input has been released
     // to avoid triggering additional actions (e.g. onClick of button).
     if (CoroutineManager.Instance != null)
     {
         CoroutineManager.Instance.StartCoroutineAlsoForEditor(
             CoroutineUtils.ExecuteWhenConditionIsTrue(
                 () => !InputUtils.AnyKeyboardOrMouseOrTouchPressed(),
                 () => RemoveOpenContextMenuFromList(this)));
     }
     else
     {
         RemoveOpenContextMenuFromList(this);
     }
 }
Exemple #30
0
        public void DrawCursor(SpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState, SamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise);

            float cursorSize = CursorScale * GlobalScale * ((float)p_CursorWidth / (float)p_CursorTexture.Width);

            Vector2 cursorPos = InputUtils.GetMousePosition();

            spriteBatch.Draw(p_CursorTexture,
                             new Rectangle(
                                 (int)(cursorPos.X + p_CursorOffset.X + cursorSize), (int)(cursorPos.Y + p_CursorOffset.Y + cursorSize),
                                 (int)(p_CursorTexture.Width * cursorSize), (int)(p_CursorTexture.Height * cursorSize)),
                             Color.White);

            spriteBatch.End();
        }