/// <summary> /// Initializes a new instance of the <see cref="BlockPlaceEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, coordinates, block <paramref name="id"/>, /// block <paramref name="style"/>, and replacement flag. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player placing the block, or <see langword="null"/> for none.</param> /// <param name="x">The block's X coordinate.</param> /// <param name="y">The block's Y coordinate.</param> /// <param name="id">The block ID being placed.</param> /// <param name="style">The block style being placed.</param> /// <param name="isReplacement">Whether the block placing is a replacement.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public BlockPlaceEvent(IWorld world, IPlayer?player, int x, int y, BlockId id, int style, bool isReplacement) : base(world, player, x, y) { Id = id; Style = style; IsReplacement = isReplacement; }
static void repeatPlay(IPlayer player1, IPlayer player2, int boardSize, int numberOfGames) { int draws = 0; int player1WinCount = 0; int player2WinCount = 0; for (int i = 0; i < numberOfGames; i++) { IPlayer?winner = play(player1, player2, boardSize, false); if (winner == null) { draws++; } else if (winner == player1) { player1WinCount++; } else { player2WinCount++; } } Console.WriteLine("Draws : " + draws); Console.WriteLine("Player1 wins count : " + player1WinCount); Console.WriteLine("Player2 wins count : " + player2WinCount); }
public bool Equals(IPlayer?x, IPlayer?y) { var nameFirst = x?.LastName + x?.FirstName; var nameSecond = y?.LastName + y?.FirstName; return(nameFirst == nameSecond); }
/// <inheritdoc /> public IPlayer?RemovePlayer(int playerid) { Guard.Argument(playerid, nameof(playerid)).NotNegative(); IPlayer?result = null; this.UpdateEntities(c => c.TryGetValue(playerid, out result) ? c.Remove(playerid) : c); return(result); }
public bool IsGameOver() { var gameResult = BoardUtils.ComputeGameResult(board, EMPTY_CHAR); if (gameResult.Item1 && gameResult.Item2 != EMPTY_CHAR) { Winner = getWinnerFromSymbol(gameResult.Item2); } return(gameResult.Item1); }
public void Bind(IPlayer implementation) { CheckArg.NotNull(implementation); if (IsBound) { throw new InvalidOperationException("Adapter is already bound"); } _implementation = implementation; }
/// <summary> /// Matchmaking loop. When two players are in the player pool /// a new match will be processed. /// </summary> private void Run() { while (listening) { try { if (playerPool.Count >= 2) { // Get players from queue IPlayer?playerA = null, playerB = null; while (playerA == null) { playerPool.TryDequeue(out playerA); } while (playerB == null) { playerPool.TryDequeue(out playerB); } // Check if players are different if (playerA.Username == playerB.Username) { Dictionary <string, object> error = new Dictionary <string, object>() { { "error", "Cannot battle oneself!" } }; playerA.BattleResult = error; playerB.BattleResult = error; } else { // Get token & GUID and start battle processing var token = tokenSource.Token; var id = Guid.NewGuid().ToString(); var task = Task.Run(() => Process(playerA, playerB), token); tasks[id] = task; // Remove task from collection when finished task.ContinueWith(t => { tasks.TryRemove(id, out t !); }, token); } } else { Thread.Sleep(15); } } catch (Exception) { // ignored } } }
public int Compare(IPlayer?x, IPlayer?y) { if (x?.Rank == null) { return(1); } if (y?.Rank == null) { return(-1); } return(x !.Rank.CompareTo(y !.Rank)); }
public void Bind(IPlayer implementation) { if (implementation is null) { throw new ArgumentNullException(nameof(implementation)); } if (IsBound) { throw new InvalidOperationException("Adapter is already bound"); } _implementation = implementation; }
/// <summary> /// Initializes a new instance of the <see cref="PlayerDeathEvent"/> class. /// </summary> /// <param name="player">Player that has been killed.</param> /// <param name="killer">Optional killer that killed the <paramref name="player"/>.</param> /// <param name="reason">Numerical reason of death.</param> /// <exception cref="ArgumentNullException"><paramref name="player"/> is null.</exception> /// <exception cref="ObjectDisposedException"><paramref name="player"/> or <paramref name="killer"/> was disposed.</exception> public PlayerDeathEvent(IPlayer player, IPlayer?killer, int reason) { Guard.Argument(player, nameof(player)).NotNull(); Guard.Disposal(player.Disposed, nameof(player)); if (killer != null) { Guard.Disposal(killer.Disposed, nameof(player)); } this.Player = player; this.Killer = killer; this.Reason = reason; }
/// <summary> /// Open the file to play. Caller has already set _fn to requested file name. /// </summary> /// <returns></returns> bool OpenFile() { bool ok = true; chkPlay.Checked = false; cmbDrumChannel.SelectedIndex = MidiDefs.DEFAULT_DRUM_CHANNEL - 1; // reset try { switch (Path.GetExtension(_fn).ToLower()) { case ".mid": // case ".sty": Use ClipExplorer for these _player = _midiPlayer; break; case ".wav": case ".mp3": case ".m4a": case ".flac": _player = _audioPlayer; break; default: MessageBox.Show($"Invalid file: {_fn}"); ok = false; _fn = ""; break; } if (ok) { if (_player !.OpenFile(_fn)) { Text = $"{Path.GetFileName(_fn)} {_player.GetInfo()}"; _player.Volume = sldVolume.Value; _player.Rewind(); // Make it go. chkPlay.Checked = true; } else { MessageBox.Show("Couldn't open file"); _fn = ""; ok = false; } } }
public void Play(IEnumerable <ITactics> tactics) { while (!IsEnded) { tactics .First(t => t.CanApply(GameState)) .Apply(GameState); if ((lastPlayer == null) && GameState.Table.Deck.Cards.None()) { lastPlayer = GameState.CurrentPlayer; } GameState.CurrentPlayer = GameState.NextPlayer; } }
public int Compare(IPlayer?x, IPlayer?y) { var namesFirst = x?.FirstName + x?.LastName; var namesSecond = y?.FirstName + y?.LastName; if (namesFirst == null || namesFirst.Trim() == "") { throw new Exception(namesFirst); //return (namesSecond == null || namesSecond.Trim() =="") ? 0 : -1; } if (namesSecond == null || namesSecond.Trim() == "") { return(1); } int minLength = Math.Min(namesFirst.Length, namesSecond.Length); for (int i = 0; i < minLength; i++) { int i1 = Dictionary.IndexOf(namesFirst[i]); int i2 = Dictionary.IndexOf(namesSecond[i]); if (i1 == -1) { throw new Exception(namesFirst); } if (i2 == -1) { throw new Exception(namesSecond); } int cmp = i1.CompareTo(i2); if (cmp != 0) { return(cmp); } } //return _comparerImplementation.Compare(x, y); return(namesFirst.Length.CompareTo(namesSecond.Length)); }
/// <summary> /// Tries to get the executor from context of this resolution. /// </summary> /// <param name="context">Context to search in.</param> /// <param name="executor">Resulting executor of this resolution. Null if no context was set or executor is not <see cref="IPlayer"/>.</param> /// <returns>true if executor has been found of type <see cref="IPlayer"/>, false otherwise.</returns> /// <exception cref="ArgumentNullException"><paramref name="context"/> is null.</exception> public static bool TryGetCommandExecutor(this ResolutionContext context, out IPlayer?executor) { Guard.Argument(context, nameof(context)).NotNull(); executor = default; if (context.Items.TryGetValue(CommandConstants.CommandExecutorKey, out var value) == false) { return(false); } if (value is not IPlayer player) { return(false); } executor = player; return(true); }
public int Compare(IPlayer?x, IPlayer?y) { var ageFirst = x?.Age; var ageSecond = y?.Age; if (ageFirst == 0 || x?.Age == null) { return(1); } if (ageSecond == 0 || y?.Age == null) { return(-1); } if (ageFirst == 0 && ageSecond == 0) { return(0); } return(x.Age.CompareTo(y.Age)); }
private void OnPlayerDeath(NativePlayerDeathEvent eventdata) { if (this.playerPool.Entities.TryGetValue(eventdata.Playerid, out var player) == false) { this.logger.LogWarning($"Received a {nameof(NativePlayerDeathEvent)} from player {eventdata.Playerid}, but the player could not be found."); return; } IPlayer?killer = null; if (eventdata.Killerid != SampConstants.InvalidPlayerId) { if (this.playerPool.Entities.TryGetValue(eventdata.Killerid, out killer) == false) { this.logger.LogWarning($"Received a {nameof(NativePlayerDeathEvent)} from killer {eventdata.Killerid}, but the player could not be found."); return; } } this.WrapCancellableEvent(eventdata, new PlayerDeathEvent(player, killer, eventdata.Reason)); }
/// <summary> /// Edit the common options in a property grid. /// </summary> void Settings_Click(object?sender, EventArgs e) { using Form f = new() { Text = "User Settings", Size = new Size(450, 450), StartPosition = FormStartPosition.Manual, Location = new Point(200, 200), FormBorderStyle = FormBorderStyle.FixedToolWindow, ShowIcon = false, ShowInTaskbar = false }; PropertyGridEx pg = new() { Dock = DockStyle.Fill, PropertySort = PropertySort.Categorized, SelectedObject = Common.Settings }; // Detect changes of interest. bool midiChange = false; bool audioChange = false; bool navChange = false; bool restart = false; pg.PropertyValueChanged += (sdr, args) => { restart |= args.ChangedItem.PropertyDescriptor.Name.EndsWith("Device"); midiChange |= args.ChangedItem.PropertyDescriptor.Category == "Midi"; audioChange |= args.ChangedItem.PropertyDescriptor.Category == "Audio"; navChange |= args.ChangedItem.PropertyDescriptor.Category == "Navigator"; }; f.Controls.Add(pg); f.ShowDialog(); // Figure out what changed - each handled differently. if (restart) { MessageBox.Show("Restart required for device changes to take effect"); } if ((midiChange && _player is MidiPlayer) || (audioChange && _player is WavePlayer)) { _player.SettingsChanged(); } if (navChange) { InitNavigator(); } SaveSettings(); } #endregion #region Info /// <summary> /// All about me. /// </summary> void About_Click(object?sender, EventArgs e) { Tools.MarkdownToHtml(File.ReadAllLines(@".\README.md").ToList(), "lightcyan", "helvetica", true); } /// <summary> /// Something you should know. /// </summary> /// <param name="sender"></param> /// <param name="ea"></param> void LogMessage(object?sender, string cat, string msg) { int catSize = 3; cat = cat.Length >= catSize?cat.Left(catSize) : cat.PadRight(catSize); // May come from a different thread. this.InvokeIfRequired(_ => { string s = $"{DateTime.Now:mm\\:ss\\.fff} {cat} ({((Control)sender!).Name}) {msg}"; txtViewer.AddLine(s); }); } #endregion #region File handling /// <summary> /// Organize the file drop down. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void File_DropDownOpening(object?sender, EventArgs e) { fileDropDownButton.DropDownItems.Clear(); // Always: fileDropDownButton.DropDownItems.Add(new ToolStripMenuItem("Open...", null, Open_Click)); fileDropDownButton.DropDownItems.Add(new ToolStripMenuItem("Dump...", null, Dump_Click)); fileDropDownButton.DropDownItems.Add(new ToolStripMenuItem("Export...", null, Export_Click)); fileDropDownButton.DropDownItems.Add(new ToolStripSeparator()); Common.Settings.RecentFiles.ForEach(f => { ToolStripMenuItem menuItem = new(f, null, new EventHandler(Recent_Click)); fileDropDownButton.DropDownItems.Add(menuItem); }); } /// <summary> /// The user has asked to open a recent file. /// </summary> void Recent_Click(object?sender, EventArgs e) { //ToolStripMenuItem item = sender as ToolStripMenuItem; string fn = sender !.ToString() !; if (fn != _fn) { OpenFile(fn); _fn = fn; } } /// <summary> /// Allows the user to select an audio clip or midi from file system. /// </summary> void Open_Click(object?sender, EventArgs e) { string sext = "Clip Files | "; foreach (string ext in _fileTypes) { sext += $"*{ext}; "; } using OpenFileDialog openDlg = new() { Filter = sext, Title = "Select a file" }; if (openDlg.ShowDialog() == DialogResult.OK && openDlg.FileName != _fn) { OpenFile(openDlg.FileName); _fn = openDlg.FileName; } } /// <summary> /// Common file opener. /// </summary> /// <param name="fn">The file to open.</param> /// <returns>Status.</returns> public bool OpenFile(string fn) { bool ok = true; Stop(); LogMessage(this, "INF", $"Opening file: {fn}"); using (new WaitCursor()) { try { if (File.Exists(fn)) { switch (Path.GetExtension(fn).ToLower()) { case ".wav": case ".mp3": case ".m4a": case ".flac": _wavePlayer !.Visible = true; _midiPlayer !.Visible = false; _player = _wavePlayer; break; case ".mid": _wavePlayer !.Visible = false; _midiPlayer !.Visible = true; _player = _midiPlayer; break; default: LogMessage(this, "ERR", $"Invalid file type: {fn}"); ok = false; break; } if (ok) { ok = _player !.OpenFile(fn); if (Common.Settings.Autoplay) { Start(); } } } else { LogMessage(this, "ERR", $"Invalid file: {fn}"); ok = false; } } catch (Exception ex) { LogMessage(this, "ERR", $"Couldn't open the file: {fn} because: {ex.Message}"); ok = false; } } if (ok) { Text = $"ClipExplorer {MiscUtils.GetVersionString()} - {fn}"; Common.Settings.RecentFiles.UpdateMru(fn); } else { Text = $"ClipExplorer {MiscUtils.GetVersionString()} - No file loaded"; } return(ok); } /// <summary> /// Dump current file. /// </summary> void Dump_Click(object?sender, EventArgs e) { var ds = _player !.Dump(); if (ds.Count > 0) { if (Common.Settings.DumpToClip) { Clipboard.SetText(string.Join(Environment.NewLine, ds)); LogMessage(this, "INF", "File dumped to clipboard"); } else { using SaveFileDialog dumpDlg = new() { Title = "Dump to file", FileName = "dump.csv" }; if (dumpDlg.ShowDialog() == DialogResult.OK) { File.WriteAllLines(dumpDlg.FileName, ds.ToArray()); } } } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Export_Click(object?sender, EventArgs e) { _player !.Export(); } #endregion #region Transport control /// <summary> /// Internal handler. /// </summary> /// <returns></returns> bool Stop() { _player?.Stop(); SetPlayCheck(false); return(true); } /// <summary> /// Internal handler. /// </summary> /// <returns></returns> bool Start() { _player?.Rewind(); _player?.Play(); SetPlayCheck(true); return(true); } /// <summary> /// Need to temporarily suppress CheckedChanged event. /// </summary> /// <param name="on"></param> void SetPlayCheck(bool on) { chkPlay.CheckedChanged -= Play_CheckedChanged; chkPlay.Checked = on; chkPlay.CheckedChanged += Play_CheckedChanged; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Play_CheckedChanged(object?sender, EventArgs e) { var _ = chkPlay.Checked ? Start() : Stop(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Player_PlaybackCompleted(object?sender, EventArgs e) { // Usually comes from a different thread. this.InvokeIfRequired(_ => { if (chkLoop.Checked) { Start(); } else { Stop(); _player !.Rewind(); } }); } /// <summary> /// Do some global key handling. Space bar is used for stop/start playing. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MainForm_KeyDown(object?sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Space: // Toggle. bool _ = chkPlay.Checked ? Stop() : Start(); e.Handled = true; break; case Keys.C: txtViewer.Clear(); e.Handled = true; break; case Keys.W: txtViewer.WordWrap = !txtViewer.WordWrap; e.Handled = true; break; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Rewind_Click(object?sender, EventArgs e) { Stop(); _player !.Rewind(); } #endregion #region Navigator functions /// <summary> /// Initialize tree from user settings. Clone so we don't mess up the originals. /// </summary> void InitNavigator() { ftree.FilterExts = _fileTypes.ToList(); ftree.RootDirs = Common.Settings.RootDirs; ftree.AllTags = Common.Settings.AllTags; ftree.TaggedPaths = Common.Settings.TaggedPaths; ftree.DoubleClickSelect = !Common.Settings.Autoplay; ftree.Init(); } /// <summary> /// Tree has seleccted a file to play. /// </summary> /// <param name="sender"></param> /// <param name="fn"></param> void Navigator_FileSelectedEvent(object?sender, string fn) { OpenFile(fn); _fn = fn; } #endregion #region Misc handlers /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Volume_ValueChanged(object?sender, EventArgs e) { float vol = (float)sldVolume.Value; Common.Settings.Volume = vol; if (_player is null) { _midiPlayer !.Volume = vol; _wavePlayer !.Volume = vol; } else { _player.Volume = vol; } } #endregion } }
/// <summary> /// Attempts to get the <see cref="IPlayer"/> for the specified /// <paramref name="guildId"/>. /// </summary> /// <param name="guildId">The guild ID to get the player for.</param> /// <param name="player">The player, if it exists.</param> /// <returns> /// <code>true</code> if successful, <code>false</code> otherwise. /// </returns> public bool TryGetPlayer(ulong guildId, out IPlayer?player) => _players.TryGetValue(guildId, out player);
/// <summary> /// Initializes a new instance of the <see cref="TileLiquidEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, tile coordinates, and <paramref name="liquid"/>. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player setting the tile's liquid, or <see langword="null"/> for none.</param> /// <param name="x">The tile's X coordinate.</param> /// <param name="y">The tile's Y coordinate.</param> /// <param name="liquid">The tile's liquid.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public TileLiquidEvent(IWorld world, IPlayer?player, int x, int y, Liquid liquid) : base(world, player, x, y) { Liquid = liquid; }
/// <summary> /// Initializes a new instance of the <see cref="WallBreakEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, and coordinates. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player breaking the wall, or <see langword="null"/> for none.</param> /// <param name="x">The wall's X coordinate.</param> /// <param name="y">The wall's Y coordinate.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public WallBreakEvent(IWorld world, IPlayer?player, int x, int y) : base(world, player, x, y) { }
/// <summary> /// Initializes a new instance of the <see cref="TileEvent"/> class with the specified <paramref name="world"/>, /// <paramref name="player"/>, and coordinates. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player involved in the event, or <see langword="null"/> for none.</param> /// <param name="x">The tile's X coordinate.</param> /// <param name="y">The tile's Y coordinate.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> protected TileEvent(IWorld world, IPlayer?player, int x, int y) : base(world) { Player = player; X = x; Y = y; }
/// <summary> /// Initializes a new instance of the <see cref="WallPlaceEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, coordinates, wall <paramref name="id"/>, and /// replacement flag. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player placing the wall, or <see langword="null"/> for none.</param> /// <param name="x">The wall's X coordinate.</param> /// <param name="y">The wall's Y coordinate.</param> /// <param name="id">The wall ID being placed.</param> /// <param name="isReplacement">Whether the wall placing is a replacement.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public WallPlaceEvent(IWorld world, IPlayer?player, int x, int y, WallId id, bool isReplacement) : base(world, player, x, y) { Id = id; IsReplacement = isReplacement; }
/// <summary> /// Initializes a new instance of the <see cref="BlockBreakEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, coordinates, and itemlessness flag. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player breaking the block, or <see langword="null"/> for none.</param> /// <param name="x">The block's X coordinate.</param> /// <param name="y">The block's Y coordinate.</param> /// <param name="isItemless">Whether the block breaking is itemless.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public BlockBreakEvent(IWorld world, IPlayer?player, int x, int y, bool isItemless) : base(world, player, x, y) { IsItemless = isItemless; }
/// <summary> /// Initializes a new instance of the <see cref="BlockPaintEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, coordinates, and block <paramref name="color"/>. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player painting the block, or <see langword="null"/> for none.</param> /// <param name="x">The block's X coordinate.</param> /// <param name="y">The block's Y coordinate.</param> /// <param name="color">The block color being painted.</param> /// <exception cref="ArgumentNullException"><paramref name="world"/> is <see langword="null"/>.</exception> public BlockPaintEvent(IWorld world, IPlayer?player, int x, int y, PaintColor color) : base(world, player, x, y) { Color = color; }
/// <summary> /// Initializes a new instance of the <see cref="WiringActivateEvent"/> class with the specified /// <paramref name="world"/>, <paramref name="player"/>, and wiring coordinates. /// </summary> /// <param name="world">The world involved in the event.</param> /// <param name="player">The player activating the wiring, or <see langword="null"/> for none.</param> /// <param name="x">The wiring's X coordinate.</param> /// <param name="y">The wiring's Y coordinate.</param> public WiringActivateEvent(IWorld world, IPlayer?player, int x, int y) : base(world, player, x, y) { }