public async Task CancelFFmpeg() { Global.cts.Cancel(); DiscordWrapper.Log("[log] Playback terminated."); await Task.Delay(TimeSpan.FromMilliseconds(1000)); }
public async Task Remind(int h, int m, [Remainder] string text) { await Context.Message.DeleteAsync(); DiscordWrapper.Log($"Lời nhắc của {Context.Message.Author.Username} ({Context.Message.Author.Id}) ở guild {Context.Guild.Name} ({h}:{m} / {text})"); try { WqlEventQuery query = new WqlEventQuery ("__InstanceModificationEvent", new TimeSpan(0, 0, 60), $"TargetInstance isa 'Win32_LocalTime' AND TargetInstance.Hour={h} AND TargetInstance.Minute={m} AND TargetInstance.Second=0"); ManagementEventWatcher watcher = new ManagementEventWatcher(query); watcher.EventArrived += async(object sender, EventArrivedEventArgs e) => { await DiscordWrapper.SendMessage(Context, $"*Đây là lời nhắc dành cho {Context.Message.Author.Mention}:*\n{text}"); }; watcher.Start(); } catch (Exception e) { DiscordWrapper.Log($"[log] ScheduledTask in Module: {e}"); DiscordWrapper.Log($"Lỗi {e} ở lời nhác của {Context.Message.Author.Id} ở guild {Context.Guild.Name} ({h}:{m} / {text})"); await DiscordWrapper.SendMessage(Context, $"Có lỗi xảy ra. Bạn nhắc lại giúp Mèo thời gian và lời nhắn với, {Context.Message.Author.Mention}."); } }
private static bool SetControl(ref ChessBoard chess) { try { for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { chess.Control[0, i, j] = chess.Control[1, i, j] = 0; } } for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { if (chess.Board[i, j] != ChessBoard.Empty && !SetControlPos(ref chess, i, j)) { return(false); } } } return(true); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
public async Task New() { ulong UserId = Context.Message.Author.Id; await DiscordWrapper.SendMessage(Context, $"{MentionUtils.MentionUser(UserId)}, bạn có chắc muốn tạo trò chơi mới? (Yes/No)"); string content = null; SocketMessage msg; Stopwatch s = new Stopwatch(); s.Start(); do { msg = await NextMessageAsync(fromSourceUser : true, inSourceChannel : true, timeout : TimeSpan.FromMinutes(5)); if (msg == null) { break; } content = msg.Content.ToLower(); if (content == "yes" || content == "no") { break; } } while (s.Elapsed < TimeSpan.FromMinutes(5)); if (msg == null) { await DiscordWrapper.SendMessage(Context, $"Mèo không nhận được phản hồi của {MentionUtils.MentionUser(UserId)}... :cry:"); return; } else if (content == "no") { await DiscordWrapper.SendMessage(Context, $"Trò chơi mới sẽ không được tạo."); await Task.Delay(TimeSpan.FromSeconds(5)); await(Context.Channel as ITextChannel).DeleteMessagesAsync(await Context.Channel.GetMessagesAsync(4).FlattenAsync()); return; } await(Context.Channel as ITextChannel).DeleteMessagesAsync(await Context.Channel.GetMessagesAsync(2).FlattenAsync()); Puzzle puzzle = new Puzzle(UserId); Save(ref puzzle); DiscordWrapper.Log($"puzzle new | {Context.Message.Author.Username} ({Context.Message.Author.Id})"); if (!(await Host())) { var embed = new EmbedBuilder { Description = $"Trò chơi của {MentionUtils.MentionUser(puzzle.PlayerId) } đã tạm dừng.", Color = Color.Blue }; await DiscordWrapper.SendMessage(Context, embed : embed.Build()); } }
public async Task JoinAudio(IGuild guild, IVoiceChannel target) { try { if (isGuildAdded(guild).Result) { if (connectedVChannel(guild).Result != null) { return; } ConnectedChannels.Clear(); } if (target.Guild.Id != guild.Id) { return; } var audioClient = await target.ConnectAsync(); if (ConnectedChannels.TryAdd(guild.Id, audioClient)) { DiscordWrapper.Log($"[info][{LogSeverity.Info}] Connected to voice on {guild.Name}."); } } catch (Exception ex) { DiscordWrapper.Log($"[log] {ex}"); } }
public async Task Remove(int day) { await Context.Channel.TriggerTypingAsync(); try { var schedule = JsonSerializer.Deserialize <TestSchedule>(File.ReadAllText(_config.GetValue <string>("json:TestSchedule.json"))); schedule.Day[day - 2].Clear(); File.WriteAllText(_config.GetValue <string>("json:TestSchedule.json"), JsonSerializer.Serialize(schedule)); await LogDiscord($"remove {day}"); var msg = await ReplyAsync($"Đã xoá bài các kiểm tra thứ {day} thành công! :partying_face::tada::confetti_ball:"); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); var msg = await ReplyAsync("Có lỗi xảy ra. Hãy chắc chắn bạn đã nhập đúng cú pháp, với các thứ trong ngày là từ 2 đến 6."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } finally { await Context.Message.DeleteAsync(); } }
private async Task HandleCommandAsync(SocketMessage messageParam) { var msg = messageParam as SocketUserMessage; if (msg == null || msg.Author.Id == _config.GetValue <ulong>("discord:ClientID")) { return; } int argPos = 0; var context = new SocketCommandContext(_client, msg); // Attachments if ((msg.Channel as SocketGuildChannel).Guild.Id == _config.GetValue <ulong>("guild:Lollipop:ID") && msg.Author.Id != _config.GetValue <ulong>("discord:AuthorID")) { Atachments(context); } // Prefix, Mention if (!(msg.HasCharPrefix(_config.GetValue <string>("discord:CommandPrefix")[0], ref argPos))) { if (msg.Content.Contains($"<@!{_config.GetValue<ulong>("discord:ClientID")}>") || msg.Content.Contains($"<@{_config.GetValue<ulong>("discord:ClientID")}>")) { DiscordWrapper.Log($"{log_discord} Activity in guild {context.Guild.Name}"); await msg.Channel.TriggerTypingAsync(); await msg.Channel.SendMessageAsync($"*meo meoo*. Bạn cần gì nè, {msg.Author.Mention}?"); } else if (msg.Content == "&party") { DiscordWrapper.Log($"{log_discord} Activity in guild {context.Guild.Name}"); Party_with_goat(context); } return; } // Execute command DiscordWrapper.Log($"{log_discord} Activity in guild {context.Guild.Name}"); var result = await _commands.ExecuteAsync( context : context, argPos : argPos, services : _services); if (!result.IsSuccess) { if (result.ErrorReason == "Unknown command.") { await msg.Channel.TriggerTypingAsync(); await msg.Channel.SendMessageAsync($"Có phải bạn vừa gọi Mèo không, {msg.Author.Mention}?"); } DiscordWrapper.Log($"{log} {result.ErrorReason}"); } }
private bool Save(ref Puzzle puzzle) { try { File.WriteAllText(_config.GetValue <string>("json:Puzzle.json"), JsonConvert.SerializeObject(puzzle)); return(true); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
private async Task <bool> Host() { try { IEnumerable <IMessage> print; Puzzle puzzle; while (true) { puzzle = Load(); print = await Print(); IMessage msg = print.First(); int EnPos = puzzle.EmptySqrPos, StPos = await WaitForMove(msg); //DiscordWrapper.Log($"move {StPos}"); if (StPos == -1) { break; } else if (!puzzle.Move(StPos, EnPos)) { await Context.Channel.TriggerTypingAsync(); await ReplyAndDeleteAsync(content : $"{MentionUtils.MentionUser(puzzle.PlayerId)}, có lỗi xảy ra. Bạn vui lòng thử lại.", timeout : TimeSpan.FromSeconds(5)); } else { Save(ref puzzle); if (puzzle.IsOver) { await Print(); break; } } await(Context.Channel as ITextChannel).DeleteMessagesAsync(print); } puzzle = Load(); return(puzzle.IsOver); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
private bool Save(TaskList taskList) { try { taskList.Unlock(); File.WriteAllText(_config.GetValue <string>("json:ReminderTaskList.json"), JsonConvert.SerializeObject(taskList)); return(true); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
public async Task PlayCmd([Remainder] string file_name) { if (!_service.isGuildAdded(Context.Guild).Result) { var channel = (Context.User as IGuildUser)?.VoiceChannel; if (channel == null) { await Context.Channel.TriggerTypingAsync(); await Context.Channel.SendMessageAsync("Mèo cần ở trong một kênh thoại!"); return; } await _service.JoinAudio(Context.Guild, (Context.User as IVoiceState).VoiceChannel); } string Path = _config.GetValue <string>("config:songPath"); if (!File.Exists($"{Path}{file_name}")) { file_name = _songs.GetValue <string>($"filename:{file_name}"); } if (file_name == null) { await Context.Channel.TriggerTypingAsync(); await ReplyAsync($"Tên bài hát không hợp lệ."); return; } DiscordWrapper.Log("metadata."); /*var metadata = TagLib.File.Create($"{Path}{file_name}"); * var embed = new EmbedBuilder { * Title = "Hiện đang phát", * Description = $"{metadata.Tag.Title} - {metadata.Tag.FirstPerformer}", * Color = Color.Blue * }; * embed.WithFooter(footer => footer.Text = $"[{Context.Message.Author.Username}]") * .WithCurrentTimestamp(); * var msg = await ReplyAsync(embed: embed.Build());*/ DiscordWrapper.Log("set-up done."); await _service.SendAudioAsync(Context.Guild, $"{Path}{file_name}"); DiscordWrapper.Log("playback done."); //await msg.DeleteAsync(); }
private void Atachments(SocketCommandContext context) { var attachments = context.Message.Attachments; if (attachments.Count > 0) { WebClient client = new WebClient(); foreach (var attachment in attachments) { client.DownloadFileAsync(new Uri(attachment.Url), $"{_config.GetValue<string>("config:downloadPath")}{attachment.Filename}"); } DiscordWrapper.Log($"{log_discord} Downloaded {attachments.Count} file(s) from guild {context.Guild.Name}."); } }
public async Task Remove(string s_name, int day, int duration, [Remainder] string note = null) { await Context.Channel.TriggerTypingAsync(); try { var schedule = JsonSerializer.Deserialize <TestSchedule>(File.ReadAllText(_config.GetValue <string>("json:TestSchedule.json"))); var idx = _subjects.GetValue <int>($"idx:{s_name}"); if (idx == default && s_name != "Toan") { throw new NullReferenceException("Subject name not found."); } if (note != null) { note = $" ({note})"; } schedule.Day[day - 2].Remove($"{s_name} - {duration}'{note}"); schedule.Subject[idx].Remove($"Thứ {day} - {duration}'{note}"); File.WriteAllText(_config.GetValue <string>("json:TestSchedule.json"), JsonSerializer.Serialize(schedule)); await LogDiscord($"remove {s_name} {day} {duration}'{note}"); var msg = await ReplyAsync($"Đã xoá bài kiểm tra môn {s_name} thành công! :partying_face::tada::confetti_ball:"); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); var msg = await ReplyAsync("Có lỗi xảy ra. Hãy chắc chắn bạn đã nhập đúng cú pháp, với tên các môn học là: Toan, QP, TD, TCMN, CN, Tin, GDCD, Dia, Su, Anh, Van, Sinh, Hoa, Ly, và các thứ trong ngày là từ 2 đến 6."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } finally { await Context.Message.DeleteAsync(); } }
public async Task KillFFmpeg() { Process killFFmpeg = new Process(); ProcessStartInfo taskkillStartInfo = new ProcessStartInfo { FileName = "taskkill", Arguments = "/F /IM FFmpeg.exe", UseShellExecute = false, CreateNoWindow = true }; killFFmpeg.StartInfo = taskkillStartInfo; killFFmpeg.Start(); DiscordWrapper.Log("[log] Playback terminated."); await Task.Delay(TimeSpan.FromMilliseconds(1000)); }
public async Task Get(string s_name) { await Context.Channel.TriggerTypingAsync(); try { var schedule = JsonSerializer.Deserialize <TestSchedule>(File.ReadAllText(_config.GetValue <string>("json:TestSchedule.json"))); var idx = _subjects.GetValue <int>($"idx:{s_name}"); if (idx == default && s_name != "Toan") { throw new NullReferenceException("Subject name not found."); } var embed = new EmbedBuilder { Color = Color.LightOrange }; if (schedule.Subject[idx].Any()) { embed.AddField($"*Môn {s_name}*", string.Join(", ", schedule.Subject[_subjects.GetValue <int>($"idx:{s_name}")])); } else { embed.AddField($"*Môn {s_name}*", $"Không có bài kiểm tra nào cho môn {s_name} 7 ngày tới cả! :partying_face:"); } await ReplyAsync(embed : embed.Build()); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); await Context.Channel.TriggerTypingAsync(); var msg = await ReplyAsync("Có lỗi xảy ra. Hãy chắc chắn bạn đã nhập đúng cú pháp, với tên các môn học là: Toan, QP, TD, TCMN, CN, Tin, GDCD, Dia, Su, Anh, Van, Sinh, Hoa, Ly."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } finally { await Context.Message.DeleteAsync(); } }
public async Task SendAudioAsync(IGuild guild, string path) { try { IAudioClient client; if (ConnectedChannels.TryGetValue(guild.Id, out client)) { var OutFormat = new WaveFormat(48000, 16, 2); var reader = new Mp3FileReader(path); var naudio = WaveFormatConversionStream.CreatePcmStream(reader); byte[] buffer = new byte[naudio.Length]; int rest = (int)(naudio.Length - naudio.Position); await naudio.ReadAsync(buffer, 0, rest); using (var dstream = client.CreatePCMStream(AudioApplication.Music)) { try { Global.cts = new CancellationTokenSource(); Global.streaming = true; await dstream.WriteAsync(buffer, 0, rest, Global.cts.Token); } finally { await dstream.FlushAsync(); Global.streaming = false; } } } else { DiscordWrapper.Log("[log] Voice channel is not added."); } } catch (Exception ex) { DiscordWrapper.Log($"[log] {ex}"); } }
public async Task React(ulong MsgID, params string[] emotes) { await Context.Message.DeleteAsync(); var msg = (RestUserMessage)await Context.Channel.GetMessageAsync(MsgID); foreach (var s in emotes) { DiscordWrapper.Log(s); if (!Emote.TryParse(s, out var emote)) { await msg.AddReactionAsync(new Emoji(s)); } else { await msg.AddReactionAsync(emote); } } }
public async Task LeaveAudio(IGuild guild) { try { IAudioClient client; if (ConnectedChannels.TryRemove(guild.Id, out client)) { await CancelFFmpeg(); await client.StopAsync(); DiscordWrapper.Log($"[info][{LogSeverity.Info}] Disconnected from the voice on {guild.Name}."); } } catch (Exception ex) { DiscordWrapper.Log($"[log] {ex}"); } }
private TaskList Load() { try { DiscordWrapper.Log("loading"); var taskListJson = JsonConvert.DeserializeObject <TaskListJson>(File.ReadAllText(_config.GetValue <string>("json:ReminderTaskList.json"))); var taskList = new TaskList(taskListJson); if (taskList.isLocked()) { taskList.Unlock(); } return(taskList); } catch (NullReferenceException) { return(new TaskList()); } }
public async Task MainAsync(string[] args) { //******************** Prepare ********************************* _cts = new CancellationTokenSource(); DiscordWrapper.Log($"{log_discord} Loading config file..."); _config = new ConfigurationBuilder() .SetBasePath(JSONBasePath) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build(); _stuff = new ConfigurationBuilder() .SetBasePath(JSONBasePath) .AddJsonFile("Stuff.json", optional: false, reloadOnChange: true) .Build(); DiscordWrapper.Log($"{log_discord} Creating discord client..."); _client = new DiscordSocketClient(); _client.Log += Log; _commands = new CommandService(); //********************* Run ********************************* _services = new ServiceCollection() //.AddSingleton(_Cservices) .AddSingleton(new AudioServiceFFmpeg()) .AddSingleton(new AudioServiceNAudio()) .AddSingleton <InteractiveService>() .AddSingleton(_commands) .AddSingleton(_cts) .AddSingleton(_config) .AddSingleton(_client) .BuildServiceProvider(); _handler = new CommandHandler( _client, _commands, _services, _config, _stuff); await _handler.InstallCommandsAsync(); RunAsync(args).Wait(); }
public async Task All() { await Context.Channel.TriggerTypingAsync(); try { var schedule = JsonSerializer.Deserialize <TestSchedule>(File.ReadAllText(_config.GetValue <string>("json:TestSchedule.json"))); string[] reply = new string[5]; for (int i = 0; i < 5; i++) { if (schedule.Day[i].Any()) { reply[i] = string.Join(", ", schedule.Day[i]); } else { reply[i] = $"Không có bài kiểm tra nào cả! :partying_face:"; } } var embed = new EmbedBuilder { Description = "**Lịch kiểm tra 7 ngày sắp tới~**", Color = Color.LightOrange }; embed.AddField("*Thứ hai*", reply[0]) .AddField("*Thứ ba*", reply[1]) .AddField("*Thứ tư*", reply[2]) .AddField("*Thứ năm*", reply[3]) .AddField("*Thứ sáu*", reply[4]) .AddField("^^Cố gắng lên nào!^^", "*^^Chúc bạn làm bài thật tốt!^^*"); await ReplyAsync(embed : embed.Build()); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); await ReplyAsync("Có lỗi xảy ra. Bạn vui lòng thử lại nhé."); } }
public async Task Get(int day) { await Context.Channel.TriggerTypingAsync(); try { var schedule = JsonSerializer.Deserialize <TestSchedule>(File.ReadAllText(_config.GetValue <string>("json:TestSchedule.json"))); var embed = new EmbedBuilder { Color = Color.LightOrange }; if (schedule.Day[day - 2].Any()) { embed.AddField($"*Thứ {day}*", string.Join(", ", schedule.Day[day - 2])); } else { embed.AddField($"*Thứ {day}*", $"Không có bài kiểm tra nào cho thứ {day} tới cả! :partying_face:"); } await ReplyAsync(embed : embed.Build()); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); await Context.Channel.TriggerTypingAsync(); var msg = await ReplyAsync("Có lỗi xảy ra. Hãy chắc chắn bạn đã nhập đúng cú pháp, với các thứ trong ngày là từ 2 đến 6."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } finally { await Context.Message.DeleteAsync(); } }
public async Task SendAudioAsync(IGuild guild, string path) { try { IAudioClient client; if (ConnectedChannels.TryGetValue(guild.Id, out client)) { await CancelFFmpeg(); DiscordWrapper.Log($"[info][{LogSeverity.Debug}] Starting playback of {path} in {guild.Name}"); using (var FFmpeg = CreateProcess(path)) using (var stream = client.CreatePCMStream(AudioApplication.Music)) { try { Global.cts = new CancellationTokenSource(); Global.streaming = true; await FFmpeg.StandardOutput.BaseStream.CopyToAsync(stream, Global.cts.Token); } finally { await stream.FlushAsync(); Global.streaming = false; } } } else { DiscordWrapper.Log("[log] Voice channel is not added."); } } catch (Exception ex) { DiscordWrapper.Log($"[log] {ex}"); } }
private async Task <bool> Move(string move, ISocketMessageChannel Channel) { try { ChessBoard chess = Load(); move = move.ToLower(); int x1 = move[1] - '1', y1 = move[0] - 'a', x2 = move[4] - '1', y2 = move[3] - 'a', pawn = chess.Board[x1, y1], color = ChessBoard.IsBlack(pawn) ? 6 : 0; int PlayerIndex = chess.CurrentPlayerIndex; if (!TryMove(move, save: true)) { return(false); } if (pawn == ChessBoard.Pawn + color) { //promo if ((PlayerIndex == ChessBoard.WhitePlayerIndex && x2 == ChessBoard.WhiteRank) || (PlayerIndex == ChessBoard.BlackPlayerIndex && x2 == ChessBoard.BlackRank)) { int[] promo = { ChessBoard.Queen + color, ChessBoard.Rook + color, ChessBoard.Bishop + color, ChessBoard.Knight + color }; await DiscordWrapper.SendMessage(Context, "move 1: Hậu; 2: Xe; 3: Tượng; 4: Mã"); SocketMessage msg; int ans = 0; Stopwatch s = new Stopwatch(); s.Start(); while (s.Elapsed < TimeSpan.FromMinutes(5)) { msg = await NextMessageAsync(fromSourceUser : false, inSourceChannel : true, timeout : TimeSpan.FromMinutes(5)); if (msg == null) { return(false); } if (msg.Author.Id != chess.Player[PlayerIndex] || !IsValidMessage(msg.Content)) { continue; } string subs = msg.Content.Substring(5); if (subs == "1" || subs == "2" || subs == "3" || subs == "4") { ans = subs[0] - '1'; break; } } s.Stop(); await(Context.Channel as ITextChannel).DeleteMessagesAsync(await Context.Channel.GetMessagesAsync(2).FlattenAsync()); chess.Board[x2, y2] = promo[ans]; if (!SetControl(ref chess)) { return(false); } if (!Save(ref chess)) { return(false); } } } return(true); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
public async Task Clear() { await Context.Channel.TriggerTypingAsync(); var msg1 = await ReplyAsync("Bạn có chắc muốn xoá toàn bộ dữ liệu về lịch kiểm tra chứ? (Yes/No)"); var response = await NextMessageAsync(timeout : TimeSpan.FromSeconds(15)); if (response == null || response.Content.ToLower() != "yes") { await Context.Channel.TriggerTypingAsync(); var msg2 = await ReplyAsync("Huỷ tác vụ."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg1.DeleteAsync(); await msg2.DeleteAsync(); await response.DeleteAsync(); await Context.Message.DeleteAsync(); return; } await Context.Channel.TriggerTypingAsync(); try { var schedule = new TestSchedule(); File.WriteAllText(_config.GetValue <string>("json:TestSchedule.json"), JsonSerializer.Serialize(schedule)); await LogDiscord("Deleted all scheduled tests."); var msg2 = await ReplyAsync("Xoá toàn bộ bài kiểm tra thành công!"); await Task.Delay(TimeSpan.FromSeconds(3)); await msg1.DeleteAsync(); await msg2.DeleteAsync(); await response.DeleteAsync(); } catch (Exception e) { DiscordWrapper.Log($"[log] {e}"); var msg = await ReplyAsync("Có lỗi xảy ra. Bạn vui lòng thử lại nhé."); await Task.Delay(TimeSpan.FromSeconds(3)); await msg.DeleteAsync(); } finally { await Context.Message.DeleteAsync(); } }
public async Task New(string str2) { ulong UserId = Context.Message.Author.Id; await DiscordWrapper.SendMessage(Context, $"{MentionUtils.MentionUser(UserId)}, bạn có chắc muốn tạo ván đấu mới? (Yes/No)"); string content = null; SocketMessage msg; Stopwatch s = new Stopwatch(); s.Start(); do { msg = await NextMessageAsync(fromSourceUser : true, inSourceChannel : true, timeout : TimeSpan.FromMinutes(5)); if (msg == null) { break; } content = msg.Content.ToLower(); if (content == "yes" || content == "no") { break; } } while (s.Elapsed < TimeSpan.FromMinutes(5)); if (msg == null) { await DiscordWrapper.SendMessage(Context, $"Mèo không nhận được phản hồi của {MentionUtils.MentionUser(UserId)}... :cry:"); return; } else if (content == "no") { await DiscordWrapper.SendMessage(Context, $"Ván đấu mới sẽ không được tạo."); await Task.Delay(TimeSpan.FromSeconds(5)); await(Context.Channel as ITextChannel).DeleteMessagesAsync(await Context.Channel.GetMessagesAsync(4).FlattenAsync()); return; } await(Context.Channel as ITextChannel).DeleteMessagesAsync(await Context.Channel.GetMessagesAsync(2).FlattenAsync()); ChessBoard chess = new ChessBoard(); if (!MentionUtils.TryParseUser(str2, out chess.Player[1])) { var embed = new EmbedBuilder { Description = "Tên người chơi 2 không hợp lệ.", Color = Color.Magenta }; await Context.Channel.TriggerTypingAsync(); await ReplyAndDeleteAsync(content : null, embed : embed.Build(), timeout : TimeSpan.FromSeconds(5)); return; } chess.Player[0] = Context.Message.Author.Id; Save(ref chess); DiscordWrapper.Log($"chess new {MentionUtils.MentionUser(chess.Player[ChessBoard.WhitePlayerIndex]) } *(white)* vs { MentionUtils.MentionUser(chess.Player[ChessBoard.BlackPlayerIndex]) } *(black)*"); if (!(await Host())) { var embed = new EmbedBuilder { Description = $"Trận đấu giữa {MentionUtils.MentionUser(chess.Player[ChessBoard.WhitePlayerIndex])} và {MentionUtils.MentionUser(chess.Player[ChessBoard.BlackPlayerIndex])} đã tạm dừng.", Color = Color.Blue }; //await ReplyAsync(embed: embed.Build()); await DiscordWrapper.SendMessage(Context, embed : embed.Build()); } }
private bool IsValidMove(string move) { try { ChessBoard chess = Load(); move = move.ToLower(); int x1 = move[1] - '1', y1 = move[0] - 'a', x2 = move[4] - '1', y2 = move[3] - 'a', pawn = chess.Board[x1, y1], color = ChessBoard.IsBlack(pawn) ? 6 : 0; int PlayerIndex = chess.CurrentPlayerIndex; ulong PlayerId = chess.Player[PlayerIndex]; if (pawn == ChessBoard.Empty) { return(false); } if (ChessBoard.IsBlack(pawn) != chess.IsBlackPlayer(PlayerId)) { return(false); } if (chess.Board[x2, y2] != ChessBoard.Empty && ChessBoard.IsBlack(chess.Board[x2, y2]) == chess.IsBlackPlayer(PlayerId)) { return(false); } if (pawn == ChessBoard.King + color) { // Castling if (x1 == x2 && ((y2 - y1) * (y2 - y1) == 4)) { if (x1 != (ChessBoard.IsBlack(pawn)? ChessBoard.BlackRank : ChessBoard.WhiteRank)) { return(false); } if (chess.Step[PlayerIndex, x1, y1] != 0 || chess.IsCheck(PlayerIndex) || chess.Control[PlayerIndex ^ 1, x2, y2] != 0) { return(false); } int xr = x1, yr = (y2 < y1) ? 0 : 7; if ((chess.Board[xr, yr] != ChessBoard.Rook && ChessBoard.IsBlack(pawn) && chess.Board[xr, yr] != ChessBoard.Rook + 6 && ChessBoard.IsWhite(pawn)) || chess.Step[PlayerIndex, xr, yr] != 0) { return(false); } for (var j = y1 + ((y1 < yr) ? 1 : -1); j != yr; j += (y1 < yr) ? 1 : -1) { if (chess.Board[x1, j] != ChessBoard.Empty) { return(false); } } for (var j = y1 + ((y1 < y2) ? 1 : -1); j != y2; j += (y1 < y2) ? 1 : -1) { if (chess.Control[PlayerIndex ^ 1, x1, j] != 0) { return(false); } } return(true); } if (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) != 1) { return(false); } if (chess.Control[PlayerIndex ^ 1, x2, y2] != 0) { return(false); } return(true); } else if (pawn == ChessBoard.Pawn + color) { if (y1 == y2 && chess.Step[PlayerIndex, x1, y1] == 0 && (x2 == x1 + (chess.IsBlackPlayer(PlayerId) ? -2 : 2))) { return(true); } if ((x2 != x1 + (chess.IsBlackPlayer(PlayerId) ? -1 : 1)) || (((y2 - y1) * (y2 - y1)) > 1)) { return(false); } if (y2 == y1) { return(true); } if (chess.Board[x2, y2] != ChessBoard.Empty) { return(true); } // en passant if (((chess.Board[x1, y2] != ChessBoard.Pawn && chess.IsBlackPlayer(PlayerId)) && (chess.Board[x1, y2] != ChessBoard.Pawn + 6 && chess.IsWhitePlayer(PlayerId))) || chess.History.Last().Item2 != ChessBoard.Convert(x1 + (chess.IsBlackPlayer(PlayerId) ? -2 : 2), y2, x1, y2)) { return(false); } return(true); } else if (pawn == ChessBoard.Knight + color) { if (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) != 5) { return(false); } return(true); } else if (((pawn == ChessBoard.Queen + color) && x1 != x2 && y1 != y2) || pawn == ChessBoard.Bishop + color) { if ((x1 - x2) != (y1 - y2) && (x1 + y1) != (x2 + y2)) { return(false); } for (int i = x1 + ((x1 < x2) ? 1 : -1), j = y1 + ((y1 < y2) ? 1 : -1); i != x2; i += (x1 < x2) ? 1 : -1, j += ((y1 < y2) ? 1 : -1)) { if (chess.Board[i, j] != ChessBoard.Empty) { return(false); } } return(true); } else if (pawn == ChessBoard.Queen + color || pawn == ChessBoard.Rook + color) { if (x1 != x2 && y1 != y2) { return(false); } if (x1 != x2) { for (var i = x1 + ((x1 < x2) ? 1 : -1); i != x2; i += (x1 < x2) ? 1 : -1) { if (chess.Board[i, y1] != ChessBoard.Empty) { return(false); } } } if (y1 != y2) { for (var j = y1 + ((y1 < y2) ? 1 : -1); j != y2; j += (y1 < y2) ? 1 : -1) { if (chess.Board[x1, j] != ChessBoard.Empty) { return(false); } } } return(true); } return(false); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
private static bool SetControlPos(ref ChessBoard chess, int x, int y) { try { int pawn = chess.Board[x, y]; int PlayerIndex = ChessBoard.IsBlack(pawn) ? ChessBoard.BlackPlayerIndex : ChessBoard.WhitePlayerIndex; if (pawn == ChessBoard.King) { int[,] f = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; for (var i = 0; i < 4; i++) { if ((x + f[i, 0] >= 0) && (x + f[i, 0] <= 7) && (y + f[i, 1] >= 0) && (y + f[i, 1] <= 7)) { ++chess.Control[PlayerIndex, x + f[i, 0], y + f[i, 1]]; } } } if (pawn == ChessBoard.Pawn) { int[] f = { -1, 1 }; for (var i = 0; i < 2; i++) { if (((x + (PlayerIndex == ChessBoard.BlackPlayerIndex ? -1 : 1)) >= 0) && ((x + (PlayerIndex == ChessBoard.BlackPlayerIndex ? -1 : 1)) <= 7) && (y + f[i] >= 0) && (y + f[i] <= 7)) { ++chess.Control[PlayerIndex, x + (PlayerIndex == ChessBoard.BlackPlayerIndex ? -1 : 1), y + f[i]]; } } if (chess.Step[PlayerIndex, x, y] == 0) { ++chess.Control[PlayerIndex, x + (PlayerIndex == ChessBoard.BlackPlayerIndex ? -2 : 2), y]; } } if (pawn == ChessBoard.Knight) { int[,] f = { { -1, 2 }, { -2, 1 }, { 1, 2 }, { 2, 1 }, { -1, -2 }, { -2, -1 }, { 1, -2 }, { 2, -1 } }; for (var i = 0; i < 8; i++) { if ((x + f[i, 0] >= 0) && (x + f[i, 0] <= 7) && (y + f[i, 1] >= 0) && (y + f[i, 1] <= 7)) { ++chess.Control[PlayerIndex, x + f[i, 0], y + f[i, 1]]; } } } if ((pawn == ChessBoard.Queen) || pawn == ChessBoard.Bishop) { int[,] f = { { 1, 1 }, { 1, -1 }, { -1, 1 }, { -1, -1 } }; for (var k = 0; k < 4; k++) { for (int i = x + f[k, 0], j = y + f[k, 1]; i >= 0 && i <= 7 && j >= 0 && j <= 7; i += f[k, 0], j += f[k, 1]) { ++chess.Control[PlayerIndex, i, j]; if (chess.Board[i, j] != ChessBoard.Empty) { break; } } } } if ((pawn == ChessBoard.Queen) || pawn == ChessBoard.Rook) { int[,] f = { { 1, 0 }, { 0, -1 }, { -1, 0 }, { 0, 1 } }; for (var k = 0; k < 4; k++) { for (int i = x + f[k, 0], j = y + f[k, 1]; i >= 0 && i <= 7 && j >= 0 && j <= 7; i += f[k, 0], j += f[k, 1]) { ++chess.Control[PlayerIndex, i, j]; if (chess.Board[i, j] != ChessBoard.Empty) { break; } } } } return(true); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
private bool TryMove(string move, bool save) { ChessBoard chess = Load(); try { move = move.ToLower(); int x1 = move[1] - '1', y1 = move[0] - 'a', x2 = move[4] - '1', y2 = move[3] - 'a', pawn = chess.Board[x1, y1], color = ChessBoard.IsBlack(pawn) ? 6 : 0; int PlayerIndex = chess.CurrentPlayerIndex; chess.Board[x1, y1] = ChessBoard.Empty; if (pawn == ChessBoard.King + color) { chess.Board[x2, y2] = pawn; chess.Step[PlayerIndex, x2, y2] = chess.Step[PlayerIndex, x1, y1] + 1; chess.KingPos[PlayerIndex, 0] = x2; chess.KingPos[PlayerIndex, 1] = y2; // Castling if (((y2 - y1) * (y2 - y1) == 4)) { int xr = x1, yr1 = (y2 < y1) ? 0 : 7, yr2 = (yr1 == 0) ? 3 : 5; chess.Board[xr, yr1] = ChessBoard.Empty; chess.Board[xr, yr2] = (PlayerIndex == ChessBoard.WhitePlayerIndex) ? ChessBoard.Rook : ChessBoard.Rook + 6; chess.Step[PlayerIndex, xr, yr2] = chess.Step[PlayerIndex, xr, yr1] + 1; } } else if (pawn == ChessBoard.Pawn + color) { // en passant if (y1 != y2 && ((chess.Board[x1, y2] == ChessBoard.Pawn && PlayerIndex == ChessBoard.BlackPlayerIndex) || (chess.Board[x1, y2] == ChessBoard.Pawn + 6 && PlayerIndex == ChessBoard.WhitePlayerIndex)) && chess.History.Last().Item2 == ChessBoard.Convert(x1 + (PlayerIndex == ChessBoard.BlackPlayerIndex ? -2 : 2), y2, x1, y2)) { chess.Board[x1, y2] = ChessBoard.Empty; } chess.Board[x2, y2] = pawn; chess.Step[PlayerIndex, x2, y2] = chess.Step[PlayerIndex, x1, y1] + 1; // Promo Queen if ((PlayerIndex == ChessBoard.WhitePlayerIndex && x2 == ChessBoard.WhiteRank) || (PlayerIndex == ChessBoard.BlackPlayerIndex && x2 == ChessBoard.BlackRank)) { chess.Board[x2, y2] = ChessBoard.Queen + color; chess.Step[PlayerIndex, x2, y2] = chess.Step[PlayerIndex, x1, y1] + 1; } } else { chess.Board[x2, y2] = pawn; chess.Step[PlayerIndex, x2, y2] = chess.Step[PlayerIndex, x1, y1] + 1; } if (!SetControl(ref chess)) { return(false); } if (!chess.IsCheck(PlayerIndex)) { if (save == true) { chess.CurrentPlayerIndex ^= 1; chess.History.Add(new Tuple <int, string>(pawn, move)); if (!Save(ref chess)) { return(false); } } return(true); } else { return(false); } } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }
private async Task <bool> Host() { try { IEnumerable <IMessage> print; ChessBoard chess; while (true) { chess = Load(); if (HasNoMove(chess.CurrentPlayerIndex)) { if (chess.IsCheck(chess.CurrentPlayerIndex)) { chess.SetGameResult(HasNoMove: true, chess.Player[chess.CurrentPlayerIndex ^ 1]); } else { chess.SetGameResult(HasNoMove: true); } Save(ref chess); await Print(); break; } print = await Print(); SocketMessage msg; Stopwatch s = new Stopwatch(); s.Start(); do { msg = await NextMessageAsync(fromSourceUser : false, inSourceChannel : true, timeout : TimeSpan.FromMinutes(5)); if (msg == null) { return(false); } if (msg.Author.Id == chess.Player[chess.CurrentPlayerIndex] && IsValidMessage(msg.Content)) { break; } } while (s.Elapsed < TimeSpan.FromMinutes(5)); s.Stop(); string move = msg.Content.Substring(5); if (move == "pause") { break; } else if (move == "draw") { ulong AskedPlayer = chess.Player[chess.CurrentPlayerIndex ^ 1]; await DiscordWrapper.SendMessage(Context, $"{MentionUtils.MentionUser(AskedPlayer)}, bạn có đồng ý hoà ván đấu này? (Yes/No)"); string content = null; SocketMessage msg_draw; s = new Stopwatch(); s.Start(); do { msg_draw = await NextMessageAsync(fromSourceUser : false, inSourceChannel : true, timeout : TimeSpan.FromMinutes(5)); if (msg_draw == null) { break; } content = msg_draw.Content.ToLower(); if (msg_draw.Author.Id == AskedPlayer && (content == "yes" || content == "no")) { break; } } while (s.Elapsed < TimeSpan.FromMinutes(5)); if (msg_draw == null) { await DiscordWrapper.SendMessage(Context, $"Người chơi {MentionUtils.MentionUser(AskedPlayer)} không phản hồi, trò chơi sẽ tiếp tục."); } else if (content == "no") { await DiscordWrapper.SendMessage(Context, $"Người chơi {MentionUtils.MentionUser(AskedPlayer)} không chấp nhận hoà, trò chơi sẽ tiếp tục."); } else { chess.SetGameResult(HasNoMove: false); Save(ref chess); await Print(); break; } } else if (move == "forfeit" || move == "surrender") { chess.SetGameResult(HasNoMove: false, chess.Player[chess.CurrentPlayerIndex ^ 1]); Save(ref chess); await Print(); break; } else if (!IsValidMove(move) || !await Move(move, Context.Channel)) { var embed = new EmbedBuilder { Description = $"{MentionUtils.MentionUser(chess.Player[chess.CurrentPlayerIndex])}, Nước đi {move} của bạn không hợp lệ. Hãy thử lại.", Color = Color.Magenta }; await Context.Channel.TriggerTypingAsync(); await ReplyAndDeleteAsync(content : null, embed : embed.Build(), timeout : TimeSpan.FromSeconds(5)); } await(Context.Channel as ITextChannel).DeleteMessagesAsync(print); } chess = Load(); return(chess.IsOver); } catch (Exception e) { DiscordWrapper.Log($"{log} {e}"); return(false); } }