public RigEditorViewModel(RigResource.RigResource rig) { rig.ResourceChanged += OnResourceChanged; mIsSaving = false; mChildren = new ObservableCollection<BoneViewModel>(); mRig = rig; mManager = new BoneManager(); mManager.Bones = mRig.Bones; foreach (RigResource.RigResource.Bone bone in mRig.Bones) { if (bone.ParentBoneIndex == -1) { mChildren.Add(new BoneViewModel(this, this, bone, mManager)); } } mManager.BoneAdded += OnBoneAdded; mManager.BoneRemoved += OnBoneRemoved; mManager.BoneParentChanged += OnBoneParentChanged; AddBoneCommand = new UserCommand<RigEditorViewModel>(x => true, y => y.Manager.AddBone(new RigResource.RigResource.Bone(0, null), null)); GetMatrixInfoCommand = new UserCommand<RigEditorViewModel>(x => true, ExecuteMatrixInfo); CommitCommand = new UserCommand<RigEditorViewModel>(x => true, y => { mIsSaving = true; Application.Current.Shutdown(); }); CancelCommand = new UserCommand<RigEditorViewModel>(x => true, y => { mIsSaving = false; Application.Current.Shutdown(); }); IResourceKey key = new TGIBlock(0, null); key.ResourceType = 0x00000000; }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { User thisRealUser = ChatRunner.Server.GetUser(user.UID); if (command.Command == "uptonogood") { /*if (!user.ChatControl) return FastMessage("This command doesn't *AHEM* exist");*/ thisRealUser.Hiding = !thisRealUser.Hiding; if (thisRealUser.Hiding) { ChatRunner.Server.BroadcastUserList(); ChatRunner.Server.Broadcast(new LanguageTagParameters(ChatTags.Leave, thisRealUser), new SystemMessageJSONObject()); return FastMessage("You're now hiding. Hiding persists across reloads. Be careful, you can still use commands!"); } else { UnhideUser(user.UID); /*thisRealUser.LastJoin = DateTime.Now; ChatRunner.Server.BroadcastUserList(); ChatRunner.Server.Broadcast(new LanguageTagParameters(ChatTags.Join, thisRealUser), new SystemMessageJSONObject());*/ return FastMessage("You've come out of hiding."); } } return new List<JSONObject>(); }
static BoneOps() { DeleteCommand = new UserCommand<BoneViewModel>(IsABone, ExecuteDeleteBone); DeleteHierarchyCommand = new UserCommand<BoneViewModel>(IsAParent, ExecuteDeleteHierarchy); AddCommand = new UserCommand<BoneViewModel>(IsABone, ExecuteAddBone); CloneCommand = new UserCommand<BoneViewModel>(IsABone, ExecuteClone); CloneHierarchyCommand = new UserCommand<BoneViewModel>(IsAParent, ExecuteCloneHierarchy); SetParentCommand = new UserCommand<BoneViewModel>(HasNonDescendants, ExecuteSetParent); UnparentCommand = new UserCommand<BoneViewModel>(IsAChild, ExecuteUnparent); FindReplaceCommand = new UserCommand<BoneViewModel>(IsAParent, ExecuteFindReplace); PrefixCommand = new UserCommand<BoneViewModel>(IsAParent, ExecutePrefix); SuffixCommand = new UserCommand<BoneViewModel>(IsAParent, ExecuteSuffix); RotationMatrixInputCommand = new UserCommand<BoneViewModel>(IsABone, ExecuteRotationMatrixInput); }
public ActionResult Edit(int id, UserModel userModel) { if (ModelState.IsValid) { var userParameters = GetCreateOrEditParameters(userModel); UserCommand.Edit(id, userParameters); AddModelSuccess(Translations.EditSuccess.FormatWith(TranslationsHelper.Get <User>())); return(RedirectToAction("Index")); } else { return(View(userModel)); } }
public CustomIntIdentity Create(UserCommand user) { return(new CustomIntIdentity { PhoneNumber = user.PhoneNumber, Email = user.Email, UserName = user.Username, Name = user.Name, Picture = user.Picture, EmailConfirmed = user.EmailConfirmed, SocialNumber = user.SocialNumber, Birthdate = user.Birthdate, LockoutEnd = null, }); }
Vector3 CalculateGroundVelocity(Vector3 velocity, ref UserCommand command, float playerSpeed, float friction, float acceleration, float deltaTime) { var moveYawRotation = Quaternion.Euler(0, command.lookYaw + command.moveYaw, 0); var moveVec = moveYawRotation * Vector3.forward * command.moveMagnitude; // Applying friction var groundVelocity = new Vector3(velocity.x, 0, velocity.z); var groundSpeed = groundVelocity.magnitude; var frictionSpeed = Mathf.Max(groundSpeed, 1.0f) * deltaTime * friction; var newGroundSpeed = groundSpeed - frictionSpeed; if (newGroundSpeed < 0) { newGroundSpeed = 0; } if (groundSpeed > 0) { groundVelocity *= (newGroundSpeed / groundSpeed); } // Doing actual movement (q2 style) var wantedGroundVelocity = moveVec * playerSpeed; var wantedGroundDir = wantedGroundVelocity.normalized; var currentSpeed = Vector3.Dot(wantedGroundDir, groundVelocity); var wantedSpeed = playerSpeed * command.moveMagnitude; var deltaSpeed = wantedSpeed - currentSpeed; if (deltaSpeed > 0.0f) { var accel = deltaTime * acceleration * playerSpeed; var speed_adjustment = Mathf.Clamp(accel, 0.0f, deltaSpeed) * wantedGroundDir; groundVelocity += speed_adjustment; } if (!Game.config.easterBunny) { newGroundSpeed = groundVelocity.magnitude; if (newGroundSpeed > playerSpeed) { groundVelocity *= playerSpeed / newGroundSpeed; } } velocity.x = groundVelocity.x; velocity.z = groundVelocity.z; return(velocity); }
public ActionResult Register(RegisterViewModel model) { if (ModelState.IsValid) { //check if user exists var user = identityServiceClient.GetUserByEmail(model.Email).Result?.FirstOrDefault(); if (user == null) { var userCommand = new UserCommand() { Email = model.Email, PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password), Firstname = model.Firstname, Lastname = model.Lastname, UserName = model.Email, EmailConfirmed = false, Gender = model.Gender, MobileNumberConfirmed = false, DateOfBirth = string.Empty, SecurityStamp = Guid.NewGuid().ToString(), Status = Lidia.Identity.Common.Models.EntityStatus.Active, AccountStatus = Lidia.Identity.Common.Models.AccountStatus.Active, Environment = this.Environment, UserToken = this.UserToken, SessionId = this.SessionId, Country = "TR", RoleId = 1002, //User ThreadId = ThreadId }; var identityServiceResponse = identityServiceClient.CreateUser(userCommand); if (identityServiceResponse.Type == Lidia.Identity.Common.Models.ServiceResponseTypes.Success) { var login = SignInManager.PasswordSignInAsync(model.Email, model.Password, false, shouldLockout: false); return(Redirect("/")); } } else { model.Errors.Add("Kullanıcı kaydı bulunuyor."); } } return(RedirectToAction("Index", "Home")); }
public MainViewModel() { SettingCheck = false; UserCheck = false; navigateToPageCommandProperty = new navigateToPageCommand(); bookMarkCommandProperty = new BookMarkCommand(); settingCommandProperty = new SettingCommand(); settingPopUpPage = new SettingPopUp(this); userCommandProprety = new UserCommand(); userPopUpPage = new UserPopUp(this); mainCloseCommandProperty = new MainCloseCommand(); toMaxOrNormalCommandProperty = new ToMaxOrNormalCommand(); toMiniCommandProperty = new ToMiniCommand(); titleBarCommandProperty = new MainTitleBarCommand(); searchCommandProperty = new searchCommand(); }
public override void HandleInput(UserCommand command) { if (string.IsNullOrEmpty(command.FullCommand)) { Game.WriteLine("Please enter a name.", PcmColor.Red); return; } GameState.Miner = Miner.Default(); GameState.Miner.Name = command.FullCommand; GameState.PromptText = null; Game.SwitchScene(Scene.Create(new List <IGameEntity> { new WelcomeEntity(GameState) })); }
// public override bool SaveFiles() // { // if(MyExtensions.MySerialize.SaveObject<List // } public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); if (command.Command == "drawsubmit") { //unsavedMessages.Add(new DrawingInfo() { Drawing = command.Arguments[0], User = user, postTime = DateTime.Now }); UserMessageJSONObject drawingMessage = new UserMessageJSONObject(user, command.Arguments[0], command.tag); drawingMessage.encoding = Nickname; drawingMessage.spamValue = 0.50; drawingMessage.SetUnspammable(); outputs.Add(drawingMessage); } return outputs; //base.ProcessCommand(command, user, users); }
public async Task <IHttpActionResult> Register(UserCommand userCommand) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } IdentityResult result = await _userRepository.AddUser(userCommand); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok()); }
// CL_SendCmd public static void SendCmd() { if (Cls.state != ClientActivityState.Connected) { return; } if (Cls.signon == SIGNONS) { UserCommand cmd = new UserCommand(); // get basic movement from keyboard BaseMove(ref cmd); // allow mice or other external controllers to add to the move Input.Move(cmd); // send the unreliable message Client.SendMove(ref cmd); } if (Cls.demoplayback) { Cls.message.Clear();// SZ_Clear (cls.message); return; } // send the reliable message if (Cls.message.IsEmpty) { return; // no message at all } if (!Net.CanSendMessage(Cls.netcon)) { Con.DPrint("CL_WriteToServer: can't send\n"); return; } if (Net.SendMessage(Cls.netcon, Cls.message) == -1) { Host.Error("CL_WriteToServer: lost server connection"); } Cls.message.Clear(); }
public void Validate_Should_Not_Add_User_With_Duplicate_Email() { UserCommand command = UserCommandHandlerTestHelper.GetCommand(); IList <User> users = Substitute.For <IList <User> >(); users.Count.Returns(1); read.Where(x => x.Email == "*****@*****.**").ReturnsForAnyArgs(users); string expectedInvalid = string.Format("A user already exists with the email {0}", command.Email); UserCommandResult result = UserCommandHandlerHelper.Validate(command, this.write, this.read); Assert.IsFalse(result.Valid); Assert.AreEqual(expectedInvalid, result.InvalidEmail); }
public static string GetPrettyCommandName(UserCommand command) { var name = command.ToString(); var nameU = name.ToUpperInvariant(); var nameL = name.ToLowerInvariant(); for (var i = name.Length - 1; i > 0; i--) { if (((name[i - 1] != nameU[i - 1]) && (name[i] == nameU[i])) || (name[i - 1] == nameL[i - 1]) && (name[i] != nameL[i])) { name = name.Insert(i, " "); nameL = nameL.Insert(i, " "); } } return(name); }
private void userCommandKICK(UserCommand cmd) { string handle = chatWindow.getCurrentChannelName(); string[] parts = cmd.parameters.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); if (parts.Length > 0) { if (parts.Length == 1) { client.send(new IRCCommand(null, "KICK", handle, parts[0])); } else { client.send(new IRCCommand(null, "KICK", handle, parts[0], parts.Last())); } } }
public void SampleInput(ref UserCommand command, float deltaTime) { // To accumulate move we store the input with max magnitude and uses that Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); float angle = Vector2.Angle(Vector2.up, moveInput); if (moveInput.x < 0) { angle = 360 - angle; } float magnitude = Mathf.Clamp(moveInput.magnitude, 0, 1); // if (magnitude > maxMoveMagnitude) // { // maxMoveYaw = angle; // maxMoveMagnitude = magnitude; // } command.moveYaw = angle; command.moveMagnitude = magnitude; float invertY = 1.0f; Vector2 deltaMousePos = new Vector2(0, 0); if (deltaTime > 0.0f) { deltaMousePos += new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y") * invertY); } const float configMouseSensitivity = 1.5f; command.lookYaw += deltaMousePos.x * configMouseSensitivity; command.lookYaw = command.lookYaw % 360; while (command.lookYaw < 0.0f) { command.lookYaw += 360.0f; } command.lookPitch += deltaMousePos.y * configMouseSensitivity; command.lookPitch = Mathf.Clamp(command.lookPitch, 0, 180); command.jump = (command.jump != 0 || Input.GetKeyDown(KeyCode.Space))?1:0; command.sprint = (command.sprint != 0 || Input.GetKey(KeyCode.LeftShift))?1:0; // command.skill = }
public async Task AddAsync(UserCommand user) { var userValid = new User { Age = user.Age, FirstName = user.FirstName, LastName = user.LastName, Street = user.Street, StreetNumber = user.StreetNumber, TelephoneNumber = user.TelephoneNumber, Username = user.Username, EmailAddress = user.EmailAddress }; await _context.UsersData.AddAsync(userValid); await _context.SaveChangesAsync(); }
/// <summary> /// Authenticates this instance. /// </summary> /// <remarks>A successful execution of this method will result in a Current State of Transaction. /// Unsuccessful USER or PASS commands can be reattempted by resetting the Username or Password /// properties and re-execution of the methods.</remarks> /// <exception cref="Pop3Exception"> /// If the Pop3Server is unable to be connected. /// If the User command is unable to be successfully executed. /// If the Pass command is unable to be successfully executed. /// </exception> public void Authenticate() { //Connect(); //execute the user command. using (UserCommand userCommand = new UserCommand(_clientStream, Username)) { ExecuteCommand <Pop3Response, UserCommand>(userCommand); } //execute the pass command. using (PassCommand passCommand = new PassCommand(_clientStream, Password)) { ExecuteCommand <Pop3Response, PassCommand>(passCommand); } CurrentState = Pop3State.Transaction; }
private async Task SendEmailToUser(IDomainUser user, UserCommand request, AccountResult accountResult, EmailType type) { if (user.EmailConfirmed) { return; } var email = await _emailRepository.GetByType(type); if (email is null) { return; } var claims = await _userService.GetClaimByName(user.UserName); await _emailService.SendEmailAsync(email.GetMessage(user, accountResult, request, claims)); }
public void LoadUserDataFromStorage() { //Arrange var customer = new UserCommand { UserName = "******", Email = "*****@*****.**", Password = "******", LoyaltyLevel = CustomerLoyalty.Standard, YearlySpend = 10 }; //Act var userRepository = new UserRepository(); var customerResult = userRepository.GetUserByName(customer.UserName).Result; //Assert Assert.AreEqual(customer.UserName, customerResult.UserName); Assert.AreEqual(customer.Email, customerResult.Email); Assert.AreEqual(customer.Password, customerResult.PasswordHash); Assert.AreEqual(customer.LoyaltyLevel, customerResult.LoyaltyLevel); Assert.AreEqual(customer.YearlySpend, customerResult.YearlySpend); }
public UserHandlerTests() { this.notFoundUserId = this.Fixture.Create <Guid>().ToString(); this.userCommand = new UserCommand(); this.repository = Substitute.For <IUserRepository>(); this.userHandler = new UserHandler(this.repository); this.userCommand.FirstName = this.MockString(); this.userCommand.LastName = this.MockString(); this.userCommand.Email = $"{this.MockString()}@teste.com"; this.userCommand.Password = this.MockString(); this.repository.CheckEmail(Arg.Is <Email>(email => email.ToString().Equals("*****@*****.**"))).Returns(true); this.repository.CheckEmail(Arg.Is <Email>(email => !email.ToString().Equals("*****@*****.**"))).Returns(false); this.repository.Delete(Arg.Any <Guid>()).Returns(true); this.repository.Delete(Arg.Is <Guid>(id => id.Equals(new Guid(this.notFoundUserId)))).Returns(false); }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); ModuleJSONObject moduleOutput; switch(command.Command) { case "me": moduleOutput = new ModuleJSONObject(); moduleOutput.broadcast = true; moduleOutput.message = user.Username + " " + command.Arguments[0]; //System.Security.SecurityElement.Escape(command.Arguments[0]); moduleOutput.tag = command.tag; outputs.Add(moduleOutput); break; case "emotes": moduleOutput = new ModuleJSONObject(); moduleOutput.message = "Emote list:\n"; try { string htmlCode; using (WebClient client = new WebClient()) { htmlCode = client.DownloadString(GetOption<string>("emoteLink")); } EmoteJSONObject emotes = JsonConvert.DeserializeObject<EmoteJSONObject>(htmlCode); foreach(string emote in emotes.mapping.Keys) moduleOutput.message += "\n" + emotes.format.Replace("emote", emote); } catch (Exception e) { moduleOutput.message = "Sorry, could not retrieve emote list!\nException: " + e.ToString(); } outputs.Add(moduleOutput); break; } return outputs; }
public UserCommand[] ReadUserCommands(NetDataReader reader, out int currentActiveTick) { lastReceivedPacketTime = DateTimeOffset.Now.ToUnixTimeMilliseconds(); int clientTick = reader.GetInt(); ClientAckedTick = reader.GetInt(); int activeTickMask = reader.GetByte(); currentActiveTick = ClientAckedTick - activeTickMask; // active tick, at the moment user command was generated if (lastReceivedTick >= clientTick) { return(null); } int tickGap = 1; // for first command tick gap is 1 if (lastReceivedTick != -1) { tickGap = clientTick - lastReceivedTick; } lastReceivedTick = clientTick; int commandCount = reader.GetByte(); int startIndexToProcede = commandCount - tickGap; UserCommand userCommand = new UserCommand(); UserCommand[] userCommands = new UserCommand[tickGap]; int index = 0; for (int i = 0; i < commandCount; i++) { userCommand.Deserialize(reader); if (i >= startIndexToProcede) { userCommands[index] = userCommand; index++; } } return(userCommands); }
public ActionResult PersonMonitor(int eventId, int userId) { var eventt = EventCommand.Get(eventId); var user = UserCommand.Get(userId); var seenInfo = AreYouOkCommand.GetSeenInfo(eventId, userId); if (seenInfo == null) { seenInfo = new SeenInfo(); } if (LoggedUserIs(RoleEnum.EventAdministrator) && eventt.Organizer.Id != GetLoggedUser().Id) { return(RedirectToAction("Monitor", "EventMonitor", new { id = eventId })); } var status = IAmOkEnum.WithoutAnswer; var statusRow = AreYouOkEvents.Where(x => x.Target == user && x.Event == eventt).FirstOrDefault(); if (statusRow?.ReplyDatetime != null) { status = statusRow.IAmOk ? IAmOkEnum.Ok : IAmOkEnum.NotOk; } var eventPersonMonitorModel = new EventPersonMonitorModel() { Username = user.Username, Image = user.Image, EventId = eventId, UserId = userId, EventLatitude = eventt.Latitude, EventLongitude = eventt.Longitude, EventName = eventt.Name, Status = status, Seen = seenInfo.Seen, SeenOk = seenInfo.SeenOk, SeenNotOk = seenInfo.SeenNotOk, SeenWithoutAnswer = seenInfo.SeenWithoutAnswer }; return(View(eventPersonMonitorModel)); }
public void UpdateUser(UserCommand updateCommand) { if (_taskContext.Users.Any(usr => usr.EmailAddress == updateCommand.EmailAddress && usr.UserId != updateCommand.UserId)) { throw new TaskException("User with specified email already exists."); } User user = _taskContext.Users.Find(updateCommand.UserId); user.Name = updateCommand.Name; user.EmailAddress = updateCommand.EmailAddress; // user.SetEntityUpdateDetails(updateCommand.UserId); // _taskContext.Save(); }
/// <summary> /// Add custom claims here /// </summary> /// <param name="user"></param> /// <returns></returns> private async Task AddClaims(TUser user, UserCommand command) { _logger.LogInformation("Begin include claims"); var claims = new List <Claim>(); _logger.LogInformation(command.ToJson()); if (command.Picture.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.Picture, command.Picture)); } if (command.Name.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.GivenName, command.Name)); } if (command.Birthdate.HasValue) { claims.Add(new Claim(JwtClaimTypes.BirthDate, command.Birthdate.Value.ToString(CultureInfo.CurrentCulture))); } if (command.SocialNumber.IsPresent()) { claims.Add(new Claim("social_number", command.SocialNumber)); } if (claims.Any()) { var result = await _userManager.AddClaimsAsync(user, claims); if (result.Succeeded) { _logger.LogInformation("Claim created successfull."); } else { foreach (var error in result.Errors) { await _bus.RaiseEvent(new DomainNotification(result.ToString(), error.Description)); } } } }
public override void HandleInput(UserCommand command) { if (sentConfirm && GameState.Miner != null) { if (command.CommandText.ToLower() == "yes") { confirmed = true; return; } if (command.CommandText.ToLower() == "no") { Game.PopScene(); } } persistenceService.LoadGame(GameState, command.FullCommand); StartGame(); }
public async Task <IActionResult> Register(UserCommand userDto) { //validate userDto.EmailAddress = userDto.EmailAddress.ToLower(); /* if(await _authService.UserExist(userDto.EmailAddress)) { * return BadRequest("user already exist"); * }*/ var userToCreate = new User { EmailAddress = userDto.EmailAddress, Name = userDto.Name }; var createdUser = await _authService.Register(userToCreate, userDto.Password); return(StatusCode(201)); }
static public Action GetCommandRequest(ref PredictedState predictedState, ref Settings settings, ref UserCommand command) { if (command.reload && predictedState.ammoInClip < settings.clipSize) { return(Action.Reload); } var isIdle = predictedState.action == Action.Idle; if (isIdle) { if (command.primaryFire && predictedState.ammoInClip == 0) { return(Action.Reload); } } return(command.primaryFire ? Action.Fire : Action.Idle); }
private void ReceiveUserCommand(NetIncomingMessage msg) { var client = GetClientInfo(msg); var commandCount = (int)msg.ReadByte(); for (var i = 0; i < commandCount; ++i) { UserCommand cmd = new UserCommand(); cmd.commandid = msg.ReadByte(); cmd.keystate = msg.ReadByte(); cmd.actionstate = msg.ReadByte(); cmd.client_time = msg.ReadFloat(); if (client.has_spawned) { client.cmd_queue.Enqueue(cmd); } } }
public static UserCommand GetCommand(string id = null, string firstName = null, string lastName = null, string email = null) { string defaultId = "id1"; string defaultFirstName = "User 1"; string defaultLastName = "User 1"; string defaultEmail = "*****@*****.**"; DateTime date = DateTime.Now; ICollection <string> roles = null; ICollection <string> groups = null; bool isEnabled = true; id = id ?? defaultId; firstName = firstName ?? defaultFirstName; lastName = lastName ?? defaultLastName; email = email ?? defaultEmail; UserCommand command = new UserCommand(id, date, firstName, lastName, email, roles, groups, isEnabled); return(command); }
public static State GetPreferredState(ref PredictedState predictedState, ref Settings settings, ref UserCommand command) { if (command.buttons.IsSet(settings.reloadButton) && predictedState.ammoInClip < settings.clipSize) { return(State.Reload); } var isIdle = predictedState.action == State.Idle; if (isIdle) { if (command.buttons.IsSet(settings.fireButton) && predictedState.ammoInClip == 0) { return(State.Reload); } } return(command.buttons.IsSet(settings.fireButton) ? State.Fire : State.Idle); }
public override void HandleInput(UserCommand command) { if (command.CommandText.ToLower() == "yes") { Game.SwitchScene(Scene.Create(new List <IGameEntity> { new CollectMinerNameEntity(GameState) })); GameState.PromptText = null; } if (command.CommandText.ToLower() == "no") { Game.SwitchScene(Scene.Create(new List <IGameEntity> { new LoadGameEntity(GameState, new GamePersistenceService()) })); GameState.PromptText = null; } }
public GraphScreen(AssemblyBrowserWindowViewModel windowViewModel) : base(windowViewModel) { PinCommand = new DelegateCommand(PinCommandHandler); HideSearchCommand = new DelegateCommand(HideSearchCommandHandler); ShowSearchCommand = new DelegateCommand(ShowSearchCommandHandler); _toggleColorizeUserCommand = new UserCommand(WindowViewModel.IsColorized ? Resources.Decolorize : Resources.Colorize, ToggleColorizeCommandHandler); Commands = new ObservableCollection <UserCommand> { new UserCommand(Resources.FillGraph, OnFillGraphRequest), new UserCommand(Resources.OriginalSize, OnOriginalSizeRequest), WindowViewModel.ShowSearchUserCommand, new UserCommand(Resources.SearchInGraph, ShowSearchCommand), _toggleColorizeUserCommand }; }
private static int GetActiveButtonIndex(UserCommand cmd, ref AbilityCollection.AbilityEntry abilityEntry) { if (cmd.buttons.IsSet(abilityEntry.ActivateButton0)) { return(0); } if (cmd.buttons.IsSet(abilityEntry.ActivateButton1)) { return(1); } if (cmd.buttons.IsSet(abilityEntry.ActivateButton2)) { return(2); } if (cmd.buttons.IsSet(abilityEntry.ActivateButton3)) { return(3); } return(-1); }
public AnimViewModel(GenericRCOLResource rcolResource) { IsSaving = false; mANIM = (ANIM) rcolResource.ChunkEntries.FirstOrDefault().RCOLBlock; CurrentFrameIndex = -1; SyncFrames(); CommitCommand = new UserCommand<AnimViewModel>(x => true, y => { IsSaving = true; Application.Current.Shutdown(); }); CancelCommand = new UserCommand<AnimViewModel>(x => true, y => { IsSaving = false; Application.Current.Shutdown(); }); RemoveFrameCommand = new UserCommand<AnimViewModel>(x => CurrentFrameIndex >= 0, RemoveFrame); AddFrameCommand = new UserCommand<AnimViewModel>(x => true, AddFrame); ShiftFrameUpCommand = new UserCommand<AnimViewModel>(x => x != null && x.CurrentFrameIndex > 0, ShiftFrameUp); ShiftFrameDownCommand = new UserCommand<AnimViewModel>(x => x != null && x.CurrentFrameIndex < x.Frames.Count - 1 && x.CurrentFrameIndex != -1, ShiftFrameDown); ImportCommand = new UserCommand<AnimViewModel>(x => x != null && x.GetSelectedFrame() != null, ImportDds); ExportCommand = new UserCommand<AnimViewModel>(x => x != null && x.GetSelectedFrame() != null && x.GetSelectedFrame().Frame.Stream.Length > 0, ExportDds); }
public FindReplaceDialog() { AcceptInputCommand = new UserCommand<FindReplaceDialog>(CanExecuteAcceptInput, ExecuteAcceptInput); InitializeComponent(); }
public bool EnsoureState(UserCommand action) { return _fsm.Instance(this.State).CanFire(action); }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); ModuleJSONObject output = new ModuleJSONObject(); switch (command.Command) { case "about": output = new ModuleJSONObject(); BandwidthContainer bandwidth = ChatRunner.Bandwidth; //Chat.GetBandwidth(); DateTime built = ChatRunner.MyBuildDate(); DateTime crashed = ChatRunner.LastCrash(); string crashedString = "never"; if (crashed.Ticks > 0) crashedString = StringExtensions.LargestTime(DateTime.Now - crashed) + " ago"; output.message = "---Build info---\n" + "Version: " + ChatRunner.AssemblyVersion() + "\n" + "Runtime: " + StringExtensions.LargestTime(DateTime.Now - ChatRunner.Startup) + "\n" + "Built " + StringExtensions.LargestTime(DateTime.Now - built) + " ago (" + built.ToString("R") + ")\n" + "---Data usage---\n" + "Outgoing: " + bandwidth.GetTotalBandwidthOutgoing() + " (1h: " + bandwidth.GetHourBandwidthOutgoing() + ")\n" + "Incoming: " + bandwidth.GetTotalBandwidthIncoming() + " (1h: " + bandwidth.GetHourBandwidthIncoming() + ")\n" + "---Websocket---\n" + "Library Version: " + WebSocketServer.Version + "\n" + "Last full crash: " + crashedString; outputs.Add(output); break; case "policy": output = new ModuleJSONObject(ChatServer.Policy); outputs.Add(output); break; case "help": output = new ModuleJSONObject(); if (command.Arguments.Count == 0) { output.message = "Which module would you like help with?\n"; foreach (Module module in ChatRunner.Server.GetModuleListCopy(user.UID)) output.message += "\n" + module.Nickname; output.message += "\n\nRerun help command with a module name to see commands for that module"; outputs.Add(output); } else { output.message = GetModuleHelp(command.Arguments[0], user); outputs.Add(output); } break; case "helpregex": output.message = GetModuleHelp(command.Arguments[0], user, true); outputs.Add(output); break; case "uactest": output = new ModuleJSONObject(); output.message = "User " + command.OriginalArguments[0] + " corrects to " + command.Arguments[0]; outputs.Add(output); break; } return outputs; }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { string output = ""; UserInfo parsedUser = null; if (command.Command == "showhiding") { if (!user.ChatControlExtended) return FastMessage("This command doesn't *AHEM* exist"); output = "Users that are hiding:\n" + String.Join("\n", GetHidingUsers(users).Select(x => x.Username)); return FastMessage(output); } else if (command.Command == "expose") { if (!user.ChatControlExtended) return FastMessage("This command doesn't *AHEM* exist"); //This should eventually use AddError instead. if(!GetUserFromArgument(command.Arguments[0], users, out parsedUser)) return FastMessage("Something weird happened in the backend during user parse!", true); else if (!GetHidingUsers(users).Any(x => x.UID == parsedUser.UID)) return FastMessage(parsedUser.Username + " isn't hiding!", true); SneakyModule.UnhideUser(parsedUser.UID); return FastMessage("You forced " + parsedUser.Username + " out of hiding!"); } return new List<JSONObject>(); }
private void CmdButtons(ref UserCommand cmd) { // // figure button bits // send a button bit even if the key was pressed and released in // less than a frame // for (int i = 0; i < 15; i++) { if (in_buttons[i].active || in_buttons[i].wasPressed) cmd.buttons |= 1 << i; //if (i == 1) Common.Instance.WriteLine(in_buttons[1].wasPressed + ""); in_buttons[i].wasPressed = false; } }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); ModuleJSONObject moduleOutput = new ModuleJSONObject(); VoteBallot ballot; string error = ""; string output = ""; long pollNumber = 0; if (!userBallots.ContainsKey(user.UID)) userBallots.Add(user.UID, new List<VoteBallot>()); try { switch(command.Command) { case "pollcreate": int maxPolls = MaxUserPolls * (user.CanStaffChat ? 5 : 1); if (userBallots[user.UID].Count >= maxPolls) return FastMessage("You've reached the maximum amount of allowed polls (" + maxPolls + ") and cannot post a new one", true); else if (command.ArgumentParts[1].Count > MaxPollChoices) return FastMessage("There are too many choices in your poll! The max is " + MaxPollChoices, true); VoteBallot newBallot = new VoteBallot(command.Arguments[0], new HashSet<string>(command.ArgumentParts[1])); if (newBallot.GetChoices().Count < 2) return FastMessage("Your poll must have at least 2 options", true); userBallots[user.UID].Add(newBallot); moduleOutput.broadcast = true; moduleOutput.message = "A new poll has been created by " + user.Username + ":\n\n" + userBallots[user.UID].Last(); outputs.Add(moduleOutput); break; case "vote": if(!long.TryParse(command.Arguments[1], out pollNumber)) return FastMessage("Your poll number is out of bounds!", true); if(!GetBallot(pollNumber, false, out ballot)) { return FastMessage("There is no open poll with ID " + pollNumber); } else { if(!ballot.AddVote(user.UID, command.Arguments[0], out error)) return FastMessage(error); else return FastMessage("You voted on this poll: \n\n" + ballot.GetResultString(user.UID)); } case "polls": output = "The top polls right now: \n"; output += PrintList(userBallots.SelectMany(x => x.Value).OrderByDescending(x => x.TotalVotes).Take(10)); return FastMessage(output); case "poll": if(!long.TryParse(command.Arguments[0], out pollNumber)) return FastMessage("Your poll number is out of bounds!", true); if(!GetBallot(pollNumber, true, out ballot)) { return FastMessage("There is no open poll with ID " + pollNumber); } else { output = ""; bool closed = archivedBallots.SelectMany(x => x.Value).Contains(ballot); if(ballot.DidVote(user.UID) || closed) output = ballot.GetResultString(user.UID); else output = ballot.ToString(); int ballotCreator = userBallots.Union(archivedBallots).First(x => x.Value.Contains(ballot)).Key; output += "\nPoll by: " + users[ballotCreator].Username + (closed ? " (closed)" : ""); return FastMessage(output); } case "pollclose": if(!long.TryParse(command.Arguments[0], out pollNumber)) return FastMessage("Your poll number is out of bounds!", true); if(!userBallots[user.UID].Any(x => x.ID == pollNumber)) return FastMessage("You don't have any open polls with this ID!"); if(!GetBallot(pollNumber, false, out ballot)) { return FastMessage("There is no open poll with ID " + pollNumber); } else { if(!archivedBallots.ContainsKey(user.UID)) archivedBallots.Add(user.UID, new List<VoteBallot>()); archivedBallots[user.UID].Add(ballot); userBallots[user.UID].Remove(ballot); moduleOutput.broadcast = true; moduleOutput.message = "The poll " + ballot.Title + " has just been closed by " + user.Username + ". The results:\n\n" + ballot.GetResultString(); outputs.Add(moduleOutput); } break; case "pollsearch": List<Tuple<double, VoteBallot>> sortedBallots = new List<Tuple<double, VoteBallot>>(); foreach(VoteBallot searchBallot in userBallots.SelectMany(x => x.Value).Union(archivedBallots.SelectMany(x => x.Value))) sortedBallots.Add(Tuple.Create(StringExtensions.StringDifference(command.Arguments[0].ToLower(), searchBallot.Title.ToLower()), searchBallot)); output = "These ballots have a similar title: \n"; output += PrintList(sortedBallots.OrderBy(x => x.Item1).Select(x => x.Item2).Take(SearchResults)); return FastMessage(output); case "pollsopen": output = "Your open polls right now are: \n" + PrintList(userBallots[user.UID]); return FastMessage(output); } } catch(Exception e) { return new List<JSONObject>() { new ModuleJSONObject() { message = "Something terrible happened in the Vote module: " + e, broadcast = true } }; } return outputs; }
void MouseMove(ref UserCommand cmd) { Client.Instance.cl.viewAngles[1] -= mousedx * Client.Instance.sensitivity.Value * 0.01f; Client.Instance.cl.viewAngles[0] += mousedy * Client.Instance.sensitivity.Value * 0.01f; }
/// <summary> /// Parse and build command if possible. Assign module which will handle command. /// </summary> /// <returns>Successful command parse</returns> /// <param name="message">Message.</param> /// <param name="commandModule">Command module.</param> /// <param name="userCommand">User command.</param> private bool TryCommandParse(UserMessageJSONObject message, out Module commandModule, out UserCommand userCommand, out string error) { userCommand = null; commandModule = null; error = ""; UserCommand tempUserCommand = null; List<Module> modules = manager.GetModuleListCopy(UID); string realMessage = System.Net.WebUtility.HtmlDecode(message.message); //Check through all modules for possible command match foreach(Module module in modules) { //We already found the module, so get out. if(commandModule != null) break; //Check through this module's command for possible match foreach(ModuleCommand command in module.Commands) { Match match = Regex.Match(realMessage, command.FullRegex, RegexOptions.Singleline); //Match partialMatch = Regex.Match(message.message, command.CommandRegex, RegexOptions.Singleline); //This command matched, so preparse the command and get out of here. if (match.Success) { //Build arguments from regex. List<string> arguments = new List<string>(); for (int i = 2; i < match.Groups.Count; i++) arguments.Add(match.Groups[i].Value.Trim()); //We have a user command. Cool, but will it parse? Ehhhh. tempUserCommand = new UserCommand(match.Groups[1].Value, arguments, message, command); //Now preprocess the command to make sure certain standard fields check out (like username) for (int i = 0; i < command.Arguments.Count; i++) { //Users need to exist. If not, throw error. if (command.Arguments[i].Type == ArgumentType.User) { tempUserCommand.Arguments[i] = ParseUser(tempUserCommand.Arguments[i]); for (int j = 0; j < tempUserCommand.ArgumentParts[i].Count; j++) tempUserCommand.ArgumentParts[i][j] = ParseUser(tempUserCommand.ArgumentParts[i][j]); if (!((tempUserCommand.MatchedCommand.Arguments[i].Repeat == RepeatType.ZeroOrOne || tempUserCommand.MatchedCommand.Arguments[i].Repeat == RepeatType.ZeroOrMore) && string.IsNullOrWhiteSpace(tempUserCommand.Arguments[i])) && (tempUserCommand.ArgumentParts[i].Count == 0 && manager.UserLookup(tempUserCommand.Arguments[i]) < 0 || tempUserCommand.ArgumentParts[i].Any(x => manager.UserLookup(x) < 0))) { error = "User does not exist"; return false; } } else if (command.Arguments[i].Type == ArgumentType.Module) { if (!modules.Any(x => x.Nickname == arguments[i].ToLower())) { error = "Module does not exist"; return false; } } } commandModule = module; break; } } } if (commandModule == null && ModuleCommand.IsACommand(message.message)) { //OOPS! A command was parsed but it wasn't parsed correctly. Doop error = "\"" + message.message + "\" was not recognized. Maybe something was misspelled, or you were missing arguments"; return false; } userCommand = new UserCommand(tempUserCommand); return (commandModule != null); }
private void ProcessCommand(UserCommand command) { switch (command) { case UserCommand.Show: this.ProcessShowCommand(); break; case UserCommand.Exit: this.ProcessExitCommand(); break; case UserCommand.New: this.ProcessNewGame(); break; case UserCommand.Shoot: this.shotPosition = this.userInterface.GetShotPositionFromInput(); this.ProcessShootCommand(); break; case UserCommand.Invalid: default: throw new InvalidOperationException(GlobalConstants.InvalidCommandMsg); } }
private void ExecuteUserCommand(UserCommand command) { UserCommandExecutorDelegate userCommandExecutor; if (this.userActionsList.TryGetValue(command, out userCommandExecutor)) { userCommandExecutor(); } else { string invalidCommandMessage = string.Format("The commant '{0}' is invalid.", command.ToString()); throw new InvalidCommandException(invalidCommandMessage); } }
public override List<ChatEssentials.JSONObject> ProcessCommand(UserCommand command, ChatEssentials.UserInfo user, Dictionary<int, ChatEssentials.UserInfo> users) { #region oneTimeProcess if(!oneTimeRun) { oneTimeRun = true; //Cheating = ExplorerConstants.Simulation.FruitGrowthHours = GetOption<double>("fruitHours"); ExplorerConstants.Simulation.TreeGrowthHours = GetOption<double>("treeHours"); ExplorerConstants.Simulation.StoneGrowthHours = GetOption<double>("stoneHours"); ExplorerConstants.Simulation.SuperFruitGrowthHours = GetOption<double>("superFruitHours"); ExplorerConstants.Items.TorchSteps = GetOption<int>("torchSteps"); ExplorerConstants.Probability.CaveChance = GetOption<double>("caveChance"); ExplorerConstants.Player.HourlyStaminaRegain = GetOption<int>("hourlyStamina"); //ExplorerConstants.Player.FruitFullnessIncrease = GetOption<double>("fullnessIncrease"); ExplorerConstants.Player.FruitPerFullness = GetOption<double>("fruitPerFullness"); ExplorerConstants.Player.FullnessDecayMinutes = GetOption<double>("fullnessDecayMinutes"); ExplorerConstants.Items.ExtraFruitPerMagicStone = GetOption<double>("extraFruitPerMagicStone"); string temp = GetOption<string>("player"); if (temp.Length > 0) ExplorerConstants.Player.CurrentPlayerToken = temp[0]; if (GetOption<bool>("cheating")) Commands.Add(new ModuleCommand("excheat", new List<CommandArgument>(), "Get a crapload of resources")); } #endregion #region fromPostProcess if (worlds.Count == 0) { GenerateWorld(); } foreach (WorldInstance world in worlds) world.RefreshFullness((DateTime.Now - lastCommand).TotalMinutes / ExplorerConstants.Player.FullnessDecayMinutes); lastCommand = DateTime.Now; if ((DateTime.Now - lastRefresh).TotalHours >= 1.0 / ExplorerConstants.Player.HourlyStaminaRegain) { foreach (WorldInstance world in worlds) world.RefreshStamina((int)Math.Ceiling((DateTime.Now - lastRefresh).TotalHours * ExplorerConstants.Player.HourlyStaminaRegain)); lastRefresh = DateTime.Now; } foreach (WorldInstance world in worlds) world.SimulateTime(); #endregion Match match; Tuple<WorldInstance, string> results; TryRegister(user.UID); try { if(command.Command == "exmastertest") { if(!user.ChatControlExtended) return FastMessage("You don't have access to this command", true); int worldType; if (!int.TryParse(command.Arguments[0], out worldType)) worldType = 0; World world = new World(); world.Generate(worldType % ExplorerConstants.Generation.PresetBases.Count); world.GetFullMapImage(false).Save(StringExtensions.PathFixer(GetOption<string>("mapFolder")) + "test" + worldType + ".png"); return FastMessage("Test " + worldType + " map: " + GetOption<string>("mapLink") + "/test" + worldType + ".png"); } if(command.Command == "exmasterflagscatter") { if(!user.ChatControlExtended) return FastMessage("You don't have access to this command", true); int amount, world; if (!int.TryParse(command.Arguments[0], out amount) || amount > 10000) return FastMessage("You can't spawn that many flags!"); if (!int.TryParse(command.Arguments[1], out world) || !worlds.Any(x => x.Operating && x.WorldID == world)) return FastMessage("The world you gave was invalid!"); int actualCount = worlds.First(x => x.Operating && x.WorldID == world).WorldData.ScatterFlags(amount); ModuleJSONObject broadcast = new ModuleJSONObject("Hey, " + user.Username + " has just spawned " + actualCount + " flags in exgame world " + world + "!"); broadcast.broadcast = true; return new List<JSONObject>{ broadcast }; } #region mastergenerate //match = Regex.Match(chunk.Message, @"^\s*/exmastergenerate\s*([0-9]+)?\s*$"); if (command.Command == "exmastergenerate") { if(!user.ChatControlExtended) return FastMessage("You don't have access to this command", true); int givenCode; if (!int.TryParse(command.Arguments[0], out givenCode)) givenCode = 0; if (generateCode == -1) { generateCode = (int)(DateTime.Now.Ticks % 10000); return FastMessage("If you wish to generate a new world, type in the same command with this code: " + generateCode); } else { if (generateCode != givenCode) { generateCode = -1; return FastMessage("That was the wrong code. Code has been reset", true); } GenerateWorld(); generateCode = -1; return FastMessage("You've generated a new world!"); } } #endregion #region masterclose //match = Regex.Match(chunk.Message, @"^\s*/exmasterclose\s+([0-9]+)\s*([0-9]+)?\s*$"); if (command.Command == "exmasterclose")//match.Success) { // if (chunk.Username != Module.AllControlUsername) // return chunk.Username + ", you don't have access to this command"; if(!user.ChatControlExtended) return FastMessage("You don't have access to this command", true); int givenCode, givenWorld; if (!int.TryParse(command.Arguments[0], out givenWorld) || !worlds.Any(x => x.Operating && x.WorldID == givenWorld)) return FastMessage("The world you gave was invalid!", true); if (!int.TryParse(command.Arguments[1], out givenCode)) givenCode = 0; if (closeCode == -1) { closeCode = (int)(DateTime.Now.Ticks % 10000); closeWorld = givenWorld; return FastMessage("If you wish to close world " + closeWorld + " , type in the same command with this code: " + closeCode); } else { if (closeCode != givenCode || closeWorld != givenWorld) { closeCode = -1; closeWorld = -1; return FastMessage("That was the wrong code or world. Code has been reset", true); } string output = "You've closed world " + closeWorld; bool warning = false; WorldInstance world = worlds.FirstOrDefault(x => x.WorldID == closeWorld); if (world == null) { output = "Something went wrong. No worlds have been closed"; warning = true; } else { world.CloseWorld(); } closeWorld = -1; closeCode = -1; return FastMessage(output, warning); } } #endregion #region worldlist if (command.Command == "exworldlist")//Regex.IsMatch(chunk.Message, @"^\s*/exworldlist\s*$")) { string output = "List of all worlds:\n-------------------------------------"; foreach (WorldInstance world in worlds) { if (world.CanPlay) output += "\n-World " + world.WorldID + " * " + world.GetOwnedAcres().Count + " acre".Pluralify(world.GetOwnedAcres().Count); } return StyledMessage(output); } #endregion #region setworld //match = Regex.Match(chunk.Message, @"^\s*/exsetworld\s+([0-9]+)\s*$"); if (command.Command == "exsetworld")//match.Success) { int setWorld; if (!int.TryParse(command.Arguments[0], out setWorld)) return FastMessage("This is an invalid world selection", true); else if (!worlds.Any(x => x.WorldID == setWorld)) return FastMessage("There are no worlds with this ID", true); else if (allPlayers[user.UID].PlayingWorld == setWorld) return FastMessage("You're already playing on this world", true); WorldInstance world = worlds.FirstOrDefault(x => x.WorldID == setWorld); if (!world.CanPlay) return FastMessage("This world is unplayable", true); allPlayers[user.UID].PlayingWorld = setWorld; if (world.StartGame(user.UID, user.Username)) return FastMessage("You've entered World " + setWorld + " for the first time!"); else return FastMessage("You've switched over to World " + setWorld); } #endregion #region toggle match = Regex.Match(command.Command, @"extoggle([^\s]+)"); if (match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return FastMessage(results.Item1.ToggleOption(user.UID, match.Groups[1].Value)); } #endregion #region go //match = Regex.Match(chunk.Message, @"^\s*/exgo\s*(.*)\s*$"); if (command.Command == "exgo")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); int chatCoinGet = 0; string output = results.Item1.PerformActions(user.UID, command.Arguments[0]/*match.Groups[1].Value*/, out chatCoinGet); // // if (chatCoinGet > 0) // StandardCalls_RequestCoinUpdate(chatCoinGet, chunk.Username); return StyledMessage(output); } #endregion #region cheat if (command.Command == "excheat")//Regex.IsMatch(chunk.Message, @"^\s*/excheat\s*$") && Cheating) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); results.Item1.Cheat(user.UID); return FastMessage("You cheated some resources into existence!"); } #endregion #region itemlist if (command.Command == "exitemlist")//Regex.IsMatch(chunk.Message, @"^\s*/exitemlist\s*$")) { string output = ""; foreach (ItemBlueprint item in ExplorerConstants.Items.AllBlueprints .Where(x => x.Key != ExplorerConstants.Items.IDS.ChatCoins).Select(x => x.Value) .Where(x => x.CanPickup && x.CanObtain || ExplorerConstants.Items.CraftingRecipes.ContainsKey(x.ID))) { output += item.ShorthandName + " (" + item.DisplayCharacter + ") - " + item.DisplayName + "\n"; } return StyledMessage(output); } #endregion #region equip //match = Regex.Match(chunk.Message, @"^\s*/exequip\s+([a-zA-Z]+)\s*$"); if (command.Command == "exequip")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return FastMessage(results.Item1.EquipItem(user.UID, command.Arguments[0].Trim()));//match.Groups[1].Value.Trim()); } #endregion #region craft //match = Regex.Match(chunk.Message, @"^\s*/excraft\s+([^0-9]+)\s*([0-9]*)\s*$"); if (command.Command == "excraft")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); int amount; if (!int.TryParse(/*match.Groups[2].Value*/command.Arguments[1], out amount)) amount = 1; return FastMessage(results.Item1.CraftItem(user.UID, command.Arguments[0].Trim()/*match.Groups[1].Value.Trim()*/, amount)); } #endregion #region craftlist if (command.Command == "excraftlist")//Regex.IsMatch(chunk.Message, @"^\s*/excraftlist\s*$")) { string output = ""; foreach (var craftRecipe in ExplorerConstants.Items.CraftingRecipes.OrderBy(x => x.Value.Values.Sum())) { output += ExplorerConstants.Items.AllBlueprints[craftRecipe.Key].ShorthandName + " - "; foreach (var craftIngredient in craftRecipe.Value) { output += ExplorerConstants.Items.AllBlueprints[craftIngredient.Key].ShorthandName + "*" + craftIngredient.Value + " "; } output += "\n"; } return StyledMessage(output); } #endregion #region map //match = Regex.Match(chunk.Message, @"^\s*/exmap\s+([0-9]+)\s*$"); if (command.Command == "exmap")//match.Success) { //return FastMessage("Not supported right now!", true); int worldID; if (!int.TryParse(command.Arguments[0], out worldID)) return FastMessage("That's not a valid number", true); if (!worlds.Any(x => x.WorldID == worldID)) return FastMessage("There's no world with this ID", true); try { SaveWorldImage(worlds.FirstOrDefault(x => x.WorldID == worldID)); } catch (Exception e) { return FastMessage("An error occurred while generating the map image! Please report this error to an admin." + "\nError: " + e, true); } return FastMessage("World " + worldID + " map: " + GetOption<string>("mapLink") + "/world" + worldID + ".png"); } #endregion #region top if (command.Command == "extop")//Regex.IsMatch(chunk.Message, @"^\s*/extop\s*$")) { List<string> scores = SortedModuleItems(users); //List<Tuple<string, int>> scores = allPlayers.Select(x => Tuple.Create(x.Key, worlds.Sum(y => y.GetScore(x.Key)))).ToList(); string output = "The top explorers are:"; for (int i = 0; i < 5; i++) if (i < scores.Count()) output += "\n" + (i + 1) + ": " + scores[i]; return FastMessage(output); } #endregion #region close if (command.Command == "exclose")//Regex.IsMatch(chunk.Message, @"^\s*/exclose\s*$")) { List<string> scores = SortedModuleItems(users); //List<Tuple<string, int>> scores = allPlayers.Select(x => Tuple.Create(x.Key, worlds.Sum(y => y.GetScore(x.Key)))).ToList(); int index = scores.FindIndex(x => x.Contains(user.Username + " ")); string output = "Your exploration competitors are:"; for (int i = index - 2; i <= index + 2; i++) if (i < scores.Count() && i >= 0) output += "\n" + (i + 1) + ": " + scores[i]; return FastMessage(output); } #endregion #region respawn if (command.Command == "exrespawn")//Regex.IsMatch(chunk.Message, @"^\s*/exrespawn\s*$")) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return StyledMessage(results.Item1.Respawn(user.UID)); } #endregion #region myacres if (command.Command == "exmyacres")//Regex.IsMatch(chunk.Message, @"^\s*/exmyacres\s*$")) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return FastMessage(results.Item1.PlayerAcres(user.UID)); } #endregion #region items if (command.Command == "exitems")//Regex.IsMatch(chunk.Message, @"^\s*/exitems\s*$")) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return StyledMessage(results.Item1.PlayerItems(user.UID)); } #endregion #region storage if (command.Command == "exstorage")//Regex.IsMatch(chunk.Message, @"^\s*/exitems\s*$")) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); return StyledMessage(results.Item1.PlayerStorage(user.UID)); } #endregion #region store //match = Regex.Match(chunk.Message, @"^\s*/excraft\s+([^0-9]+)\s*([0-9]*)\s*$"); if (command.Command == "exstore")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); int amount; if (!int.TryParse(/*match.Groups[2].Value*/command.Arguments[1], out amount)) amount = int.MaxValue; return FastMessage(results.Item1.StoreItems(user.UID, command.Arguments[0].Trim()/*match.Groups[1].Value.Trim()*/, amount)); } #endregion #region store //match = Regex.Match(chunk.Message, @"^\s*/excraft\s+([^0-9]+)\s*([0-9]*)\s*$"); if (command.Command == "extake")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); int amount; if (!int.TryParse(/*match.Groups[2].Value*/command.Arguments[1], out amount)) amount = int.MaxValue; return FastMessage(results.Item1.TakeItems(user.UID, command.Arguments[0].Trim()/*match.Groups[1].Value.Trim()*/, amount)); } #endregion #region teleport //match = Regex.Match(chunk.Message, @"^\s*/exteleport\s+([0-9]+)\s*-\s*([0-9]+)\s*$"); if (command.Command == "exteleport")//match.Success) { if (!WorldCommandCheck(user.UID, out results)) return FastMessage(results.Item2, true); int x, y; if (!int.TryParse(command.Arguments[0], out x) || !int.TryParse(command.Arguments[1], out y)) return FastMessage("Your acre was formatted incorrectly!", true); return StyledMessage(results.Item1.TeleportToTower(user.UID, Tuple.Create(x, y))); } #endregion } catch (Exception e) { return FastMessage("An exception occurred: " + e.Message + ". Please report to an admin\n" + "Stack trace: \n" + e.StackTrace, true); } return new List<JSONObject>(); }
//THIS is the function you're looking for. When the chat server detects a command for your module, it passes it along //to this function. You can process the command here, then send the output as the return object. Notice that the return //is a list; you can return multiple messages per command. This function is called ONCE for each command detected. //"user" is the user who performed the command; the class UserInfo contains a lot of information about a user, so //use it as needed. The provided dictionary is a list of ALL users ever seen by the chat, so it's like the chat server's //database. Each UserInfo object has a "LoggedIn" field, so you can tell if they're logged in or not. "command" has //two important fields: "Command" and "Arguments". Command is simply the string containing just the command performed, //and Arguments is a list (array) of the arguments, each as a string. The returned messages are in a JSON format, which //is masked by the JSONObject class. You will almost ALWAYS be returning one or more ModuleJSONObjects, which is a //chat server message specific to modules. You can also return system messages, etc. All the X_JSONObjects classes like //ModuleJSONObject derive from the JSONObject class, so you can return any of them. The "message" field of the //ModuleJSONObject holds the output, and you can change the recipient by adding users (as integers) to the "recipients" //field. If you do not specify any recipients, it defaults to the sender (this is usually what you want). If you //want to broadcast a message to everyone (please don't do this for every command), you can set the "broadcast" field //to true. public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { //This is what we're returning from our function List<JSONObject> outputs = new List<JSONObject>(); //Our commands (and probably yours too) usually returns just one message, so that's what this is. //It gets added to the above "outputs" list. ModuleJSONObject moduleOutput = new ModuleJSONObject(); List<UserStatistics> allStats = userStatistics.Select(x => x.Value).ToList(); //Run different code depending on the command (duh) switch(command.Command) { case "mystatistics": //Always use the UID, NOT the username to identifiy users. Usernames can change. if (!userStatistics.ContainsKey(user.UID)) { //Here, we're setting the message that will be displayed for this chat message object. moduleOutput.message = "You have no statistics yet. You will after this message!"; } else { moduleOutput.message = GetUserStats(user); } //We add just the one output to our list of outputs (we only want to output one thing) outputs.Add(moduleOutput); break; case "statistics": if (command.Arguments.Count == 0) { moduleOutput.message = "---Global Chat Statistics---\n"; moduleOutput.message += "Total messages: " + allStats.Sum(x => x.TotalMessages) + "\n"; moduleOutput.message += "Average message size: " + (allStats.Count == 0 ? 0 : (int)(allStats.Sum(x => x.AverageMessageLength) / allStats.Count)) + " characters\n"; moduleOutput.message += "Total users seen: " + allStats.Count + "\n"; moduleOutput.message += "Total user chat time: " + StringExtensions.LargestTime(new TimeSpan(users.Sum(x => x.Value.TotalChatTime.Ticks))) + "\n"; moduleOutput.message += "Average session time: " + (users.Count == 0 ? "error" : StringExtensions.LargestTime(new TimeSpan(users.Sum(x => x.Value.AverageSessionTime.Ticks) / users.Count))) + "\n"; outputs.Add(moduleOutput); } else { //THIS IS IMPORTANT! Arguments containing a user will be given to you as a USERNAME! However, you want //to store their information based on their UID. This function "GetUserFromArgument()" will search through //the given dictionary to find you the user with the given username. It should always succeed, and puts the //result in the "out" parameter. You probably don't need to check the return of GetUserFromArgument like I //do, but just to be save, if it fails, you can just fail with a generic error. AddError adds a generic //module error to the given list of outputs, then you can return outputs and it'll contain that error. UserInfo findUser; if (!GetUserFromArgument(command.Arguments[0], users, out findUser)) { AddError(outputs); break; } moduleOutput.message = GetUserStats(findUser); outputs.Add(moduleOutput); } break; } return outputs; }
private void FinishMove(ref UserCommand cmd) { // copy the state that the cgame is currently sending cmd.weapon = (byte)Client.Instance.cl.cgameUserCmdValue; // send the current server time so the amount of movement // can be determined without allowing cheating cmd.serverTime = Client.Instance.cl.serverTime; cmd.anglex = ((int)(Client.Instance.cl.viewAngles[0] * 65536 / 360) & 65535); cmd.angley = ((int)(Client.Instance.cl.viewAngles[1] * 65536 / 360) & 65535); cmd.anglez = ((int)(Client.Instance.cl.viewAngles[2] * 65536 / 360) & 65535); cmd.DX = mousedx; cmd.DY = mousedy; }
public UserCommand CreateCmd() { Vector3 oldAngles = Client.Instance.cl.viewAngles; UserCommand cmd = new UserCommand(); CmdButtons(ref cmd); KeyMove(ref cmd); MouseMove(ref cmd); // check to make sure the angles haven't wrapped if (Client.Instance.cl.viewAngles[0] - oldAngles[0] > 90) { Client.Instance.cl.viewAngles[0] = oldAngles[0] + 90; } else if (oldAngles[0] - Client.Instance.cl.viewAngles[0] > 90) { Client.Instance.cl.viewAngles[0] = oldAngles[0] - 90; } FinishMove(ref cmd); UserCmd = cmd; return cmd; }
public void WritePacket() { if (Client.Instance.state == ConnectState.CINEMATIC) return; NetBuffer buffer = new NetBuffer(); // write the current serverId so the server // can tell if this is from the current gameState buffer.Write(Client.Instance.cl.serverId); // write the last message we received, which can // be used for delta compression, and is also used // to tell if we dropped a gamestate buffer.Write(Client.Instance.clc.serverMessageSequence); // write the last reliable message we received buffer.Write(Client.Instance.clc.serverCommandSequence); // write any unacknowledged clientCommands for (int i = Client.Instance.clc.reliableAcknowledge + 1; i <= Client.Instance.clc.reliableSequence; i++) { buffer.Write((byte)clc_ops_e.clc_clientCommand); buffer.Write(i); buffer.Write(Client.Instance.clc.reliableCommands[i & 63]); } // we want to send all the usercmds that were generated in the last // few packet, so even if a couple packets are dropped in a row, // all the cmds will make it to the server if (Client.Instance.cl_packetdup.Integer < 0) CVars.Instance.Set("cl_cmdbackup", "0"); else if (Client.Instance.cl_packetdup.Integer > 5) CVars.Instance.Set("cl_cmdbackup", "5"); int oldPacketNum = (Client.Instance.clc.netchan.outgoingSequence - 1 - Client.Instance.cl_packetdup.Integer) & 31; int count = Client.Instance.cl.cmdNumber - Client.Instance.cl.outPackets[oldPacketNum].p_cmdNumber; if (count > 32) { count = 32; Common.Instance.WriteLine("MAX_PACKET_USERCMDS"); } int oldcmd = -1; if (count >= 1) { // begin a client move command if (!Client.Instance.cl.snap.valid || Client.Instance.clc.serverMessageSequence != Client.Instance.cl.snap.messageNum || Client.Instance.cl_nodelta.Integer > 0) { buffer.Write((byte)clc_ops_e.clc_moveNoDelta); } else buffer.Write((byte)clc_ops_e.clc_move); // write the command count buffer.Write((byte)count); // write all the commands, including the predicted command UserCommand newcmd = new UserCommand(); for (int i = 0; i < count; i++) { int j = (Client.Instance.cl.cmdNumber - count + i +1) & 63; if(i == 0) WriteDeltaUsercmdKey(buffer, ref newcmd, ref Client.Instance.cl.cmds[j]); else WriteDeltaUsercmdKey(buffer, ref Client.Instance.cl.cmds[oldcmd], ref Client.Instance.cl.cmds[j]); oldcmd = j; } } // // deliver the message // int packetNum = Client.Instance.clc.netchan.outgoingSequence & 31; Client.Instance.cl.outPackets[packetNum].p_realtime = (int)Client.Instance.realtime; Client.Instance.cl.outPackets[packetNum].p_serverTime = ((oldcmd == -1) ? 0 : Client.Instance.cl.cmds[oldcmd].serverTime); Client.Instance.cl.outPackets[packetNum].p_cmdNumber = Client.Instance.cl.cmdNumber; Client.Instance.clc.lastPacketSentTime = (int)Client.Instance.realtime; // Bam, send... Client.Instance.NetChan_Transmit(Client.Instance.clc.netchan, buffer); }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); ModuleJSONObject moduleOutput = new ModuleJSONObject(); string message = ""; UserInfo parsedInfo; try { switch(command.Command) { case "spamscore": moduleOutput.message = "Your spam score is: " + user.SpamScore + ", offense score: " + user.GlobalSpamScore; outputs.Add(moduleOutput); break; case "resetserver": int timeout = 5; //Get the real timeout if one was given if (command.Arguments.Count > 0 && !string.IsNullOrWhiteSpace(command.Arguments[0])) timeout = int.Parse(command.Arguments[0]); TimeSpan realTimeout = TimeSpan.FromSeconds(timeout); //Make sure the user can even run such a high command if(!user.ChatControl) return FastMessage("You don't have access to this command!", true); //Request the reset we wanted ChatRunner.PerformRequest(new SystemRequest(SystemRequests.Reset, realTimeout)); moduleOutput.message = user.Username + " is resetting the server in " + StringExtensions.LargestTime(realTimeout); moduleOutput.broadcast = true; outputs.Add(moduleOutput); break; case "simulatelock": //Make sure the user can even run such a high command if(!user.ChatControlExtended) return FastMessage("You don't have access to this command!", true); //Request the lock we wanted ChatRunner.PerformRequest(new SystemRequest(SystemRequests.LockDeath, TimeSpan.FromSeconds(5))); moduleOutput.message = user.Username + " is simulating a server crash. The server WILL be unresponsive if successful"; moduleOutput.broadcast = true; outputs.Add(moduleOutput); break; case "savemodules": //Make sure the user can even run such a high command if(!user.ChatControlExtended) return FastMessage("You don't have access to this command!", true); ChatRunner.PerformRequest(new SystemRequest(SystemRequests.SaveModules)); moduleOutput.message = user.Username + " is saving all module data. This may cause a small hiccup"; moduleOutput.broadcast = true; outputs.Add(moduleOutput); break; case "checkserver": //Make sure the user can even run such a high command if(!user.ChatControl) return FastMessage("You don't have access to this command!", true); message = "Information about the chat server:\n\n"; Dictionary<string, List<UserMessageJSONObject>> history = ChatRunner.Server.GetHistory(); List<UserMessageJSONObject> messages = ChatRunner.Server.GetMessages(); List<LogMessage> logMessages = ChatRunner.Server.Settings.LogProvider.GetMessages(); List<LogMessage> logFileBuffer = ChatRunner.Server.Settings.LogProvider.GetFileBuffer(); List<Module> modules = ChatRunner.Server.GetModuleListCopy(); message += "Rooms: " + history.Keys.Count + "\n"; message += "History messages: " + history.Sum(x => x.Value.Count) + "\n"; message += "Registered users: " + users.Count + "\n"; message += "Total user sessions: " + users.Sum(x => (long)x.Value.SessionCount) + "\n"; message += "Stored messages: " + messages.Count + "\n"; message += "Stored log: " + logMessages.Count + "\n"; message += "Log file buffer: " + logFileBuffer.Count + "\n"; message += "Modules loaded: " + string.Join(", ", modules.Select(x => x.GetType().Name)) + " (" + modules.Count + ")\n"; message += "Subscribed handlers for extra output: " + this.ExtraCommandHandlerCount + "\n"; message += "Registered connections: " + ChatRunner.Server.ConnectedUsers().Count + "\n"; using(Process process = Process.GetCurrentProcess()) { message += "Virtual Memory: " + (process.PrivateMemorySize64 / 1048576) + "MiB\n"; message += "Heap Allocated: " + (GC.GetTotalMemory(true) / 1048576) + "MiB\n"; message += "Threads: " + process.Threads.Count; } moduleOutput.message = message; outputs.Add(moduleOutput); break; case "debuginfo": //if we can't parse the user, use yourself. Otherwise if it parsed but they don't have //access to this command, stop and let them know. if(string.IsNullOrWhiteSpace(command.Arguments[0]) || !GetUserFromArgument(command.Arguments[0], users, out parsedInfo)) parsedInfo = user; else if(!user.ChatControl && parsedInfo.UID != user.UID) return FastMessage("You don't have access to this command!", true); message = parsedInfo.Username + "'s debug information: \n\n"; message += "Session ID: " + parsedInfo.LastSessionID + "\n"; message += "Open sessions: " + parsedInfo.OpenSessionCount + "\n"; message += "Bad sessions: " + parsedInfo.BadSessionCount + "\n"; message += "Current session time: " + StringExtensions.LargestTime(parsedInfo.CurrentSessionTime) + "\n"; message += "UID: " + parsedInfo.UID + "\n"; message += "Active: " + parsedInfo.Active + "\n"; message += "Last ping: " + StringExtensions.LargestTime(DateTime.Now - parsedInfo.LastPing) + "\n"; message += "Last post: " + StringExtensions.LargestTime(DateTime.Now - parsedInfo.LastPost) + "\n"; message += "Last entry: " + StringExtensions.LargestTime(DateTime.Now - parsedInfo.LastJoin) + "\n"; message += "Staff chat: " + parsedInfo.CanStaffChat + "\n"; message += "Global chat: " + parsedInfo.CanGlobalChat + "\n"; message += "Chat control: " + parsedInfo.ChatControl + "\n"; message += "Chat control extended: " + parsedInfo.ChatControlExtended + "\n"; message += "Avatar: " + user.Avatar + "\n"; moduleOutput.message = message; outputs.Add(moduleOutput); break; } } catch (Exception e) { return FastMessage("An error has occurred in the debug module: " + e.Message, true); } return outputs; }
public UserCommand MSG_ReadDeltaUsercmdKey(NetBuffer msg, ref UserCommand from) { UserCommand to = new UserCommand(); if (msg.ReadBoolean()) to.serverTime = from.serverTime + (int)msg.ReadUInt32(8); else to.serverTime = msg.ReadInt32(); if (msg.ReadBoolean()) { to.anglex = (int)MSG_ReadDeltaKey(msg, (uint)from.anglex, 16); to.angley = (int)MSG_ReadDeltaKey(msg, (uint)from.angley, 16); to.anglez = (int)MSG_ReadDeltaKey(msg, (uint)from.anglez, 16); to.forwardmove = (short)MSG_ReadDeltaKey(msg, from.forwardmove, 16); to.rightmove = (short)MSG_ReadDeltaKey(msg, from.rightmove, 16); to.upmove = (short)MSG_ReadDeltaKey(msg, from.upmove, 16); to.buttons = MSG_ReadDeltaKey(msg, from.buttons, 16); to.weapon = (byte)MSG_ReadDeltaKey(msg, from.weapon, 8); } else { to.anglex = from.anglex; to.angley = from.angley; to.anglez = from.anglez; to.forwardmove = from.forwardmove; to.rightmove = from.rightmove; to.upmove = from.upmove; to.buttons = from.buttons; to.weapon = from.weapon; } return to; }
private void ReceiveUserCommand(NetIncomingMessage msg) { var client = GetClientInfo(msg); var commandCount = (int)msg.ReadByte(); for (var i = 0; i < commandCount; ++i) { UserCommand cmd = new UserCommand(); cmd.commandid = msg.ReadByte(); cmd.keystate = msg.ReadByte(); cmd.actionstate = msg.ReadByte(); cmd.client_time = msg.ReadFloat(); if(client.has_spawned) { client.cmd_queue.Enqueue(cmd); } } }
private void WriteDeltaUsercmdKey(NetBuffer msg, ref UserCommand from, ref UserCommand to) { // Can delta time fit in one byte? if (to.serverTime - from.serverTime < 256) { msg.Write(true); msg.Write((uint)(to.serverTime - from.serverTime), 8); } else { msg.Write(false); msg.Write(to.serverTime, 32); } if (from.anglex == to.anglex && from.angley == to.angley && from.anglez == to.anglez && from.buttons == to.buttons && from.forwardmove == to.forwardmove && from.rightmove == to.rightmove && from.upmove == to.upmove && from.weapon == to.weapon) { msg.Write(false); // no change return; } msg.Write(true); MSG_WriteDeltaKey(msg, (uint)from.anglex, (uint)to.anglex, 16); MSG_WriteDeltaKey(msg, (uint)from.angley, (uint)to.angley, 16); MSG_WriteDeltaKey(msg, (uint)from.anglez, (uint)to.anglez, 16); MSG_WriteDeltaKey(msg, from.forwardmove, to.forwardmove, 16); MSG_WriteDeltaKey(msg, from.rightmove, to.rightmove, 16); MSG_WriteDeltaKey(msg, from.upmove, to.upmove, 16); MSG_WriteDeltaKey(msg,from.buttons, to.buttons, 16); MSG_WriteDeltaKey(msg, from.weapon, to.weapon, 8); }
/// <summary> /// Get command. /// </summary> /// <param name="userInput">User input.</param> /// <param name="currentScreen">Current screen.</param> /// <param name="userCommand">User command.</param> /// <returns>True if user has entered existing command, Screen that should be shown next.</returns> public static bool GetCommand(string userInput, Screen currentScreen, out UserCommand userCommand) { switch (userInput.ToLower()) { case "register": userCommand = UserCommand.GoToRegister; return true; case "login": userCommand = UserCommand.GoToLogin; return true; case "add": if (currentScreen == Screen.UserProfile) { userCommand = UserCommand.AddToDo; return true; } else { IOService.Print(Resources.wrongCommand); userCommand = UserCommand.None; return false; } case "remove": if (currentScreen == Screen.UserProfile) { userCommand = UserCommand.RemoveToDo; return true; } else { userCommand = UserCommand.None; return false; } case "complete": if(currentScreen == Screen.UserProfile) { userCommand = UserCommand.CompleteToDo; return true; } else { userCommand = UserCommand.None; return false; } case "history": if (currentScreen == Screen.UserProfile) { userCommand = UserCommand.HistoryToDo; return true; } else { userCommand = UserCommand.None; return false; } case "back": if (currentScreen == Screen.UserProfile) { userCommand = UserCommand.GoToLogin; return true; } else { IOService.Print(Resources.wrongCommand); userCommand = UserCommand.None; return false; } case "exit": userCommand = UserCommand.None; Environment.Exit(-1); return false; default: userCommand = UserCommand.None; return false; } }
public override List<JSONObject> ProcessCommand(UserCommand command, UserInfo user, Dictionary<int, UserInfo> users) { List<JSONObject> outputs = new List<JSONObject>(); ModuleJSONObject output = new ModuleJSONObject(); string error = ""; switch (command.Command) { case "pm": //First, make sure this even works UserInfo recipient; output = new ModuleJSONObject(); if (!GetUserFromArgument(command.Arguments[0], users.Where(x => x.Value.LoggedIn).ToDictionary(x => x.Key, y => y.Value), out recipient)) { AddError(outputs); break; } output.tag = "any"; output.message = user.Username + " -> " + command.Arguments[0] + ":\n" + command.Arguments[1]; //System.Security.SecurityElement.Escape(command.Arguments[1]); output.recipients.Add(recipient.UID); output.recipients.Add(command.uid); outputs.Add(output); break; case "pmcreateroom": HashSet<int> roomUsers = new HashSet<int>(); foreach (string roomUser in command.ArgumentParts[0]) { UserInfo tempUser; if (!GetUserFromArgument(roomUser, users, out tempUser)) { error = "User not found!"; break; } else if (!roomUsers.Add(tempUser.UID)) { error = "Duplicate user in list: " + tempUser.Username; break; } } roomUsers.Add(user.UID); if (!string.IsNullOrWhiteSpace(error) || !ChatRunner.Server.CreatePMRoom(roomUsers, user.UID, out error)) { WarningJSONObject warning = new WarningJSONObject(error); outputs.Add(warning); } else { output.message = "You created a chatroom for " + string.Join(", ", roomUsers.Select(x => users[x].Username)); outputs.Add(output); } break; case "pmleaveroom": if (!ChatRunner.Server.LeavePMRoom(user.UID, command.tag, out error)) { WarningJSONObject warning = new WarningJSONObject(error); outputs.Add(warning); } else { output.message = "You left this PM room"; outputs.Add(output); } break; } return outputs; }
public virtual void Execute(UserCommand command) { command.Execute(); }
void KeyMove(ref UserCommand cmd) { int forward = 0, side = 0, up = 0; int movespeed = 400; side += (int)(movespeed * KeyState(ref in_moveright)); side -= (int)(movespeed * KeyState(ref in_moveleft)); up += (int)(movespeed * KeyState(ref in_up)); up -= (int)(movespeed * KeyState(ref in_down)); forward += (int)(movespeed * KeyState(ref in_forward)); forward -= (int)(movespeed * KeyState(ref in_back)); cmd.forwardmove = ClampShort(forward); cmd.rightmove = ClampShort(side); cmd.upmove = ClampShort(up); //if(cmd.forwardmove != 0 || cmd.rightmove != 0) // System.Console.WriteLine("{0} {1} {2}", cmd.forwardmove, cmd.rightmove, cmd.upmove); }
/// <summary> /// Process inputed command. /// </summary> /// <param name="userCommand">User command.</param> /// <param name="currentScreen">Current screen.</param> /// <returns>Screen.</returns> public static Screen ProcessCommand(UserCommand userCommand, Screen currentScreen) { Screen screen = currentScreen; switch (userCommand) { case UserCommand.GoToRegister: screen = Screen.Register; UIPresenter.ShowScreen(screen); if (RegisterProcess()) { screen = Screen.UserProfile; UIPresenter.ShowScreen(screen); } else { screen = Screen.StartUp; UIPresenter.ShowScreen(screen); } break; case UserCommand.GoToLogin: screen = Screen.Login; UIPresenter.ShowScreen(screen); if (LogInProcess()) screen = Screen.UserProfile; else screen = Screen.StartUp; break; case UserCommand.AddToDo: screen = Screen.AddToDoScreen; UIPresenter.ShowScreen(screen); if (AddToList()) screen = Screen.UserProfile; else screen = Screen.UserProfile; break; case UserCommand.RemoveToDo: RemoveToDo(); screen = Screen.UserProfile; break; case UserCommand.CompleteToDo: CompleteToDo(); screen = Screen.UserProfile; break; case UserCommand.HistoryToDo: screen = Screen.HistoryScreen; UIPresenter.ShowScreen(screen); History(); screen = Screen.UserProfile; break; case UserCommand.None: break; } return screen; }