daily pastebin goal
32%
SHARE
TWEET

Untitled

a guest May 19th, 2017 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Xml;
  7. using System.Xml.XPath;
  8. using MafiaSharp;
  9. using Hash.Chat;
  10. using Hash.Processing;
  11. using System.Timers;
  12.  
  13. namespace Hash.Mafia {
  14.     [Module("Mafia")]
  15.     public sealed class MafiaModule : CommandModule {
  16.  
  17.         // XML message store stuff
  18.  
  19.         private static readonly XmlDocument messageStore = InitializeXmlStore();
  20.  
  21.         private static XmlDocument InitializeXmlStore() {
  22.             XmlDocument store = new XmlDocument();
  23.             store.LoadXml(Resources.MafiaMessages);
  24.             return store;
  25.         }
  26.  
  27.         private string GetMessage(string path) {
  28.             string reply = messageStore.SelectSingleNode("root").SelectSingleNode(path).InnerText;
  29.             return reply;
  30.         }
  31.  
  32.         // Fields
  33.  
  34.         private Game currentGame;
  35.         private TimedHandleList handles;
  36.         private GameSetup defaultSetup;
  37.         private TimedChecklist checklist;
  38.         private Dictionary<string, PlayerContext> queryContexts;
  39.         private Dictionary<string, TeamContext> teamContexts;
  40.         private IrcChannel mainChannel;
  41.         private IrcNetwork network;
  42.  
  43.         // Constructor
  44.  
  45.         public MafiaModule() {
  46.             this.currentGame = new Game();
  47.             this.handles = new TimedHandleList();
  48.             this.defaultSetup = GameSetup.DefaultSetup;
  49.         }
  50.  
  51.         // Methods
  52.  
  53.         public override MessageResponse ProcessMessage(int messageID) {
  54.             return base.ProcessMessage(messageID);
  55.         }
  56.  
  57.  
  58.         private void InitializeGame() {
  59.             this.currentGame = new Game();
  60.             this.handles = new TimedHandleList();
  61.             this.mainChannel.SetTopic(GetMessage("stateChange/idle/topic"));
  62.         }
  63.  
  64.         private void EndGame() {
  65.             if (this.teamContexts != null) {
  66.                 foreach(var context in teamContexts.Keys) {
  67.                     InstanceManager.Instance.GetInstanceByID(this.network.ID).Send(new IrcPartCommand(context));
  68.                 }
  69.             }
  70.             this.teamContexts = null;
  71.             this.queryContexts = null;
  72.         }
  73.  
  74.         private void InitStarting(IrcChannel context) {
  75.             this.currentGame.Status = GameStatus.Starting;
  76.             this.currentGame.InitStarting();
  77.  
  78.             this.mainChannel = context;
  79.             this.mainChannel.BroadcastToUsers(new IrcModeCommand(this.mainChannel.Name, "-v [@context.user]"));
  80.             this.mainChannel.OnUserEnter += ProcessUserEnterMainChannel;
  81.             this.mainChannel.OnUserLeave += ProcessUserLeaveMainChannel;
  82.             this.network = InstanceManager.Instance.GetNetworkByID(context.NetworkID);
  83.  
  84.             this.queryContexts = new Dictionary<string, PlayerContext>();
  85.             this.teamContexts = new Dictionary<string, TeamContext>();
  86.         }
  87.  
  88.         protected override bool Dispose(bool disposing) {
  89.             if (base.Dispose(disposing)) {
  90.                 this.mainChannel.OnUserEnter -= ProcessUserEnterMainChannel;
  91.                 this.mainChannel.OnUserLeave -= ProcessUserLeaveMainChannel;
  92.                 return true;
  93.             }
  94.             return false;
  95.         }
  96.  
  97.         private void ProcessUserEnterMainChannel(object sender, IrcUserEventArgs e) {
  98.             IrcUser user = e.User;
  99.         }
  100.  
  101.         private void ProcessUserLeaveMainChannel(object sender, IrcUserEventArgs e) {
  102.         }
  103.  
  104.  
  105.         private void InitSetup() {
  106.             currentGame.Status = GameStatus.Setup;
  107.             currentGame.InitSetup();
  108.             PlayerCollection players = this.currentGame.Players;
  109.             foreach (string handle in handles) {
  110.                 players.AddPlayer(handle);
  111.                 players[handle].UpdateState(PlayerState.Playing);
  112.             }
  113.             this.defaultSetup.InjectIntoPlayerCollection(players);
  114.             var roles = players.GetRolesWhere(role => role != MafiaSharp.Roles.TownieRole.Instance);
  115.             var loners = roles.Where(role => !role.IsTeamRole);
  116.             foreach (var pair in loners.ToDictionary(role => players.Single(player => player.HasRole(role)).Handle, role => role)) {
  117.                 this.queryContexts.Add(pair.Key, new PlayerContext(pair.Value, pair.Key));
  118.             }
  119.  
  120.             var teams = roles.Where(role => role.IsTeamRole);
  121.             int random = new Random().Next(0, 1000);
  122.             foreach (var teamRole in teams) {
  123.                 List<string> teamMembers = players.SelectByRole(teamRole).Select(player => player.Handle).ToList();
  124.                 string channelName = "#" + teamRole.Name + (random + teamRole.Faction);
  125.                 TeamContext currentTeamContext = new TeamContext(teamRole, teamMembers);
  126.                 this.network.EventManager.SubscribeToUserJoin(channelName, HandleTeamChannelUserJoin);
  127.                 this.network.EventManager.SubscribeToSelfJoin(channelName, HandleTeamChannelSelfJoin);
  128.                 InstanceManager.Instance.GetInstanceByID(this.network.ID).Send(new IrcJoinCommand(channelName));
  129.                 this.teamContexts.Add(channelName, currentTeamContext);
  130.             }
  131.             this.mainChannel.SetTopic(GetMessage("stateChange/setup/topic"));
  132.         }
  133.  
  134.         private void HandleTeamChannelSelfJoin(object sender, IrcChannelEventArgs e) {
  135.             e.Channel.SetMode("+si");
  136.             TeamContext team = this.teamContexts[e.Channel.Name];
  137.             team.Checklist.Initialize();
  138.             var teamUsers = this.network.Users.Where(user => user.IsLoggedIn &&
  139.                 team.Members.Contains(user.Username));
  140.             this.network.BroadcastToUsers(teamUsers,
  141.                 new IrcPrivmsgCommand("[@context.user]", Utils.Color(ColorCode.RoyalBlue, team.Role.RoleDescription)));
  142.             this.network.BroadcastToUsers(teamUsers,
  143.                 new IrcPrivmsgCommand("[@context.user]", Utils.Color(ColorCode.RoyalBlue, team.Role.ActionDescription)));
  144.             this.network.BroadcastToUsers(teamUsers,
  145.                 new IrcInviteCommand("[@context.user]", e.Channel.Name));
  146.         }
  147.  
  148.         private void HandleTeamChannelUserJoin(object sender, IrcUserChannelEventArgs e) {
  149.             TeamContext context = this.teamContexts[e.Channel.Name];
  150.             context.Checklist.Check(e.User.Username);
  151.         }
  152.  
  153.         // Module commands
  154.  
  155.         [Command("aye", "", IrcContextType.Channel, Hash.Data.AccessLevel.None)]
  156.         private MessageResponse AyeCommand(int messageID, string[] arguments) {
  157.             IrcUser user = MessageManager.Instance[messageID].User;
  158.             switch (currentGame.Status) {
  159.                 case GameStatus.Starting:
  160.                     if (user.IsLoggedIn) {
  161.                         if (handles.Add(user.Username)) {
  162.                             this.network.BroadcastToUsers(receiver => (receiver.UserID == user.UserID),
  163.                                 new IrcModeCommand(mainChannel.Name, "+v [@context.user]"));
  164.                             return new MessageResponse(messageID, CommandStatus.NullResponse, "Broadcasted command.");
  165.                         } else {
  166.                             return new MessageResponse(messageID, CommandStatus.LogicError,
  167.                                 new IrcNoticeCommand("[@context.user]", "You are already playing."));
  168.                         }
  169.                     } else {
  170.                         return new MessageResponse(messageID, CommandStatus.LogicError, new IrcNoticeCommand("[@context.user]",
  171.                             "You need to log in to play. Please PM me with [$c=Brown|\"[$b|login] <username> <password>\"] to log in. " +
  172.                             "If you don't have an account you can register one with the command [$c=Brown|\"[$b|register] <username> <password>\"]. "));
  173.                     }
  174.                 case GameStatus.Setup:
  175.                     bool done = this.checklist.Check(user.Username);
  176.                     if (done) return AdvanceGameStatus(messageID, arguments);
  177.                     else return new MessageResponse(messageID, CommandStatus.NullResponse, "User is active.");
  178.                 default:
  179.                     return new MessageResponse(messageID, CommandStatus.UnknownCommand, "This command is invalid in the current context.");
  180.             }
  181.         }
  182.  
  183.         [Command("watching", "", IrcContextType.Channel, Hash.Data.AccessLevel.User)]
  184.         private MessageResponse WatchingCommand(int messageID, string[] arguments) {
  185.             IrcUser user = MessageManager.Instance[messageID].User;
  186.             if (currentGame.Status == GameStatus.Starting) {
  187.                 if (handles.Remove(user.Username)) {
  188.                     this.network.BroadcastToUsers(receiver => (receiver.UserID == user.UserID),
  189.                         new IrcModeCommand(mainChannel.Name, "-v [@context.user]"));
  190.                     return new MessageResponse(messageID, CommandStatus.NullResponse, "Broadcasted command.");
  191.                 } else {
  192.                     return new MessageResponse(messageID, CommandStatus.LogicError, "You are not in the player list.");
  193.                 }
  194.             } else {
  195.                 return new MessageResponse(messageID, CommandStatus.UnknownCommand, "This command is invalid in the current context.");
  196.             }
  197.         }
  198.  
  199.         [Command("start", "", IrcContextType.Channel, Data.AccessLevel.User)]
  200.         private MessageResponse StartGameCommand(int messageID, string[] arguments) {
  201.             if (currentGame.Status == GameStatus.Idle) {
  202.                 return AdvanceGameStatus(messageID, arguments);
  203.             } else {
  204.                 return new MessageResponse(messageID, CommandStatus.LogicError,
  205.                     new IrcNoticeCommand("[@context.user]", "The game has already started"));
  206.             }
  207.         }
  208.  
  209.         [Command("advance", "", IrcContextType.Channel, Data.AccessLevel.Owner)]
  210.         private MessageResponse AdvanceGameStatus(int messageID, string[] arguments) {
  211.             string reply = String.Empty;
  212.             switch (currentGame.Status) {
  213.                 case GameStatus.Idle:
  214.                     this.InitStarting((IrcChannel) MessageManager.Instance[messageID].Source);
  215.                     this.mainChannel.SetTopic(GetMessage("stateChange/starting/topic"));
  216.                     reply = GetMessage("stateChange/starting/channel");
  217.                     break;
  218.                 case GameStatus.Starting:
  219.                     this.InitSetup();
  220.                     reply = GetMessage("stateChange/setup/channel");
  221.                     break;
  222.                 case GameStatus.Setup:
  223.                     currentGame.Status = GameStatus.Running;
  224.                     currentGame.InitRunning();
  225.                     reply = GetMessage("stateChange/running/channel");
  226.                     checklist = new TimedChecklist(handles.ToList());
  227.                     checklist.Initialize();
  228.                     break;
  229.                 case GameStatus.Running:
  230.                     currentGame.Status = GameStatus.Over;
  231.                     break;
  232.                 case GameStatus.Over:
  233.                     InitializeGame();
  234.                     break;
  235.                 default:
  236.                     break;
  237.             }
  238.             if (String.IsNullOrEmpty(reply)) {
  239.                 return new MessageResponse(messageID, CommandStatus.Success, Utils.GetFormattedString(
  240.                     "The game status is now '{0}'", Enum.GetName(typeof(GameStatus), currentGame.Status)));
  241.             } else {
  242.                 return new MessageResponse(messageID, CommandStatus.Success, reply);
  243.             }
  244.         }
  245.  
  246.         [Command("endthis", "", IrcContextType.Channel, Data.AccessLevel.Owner)]
  247.         private MessageResponse EndGameCommand(int messageID, string[] arguments) {
  248.             if (this.currentGame.Status != GameStatus.Idle) {
  249.                 EndGame();
  250.                 InitializeGame();
  251.                 return new MessageResponse(messageID, CommandStatus.NullResponse, "Game reinitialized.");
  252.             } else {
  253.                 return new MessageResponse(messageID, CommandStatus.LogicError, "No game currently running.");
  254.             }
  255.         }
  256.     }
  257. }
RAW Paste Data
Top