Exemplo n.º 1
0
        /*
         * Fetch all players from the database and rturn the resulant playerList object
         */
        public PlayerCollection getPlayers()
        {
            PlayerCollection playerList = new PlayerCollection();
            const string selectStatement = "SELECT * FROM player";

            cmd = new SqlCommand(selectStatement, conn);
            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (reader.Read())
                    playerList.Add(new Player(reader["playerName"].ToString(), (int)reader["rating"], (int)reader["wins"], (int)reader["losses"], (int)reader["draws"], (int)reader["id"]));

                reader.Close();
            }
            catch (SqlException)
            {
            }
            finally
            {
                conn.Close();
            }

            return playerList;
        }
Exemplo n.º 2
0
 public Game(SerializationInfo info, StreamingContext context)
 {
     CombatLocations = (LocationCollection)info.GetValue("CombatLocations", typeof(LocationCollection));
     StarSystems = (StarSystemCollection)info.GetValue("StarSystems", typeof(StarSystemCollection));
     Players = (PlayerCollection)info.GetValue("Players", typeof(PlayerCollection));
     ExistingHulls = (List<ShipHull>)info.GetValue("ExistingHulls", typeof(List<ShipHull>));
     ExistingParts = (List<EidosPart>)info.GetValue("ExistingParts", typeof(List<EidosPart>));
     ExistingShips = (List<Ship>)info.GetValue("ExistingShips", typeof(List<Ship>));
 }
Exemplo n.º 3
0
 /*
  * Fetch all players from the database and store them in the playerList object
  * passed in by reference
  */
 public PlayerCollection getPlayers()
 {
     XmlDocument doc = GetFile(fullPath);
     PlayerCollection list = new PlayerCollection();
     foreach (XmlElement elem in doc.DocumentElement.ChildNodes)
     {
         list.Add(FromElement(elem));
     }
     return list;
 }
Exemplo n.º 4
0
        public GameOverview(GameSettings settings = null)
        {
            if (settings == null)
            {
                settings = new GameSettings();
            }

            Settings = settings;
            Players = new PlayerCollection();
            Status = GameStatus.WaitingForPlayers;
        }
        public PlayerCollection<Player> CreatePlayerCollection()
        {
            var players = new PlayerCollection<Player>();

            for (int i = 0; i < 15; i++)
            {
                players.Add(new Player(i, "PlayerKey_" + i, "Player " + i, "Status_" + i, null, null));
            }

            return players;
        }
Exemplo n.º 6
0
        public Table(int playerCount, AppSettings settings)
        {
            TotalRounds = 0;

            ButtonPlayerPrev = -999;
            _random = new Random();
            ShortButton1 = settings.ShortButtonRect1;
            ShortButton2 = settings.ShortButtonRect2;
            ShortButton3 = settings.ShortButtonRect3;
            ShortButton4 = settings.ShortButtonRect4;

            CardSuitRect = settings.CardSuitRect;
            CardRankRect = settings.CardRankRect;
            CardMinSize = (int)settings.MinCardSize;

            BetCounterPreFlop = 1;
            BetCounterFlop = 1;
            BetCounterTurn = 1;
            BetCounterRiver = 1;
            RaiseCounter = 0;

            PlayerActionCounter = 0;

            PlayerRects = new List<Rectangle>();
            PlayerFolds = new List<Rectangle>();
            ButtonRects = new List<Rectangle>();
            BetRects = new List<Rectangle>();

            Players = new PlayerCollection();
            DealerButtons = new List<bool>();
            PlayerBets = new List<PlayerBet>();

            MyBalance = new Player();
            Bank = new Bank();

            for (int i = 0; i < playerCount; i++)
            {
                Players.Add(new Player {Action = PlayerAction.Init});
            }

            for (int i = 0; i < playerCount; i++)
            {
                DealerButtons.Add(false);
            }

            for (int i = 0; i < playerCount; i++)
            {
                PlayerBets.Add(new PlayerBet());
            }

            _cardRecognizer = new CardRecognizer();
        }
Exemplo n.º 7
0
        protected GameManager()
        {
            Players = new PlayerCollection();

            WallList = new List<Wall>();
            PowerUpList = new List<PowerUp>();
            BombList = new List<Bomb>();

            _currentMap = new Map();
            BaseCurrentMap = _currentMap;

            _gameStopWatch = TimeSpan.Zero;

            _gameTime = new GameTime();
        }
Exemplo n.º 8
0
        public GeneralStats(Demo demo)
            : base(demo)
        {
            m_GameEventHandlers = new Dictionary<string, OnGameEvent>();

            m_GameEventHandlers.Add("flashbang_detonate", new OnGameEvent(FlashbangDetonate));
            m_GameEventHandlers.Add("player_blind", new OnGameEvent(PlayerBlind));
            m_GameEventHandlers.Add("player_connect", new OnGameEvent(PlayerConnect));
            m_GameEventHandlers.Add("player_connect_full", new OnGameEvent(PlayerConnectFull));
            m_GameEventHandlers.Add("player_death", new OnGameEvent(PlayerDeath));
            m_GameEventHandlers.Add("player_disconnect", new OnGameEvent(PlayerDisconnect));
            m_GameEventHandlers.Add("player_team", new OnGameEvent(PlayerTeam));

            m_Players = new PlayerCollection(demo);
        }
Exemplo n.º 9
0
        /*
         * Fetch all players from the database and store them in the playerList object
         * passed in by reference
         */
        public PlayerCollection getPlayers()
        {
            PlayerCollection playerList = new PlayerCollection();

            if (File.Exists(this.fullPath))
            {
                byte[] fileContents = File.ReadAllBytes(this.fullPath);
                Player currPlayer = null;
                int currIndex = 0;

                while ((currPlayer = Player.FromBytes(fileContents, ref currIndex)) != null)
                    playerList.Add(currPlayer);
            }

            return playerList;
        }
Exemplo n.º 10
0
        public Main()
        {
            InitializeComponent();

            IPlayerDB db = GetPlayerIO();
            this.playerList = db.getPlayers();

            foreach (Player p in this.playerList)
            {
                cmbPlayer1.Items.Add(p);
                cmbPlayer2.Items.Add(p);
            }

            #if DEBUG
            if (this.playerList.Count > 1)
            {
                cmbPlayer1.SelectedIndex = 0;
                cmbPlayer2.SelectedIndex = 1;
            }
            #endif
        }
Exemplo n.º 11
0
        /// <summary>
        /// Parses the raw binary data for use within TQVault
        /// </summary>
        private void ParseRawData(PlayerCollection pc)
        {
            // First create a memory stream so we can decode the binary data as needed.
            using (MemoryStream stream = new MemoryStream(pc.rawData, false))
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    // Find the block pairs until we find the block that contains the item data.
                    int blockNestLevel  = 0;
                    int currentOffset   = 0;
                    int itemOffset      = 0;
                    int equipmentOffset = 0;

                    // vaults start at the item data with no crap
                    bool foundItems     = pc.IsVault;
                    bool foundEquipment = pc.IsVault;

                    while ((!foundItems || !foundEquipment) && (currentOffset = FindNextBlockDelim(pc, currentOffset)) != -1)
                    {
                        if (pc.rawData[currentOffset] == beginBlockPattern[0])
                        {
                            // begin block
                            ++blockNestLevel;
                            currentOffset += beginBlockPattern.Length;

                            // skip past the 4 bytes of noise after begin_block
                            currentOffset += 4;

                            // Seek our stream to the correct position
                            stream.Seek(currentOffset, SeekOrigin.Begin);

                            // Now get the string for pc block
                            string blockName = TQData.ReadCString(reader).ToUpperInvariant();

                            // Assign loc to our new stream position
                            currentOffset = (int)stream.Position;

                            // See if we accidentally got a begin_block or end_block
                            if (blockName.Equals("BEGIN_BLOCK"))
                            {
                                blockName      = "(NONAME)";
                                currentOffset -= beginBlockPattern.Length;
                            }
                            else if (blockName.Equals("END_BLOCK"))
                            {
                                blockName      = "(NONAME)";
                                currentOffset -= endBlockPattern.Length;
                            }
                            else if (blockName.Equals("ITEMPOSITIONSSAVEDASGRIDCOORDS"))
                            {
                                currentOffset += 4;
                                itemOffset     = currentOffset;                     // skip value for itemPositionsSavedAsGridCoords
                                foundItems     = true;
                            }
                            else if (blockName.Equals("USEALTERNATE"))
                            {
                                currentOffset  += 4;
                                equipmentOffset = currentOffset;                         // skip value for useAlternate
                                foundEquipment  = true;
                            }
                        }
                        else
                        {
                            // end block
                            --blockNestLevel;
                            currentOffset += endBlockPattern.Length;
                        }
                    }

                    if (foundItems)
                    {
                        try
                        {
                            ParseItemBlock(pc, itemOffset, reader);
                        }
                        catch (ArgumentException exception)
                        {
                            var ex = new ArgumentException($"Error parsing player file Item Block- '{pc.PlayerName}'", exception);
                            Log.ErrorException(ex);
                            throw ex;
                        }
                    }

                    // Process the equipment block
                    if (foundEquipment && !pc.IsVault)
                    {
                        try
                        {
                            ParseEquipmentBlock(pc, equipmentOffset, reader);
                        }
                        catch (ArgumentException exception)
                        {
                            var ex = new ArgumentException($"Error parsing player file Equipment Block - '{pc.PlayerName}'", exception);
                            Log.ErrorException(ex);
                            throw ex;
                        }
                    }

                    if (pc.IsPlayer)
                    {
                        try
                        {
                            pc.PlayerInfo = ReadPlayerInfo(pc);
                        }
                        catch (ArgumentException ex)
                        {
                            var exx = new ArgumentException($"Error parsing player player info Block - '{pc.PlayerName}'", ex);
                            Log.ErrorException(exx);
                            throw exx;
                        }
                    }
                }
        }
Exemplo n.º 12
0
        public GameServer()
        {
            Channels = new ChannelCollection();
            Rooms = new RoomCollection();
            Players = new PlayerCollection();
            Logger = new Logger() { WriteToConsole = true };
            _packetLogger = new PacketLogger();
            Logger.Load(Path.Combine("logs", string.Format("game_{0}.log", DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss"))));
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                Error(s, new ExceptionEventArgs((Exception)e.ExceptionObject));
                Environment.Exit(0);
            };

            _packetLogger.Load("game_packets.log");

            Logger.Info("Loading game_config.xml...");
            GameConfig.Load();
            Logger.Info("Setting up servers...");
            _server = new TcpServer(IPAddress.Parse(GameConfig.Instance.IP), GameConfig.Instance.Port);
            _server.PacketReceived += HandlePacket;
            _server.ClientDisconnected += ClientDisconnected;
            _server.Error += Error;

            var isMono = Type.GetType("Mono.Runtime") != null;
            switch (GameConfig.Instance.AuthRemote.Binding)
            {
                case "pipe":
                    if (isMono)
                    {
                        Logger.Error("pipe is not supported in mono, use http!");
                        Environment.Exit(1);
                        return;
                    }
                    _authRemoteClient = new RemoteClient(ERemoteBinding.Pipe, string.Format("localhost/AuthServer/{0}/", SHA256.ComputeHash(GameConfig.Instance.AuthRemote.Password)));
                    break;

                case "tcp":
                    if (isMono)
                    {
                        Logger.Error("pipe is not supported in mono, use http!");
                        Environment.Exit(1);
                        return;
                    }
                    _authRemoteClient = new RemoteClient(ERemoteBinding.Pipe, string.Format("{0}:{1}/AuthServer/{2}/", GameConfig.Instance.AuthRemote.Server, GameConfig.Instance.AuthRemote.Port, SHA256.ComputeHash(GameConfig.Instance.AuthRemote.Password)));
                    break;

                case "http":
                    _authRemoteClient = new RemoteClient(ERemoteBinding.Http, string.Format("{0}:{1}/AuthServer/{2}/", GameConfig.Instance.AuthRemote.Server, GameConfig.Instance.AuthRemote.Port, SHA256.ComputeHash(GameConfig.Instance.AuthRemote.Password)));
                    break;

                default:
                    Logger.Error("Invalid remote binding '{0}' for AuthRemote", GameConfig.Instance.AuthRemote.Binding);
                    Environment.Exit(1);
                    break;
            }

            Logger.Info("Loading plugins... {0}",AppDomain.CurrentDomain.BaseDirectory);
            _pluginManager.Load();

            foreach (var plugin in _pluginManager.Plugins)
                Logger.Info("Loaded {0}", plugin.Name);
        }
Exemplo n.º 13
0
		protected virtual void Dispose(bool disposing)
		{
			// Check to see if Dispose has already been called.
			if (!this.disposed)
			{
				// If disposing equals true, dispose all managed
				// and unmanaged resources.
				if (disposing)
				{
					// Dispose managed resources.
					this._ActivePlayer = null;
					this._CardsAvailable = null;
					this._MessageRequestQueue = null;
					this._MessageResponseQueue = null;
					this._Players = null;
					this._RNG = null;
					this._Table = null;
					this._TurnsTaken = null;
				}

				// Call the appropriate methods to clean up
				// unmanaged resources here.
				// If disposing is false,
				// only the following code is executed.

				// Note disposing has been done.
				disposed = true;
			}
		}
Exemplo n.º 14
0
		public Ethic()
		{
			m_Players = new PlayerCollection();
		}
Exemplo n.º 15
0
 public override void DisplayKingsReward( PlayerCollection players )
 {
     //Displays the confirmation that the players in the playerlist have received a 1VP bonus.
     switch( this.Mode )
     {
         case graphicsMode.CLI:
             foreach( Player p in players )
             {
                 Console.WriteLine( "{0} receives the King's reward of 1 Victory Point.", p.Name );
             }
             break;
         case graphicsMode.GUI:
             throw new NotImplementedException();
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Commits the player info changes to the player.chr file
        /// </summary>
        /// <param name="playerInfo"></param>
        /// <param name="playerFileRawData"></param>
        public void Commit(PlayerCollection pc)
        {
            TQData.WriteIntAfter(pc.rawData, "playerLevel", pc.PlayerInfo.CurrentLevel);

            TQData.WriteIntAfter(pc.rawData, "money", pc.PlayerInfo.Money);

            TQData.WriteIntAfter(pc.rawData, "masteriesAllowed", pc.PlayerInfo.MasteriesAllowed);

            // first "temp" / first "block"
            var difficultyUnlocked = TQData.WriteIntAfter(pc.rawData, "temp", pc.PlayerInfo.DifficultyUnlocked);

            TQData.WriteIntAfter(pc.rawData, "currentStats.charLevel", pc.PlayerInfo.CurrentLevel);

            TQData.WriteIntAfter(pc.rawData, "currentStats.experiencePoints", pc.PlayerInfo.CurrentXP);

            TQData.WriteIntAfter(pc.rawData, "modifierPoints", pc.PlayerInfo.AttributesPoints);

            TQData.WriteIntAfter(pc.rawData, "skillPoints", pc.PlayerInfo.SkillPoints);

            var baseStrength     = TQData.WriteFloatAfter(pc.rawData, "temp", pc.PlayerInfo.BaseStrength, difficultyUnlocked.nextOffset);
            var baseDexterity    = TQData.WriteFloatAfter(pc.rawData, "temp", pc.PlayerInfo.BaseDexterity, baseStrength.nextOffset);
            var baseIntelligence = TQData.WriteFloatAfter(pc.rawData, "temp", pc.PlayerInfo.BaseIntelligence, baseDexterity.nextOffset);
            var baseHealth       = TQData.WriteFloatAfter(pc.rawData, "temp", pc.PlayerInfo.BaseHealth, baseIntelligence.nextOffset);
            var baseMana         = TQData.WriteFloatAfter(pc.rawData, "temp", pc.PlayerInfo.BaseMana, baseHealth.nextOffset);

            if (pc.PlayerInfo.MasteriesAllowed_OldValue.HasValue && pc.PlayerInfo.MasteriesAllowed < pc.PlayerInfo.MasteriesAllowed_OldValue ||
                pc.PlayerInfo.MasteriesResetRequiered)
            {
                pc.PlayerInfo.ResetMasteries();

                #region Override skill lines block after reset

                // Find skill section boundaries
                var firstblock       = TQData.ReadIntAfter(pc.rawData, "begin_block");
                var secondblock      = TQData.ReadIntAfter(pc.rawData, "begin_block", firstblock.nextOffset);
                var max              = TQData.ReadIntAfter(pc.rawData, "max", secondblock.nextOffset);      // Boundary top
                var end_block        = TQData.ReadIntAfter(pc.rawData, "end_block", max.nextOffset);
                var masteriesAllowed = TQData.ReadIntAfter(pc.rawData, "masteriesAllowed", max.nextOffset); // Boundary bottom

                // Split file
                var startfile = pc.rawData.Take(max.nextOffset).ToArray();
                var endfile   = pc.rawData.Skip(masteriesAllowed.indexOf - 4).ToArray();               // -4 include key name length

                // make binary section
                var section = pc.PlayerInfo.SkillRecordList.SelectMany(s => s.ToBinary(secondblock.valueAsInt, end_block.valueAsInt)).ToArray();

                // put pieces back together
                pc.rawData = new[] {
                    startfile,
                    section,
                    endfile,
                }.SelectMany(a => a).ToArray();

                // Adjust "max" value
                var found = TQData.WriteIntAfter(pc.rawData, "max", pc.PlayerInfo.SkillRecordList.Count, max.indexOf);

                // Adjust "skillPoints"
                var skillpointsToRestore = pc.PlayerInfo.ReleasedSkillPoints;

                if (skillpointsToRestore > 0)
                {
                    TQData.WriteIntAfter(pc.rawData, "skillPoints", pc.PlayerInfo.SkillPoints + skillpointsToRestore);
                }

                #endregion
            }

            //if this value is set to true, the TQVaultAE program will know save the player.chr file
            pc.PlayerInfo.Modified = true;
        }
Exemplo n.º 17
0
 public abstract void DisplayPlayerOrder(PlayerCollection order);
Exemplo n.º 18
0
        /// <summary>
        /// Updates the list of client names in the window
        /// </summary>
        /// <param name="players">The list of players to add</param>
        public void UpdateClientList(List<Player> players)
        {
            if (InvokeRequired)
            {
                Invoke(new PlayerListCallback(UpdateClientList), players);
            }
            else
            {

                if (dgvPlayers.DataSource == null)
                    dgvPlayers.DataSource = pc;

                string selected = null;
                if (pc.Count > 0 && dgvPlayers.SelectedRows.Count > 0)
                {
                    selected = (from DataGridViewRow row in dgvPlayers.Rows where row.Selected select pc[row.Index]).First().name;
                }

                dgvPlayers.SuspendLayout();

                pc = new PlayerCollection(new PlayerListView());
                Player.players.ForEach(p => pc.Add(p));

                dgvPlayers.Invalidate();
                dgvPlayers.DataSource = pc;
                if (selected != null)
                {
                    foreach (Player t in Player.players)
                        for (int j = 0; j < dgvPlayers.Rows.Count; j++)
                            if (Equals(dgvPlayers.Rows[j].Cells[0].Value, selected))
                                dgvPlayers.Rows[j].Selected = true;
                }

                dgvPlayers.Refresh();
                dgvPlayers.ResumeLayout();
            }
        }
Exemplo n.º 19
0
 public Controller()
 {
     Players = new PlayerCollection();
 }
 public static bool HasYears(this PlayerCollection <LifeCardGamePlayerItem> thisList)
 {
     return(thisList.Any(thisPlayer => thisPlayer.MainHandList.Any(thisCard => thisCard.Points == 0)));
 }
Exemplo n.º 21
0
        /// <summary>
        /// Searches all loaded player files
        /// </summary>
        /// <param name="predicate">Predicate that the items should match</param>
        /// <param name="quality">Quality filter</param>
        /// <param name="searchByType">flag for whether we are searching by type or name</param>
        /// <param name="results">List holding the search results.</param>
        private void SearchPlayers(IItemPredicate predicate, List <Result> results)
        {
            if (this.UserContext.Players == null || this.UserContext.Players.Count == 0)
            {
                return;
            }

            foreach (KeyValuePair <string, PlayerCollection> kvp in this.UserContext.Players)
            {
                string           playerFile = kvp.Key;
                PlayerCollection player     = kvp.Value;

                if (player == null)
                {
                    // Make sure the name is valid and we have a player.
                    Log.DebugFormat(CultureInfo.InvariantCulture, "playerFile={0} returned null player.", playerFile);
                    continue;
                }

                string playerName = GetNameFromFile(playerFile);
                if (playerName == null)
                {
                    Log.DebugFormat(CultureInfo.InvariantCulture, "playerFile={0} returned null playerName.", playerFile);
                    continue;
                }

                int sackNumber = -1;
                foreach (SackCollection sack in player)
                {
                    sackNumber++;
                    if (sack == null)
                    {
                        Log.DebugFormat(CultureInfo.InvariantCulture, "playerFile={0}", playerFile);
                        Log.DebugFormat(CultureInfo.InvariantCulture, "sack({0}) returned null.", sackNumber);
                        continue;
                    }

                    // Query the sack for the items containing the search string.
                    foreach (var fnames in QuerySack(predicate, sack))
                    {
                        results.Add(new Result(
                                        playerFile,
                                        playerName,
                                        sackNumber,
                                        SackType.Player,
                                        fnames
                                        ));
                    }
                }

                // Now search the Equipment panel
                SackCollection equipmentSack = player.EquipmentSack;
                if (equipmentSack == null)
                {
                    Log.DebugFormat(CultureInfo.InvariantCulture, "playerFile={0} Equipment Sack returned null.", playerFile);
                    continue;
                }

                foreach (var fnames in QuerySack(predicate, equipmentSack))
                {
                    results.Add(new Result(
                                    playerFile,
                                    playerName,
                                    0,
                                    SackType.Equipment,
                                    fnames
                                    ));
                }
            }
        }
Exemplo n.º 22
0
 public Ethic()
 {
     m_Players = new PlayerCollection();
 }
Exemplo n.º 23
0
        /// <summary>
        /// Handles moving on to the next duel, this will also check for the end of the game as set the GAME_OVER param to true if needed
        /// </summary>
        /// <param name="server">The server to excecute on</param>
        public static void MoveNextDuel(GameServer server)
        {
            GameState        state   = server.GameState;
            PlayerCollection players = server.Players;

            if (!state.GetValueBool(Names.GAME_OVER))
            {
                // Start by determining the number of active players
                int activePlayers = players.Where(X => X.Hand.Count > 0).Count();

                // If there are more than 1 players left, keep playing
                if (activePlayers > 1)
                {
                    // Clear the battle-specific states
                    state.Set(Names.IS_ATTACKING, true);
                    state.Set(Names.ATTACKER_FORFEIT, false);
                    state.Set(Names.DEFENDER_FORFEIT, false);

                    // Clear the match-specific states
                    state.Set(Names.CURRENT_ROUND, 0);

                    // Get the ID of the attacking player, this is the first person to get new cards
                    byte id      = state.GetValueByte(Names.ATTACKING_PLAYER);
                    byte startId = id;

                    // Get the deck off the state
                    Deck deck = new Deck(state.GetValueCardCollection(Names.DECK));

                    bool go = true;

                    while (go)
                    {
                        Player player = players[id];

                        if (player != null)
                        {
                            while (player.Hand.Count < 6)
                            {
                                if (deck.Cards.Count > 0)
                                {
                                    player.Hand.Add(deck.Draw());
                                }
                                else if (!state.GetValueBool(Names.TRUMP_CARD_USED))
                                {
                                    player.Hand.Add(state.GetValueCard(Names.TRUMP_CARD));
                                    state.Set <bool>(Names.TRUMP_CARD_USED, true);
                                    go = false;
                                    break;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        id++;

                        if (id >= players.Count)
                        {
                            id = 0;
                        }
                        if (id == startId)
                        {
                            break;
                        }
                    }

                    // Start by getting a round idea of the new attackers and defenders
                    byte attackingPlayerId = (byte)(state.GetValueByte(Names.ATTACKING_PLAYER) + 1);

                    // Iterate over each player until we come across a valid attacker
                    for (byte index = attackingPlayerId, iterations = 0; iterations < players.Count; index++, iterations++)
                    {
                        index = (byte)(index >= players.Count ? players.Count - index : index);

                        if (players[index] != null && players[index].Hand.Count > 0)
                        {
                            attackingPlayerId = index;
                            break;
                        }
                    }
                    byte defendingPlayerId = (byte)(attackingPlayerId + 1 >= players.Count ? players.Count - (attackingPlayerId + 1) : attackingPlayerId + 1);

                    // Iterate over each player until we come across a valid defender
                    for (byte index = defendingPlayerId, iterations = 0; iterations < players.Count; index++, iterations++)
                    {
                        index = (byte)(index >= players.Count ? players.Count - index : index);

                        if (players[index] != null && players[index].Hand.Count > 0)
                        {
                            defendingPlayerId = index;
                            break;
                        }
                    }

                    // Update the attacker and defenders
                    state.Set(Names.ATTACKING_PLAYER, attackingPlayerId);
                    state.Set(Names.DEFENDING_PLAYER, defendingPlayerId);

                    state.Set(Names.DECK, deck.Cards);
                    state.Set(Names.DECK_COUNT, deck.CardsInDeck);
                }
                else
                {
                    if (activePlayers == 1)
                    {
                        state.Set <byte>(Names.LOSER_ID, players.Where(X => X.Hand.Count > 0).ElementAt(0).PlayerId);
                        state.Set <bool>(Names.IS_TIE, false);
                        state.Set <bool>(Names.GAME_OVER, true);
                    }
                    else if (activePlayers == 0)
                    {
                        state.Set <bool>(Names.IS_TIE, true);
                        state.Set <bool>(Names.GAME_OVER, true);
                    }
                }
            }
        }
Exemplo n.º 24
0
 private void RefreshPlayersGrid()
 {
     playersDataGridView.DataSource = null;
     playersDataGridView.DataSource = PlayerCollection.Instance().Players;
 }
        internal TeamRosterPlayerCollection(Team team, PlayerCollection<Player> players, int week)
        {
            if (team == null) { throw new ArgumentNullException("team"); }
            if (players == null) { throw new ArgumentNullException("players"); }

            this.Team = team;
            this.Players = players;
            this.Week = week;
        }
Exemplo n.º 26
0
 public abstract void DisplayKingsReward(PlayerCollection players);
Exemplo n.º 27
0
 public AddPlayerWindow(PlayerCollection PlayerList)
 {
     initAddPlayerWindow(PlayerList);
 }
Exemplo n.º 28
0
        /// <summary>
        /// Parses the raw binary data for use within TQVault
        /// </summary>
        private void ParseRawData(PlayerCollection pc)
        {
            // First create a memory stream so we can decode the binary data as needed.
            using (MemoryStream stream = new MemoryStream(pc.rawData, false))
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    // Find the block pairs until we find the block that contains the item data.
                    int blockNestLevel  = 0;
                    int currentOffset   = 0;
                    int itemOffset      = 0;
                    int equipmentOffset = 0;
                    var playerReader    = new PlayerInfoReader(this.TQData);

                    // vaults start at the item data with no crap
                    bool foundItems     = pc.IsVault;
                    bool foundEquipment = pc.IsVault;

                    while ((!foundItems || !foundEquipment) && (currentOffset = FindNextBlockDelim(pc, currentOffset)) != -1)
                    {
                        if (pc.rawData[currentOffset] == beginBlockPattern[0])
                        {
                            // begin block
                            ++blockNestLevel;
                            currentOffset += beginBlockPattern.Length;

                            // skip past the 4 bytes of noise after begin_block
                            currentOffset += 4;

                            // Seek our stream to the correct position
                            stream.Seek(currentOffset, SeekOrigin.Begin);

                            // Now get the string for pc block
                            string blockName = TQData.ReadCString(reader).ToUpperInvariant();

                            // Assign loc to our new stream position
                            currentOffset = (int)stream.Position;

                            // See if we accidentally got a begin_block or end_block
                            if (blockName.Equals("BEGIN_BLOCK"))
                            {
                                blockName      = "(NONAME)";
                                currentOffset -= beginBlockPattern.Length;
                            }
                            else if (blockName.Equals("END_BLOCK"))
                            {
                                blockName      = "(NONAME)";
                                currentOffset -= endBlockPattern.Length;
                            }
                            else if (blockName.Equals("ITEMPOSITIONSSAVEDASGRIDCOORDS"))
                            {
                                currentOffset += 4;
                                itemOffset     = currentOffset;                             // skip value for itemPositionsSavedAsGridCoords
                                foundItems     = true;
                            }
                            else if (blockName.Equals("USEALTERNATE"))
                            {
                                currentOffset  += 4;
                                equipmentOffset = currentOffset;                                 // skip value for useAlternate
                                foundEquipment  = true;
                            }
                            else if (!pc.IsVault && playerReader.Match(blockName))
                            {
                                playerReader.Record(blockName, currentOffset);
                            }
                        }
                        else
                        {
                            // end block
                            --blockNestLevel;
                            currentOffset += endBlockPattern.Length;
                        }
                    }

                    if (foundItems)
                    {
                        try
                        {
                            ParseItemBlock(pc, itemOffset, reader);
                        }
                        catch (ArgumentException exception)
                        {
                            var ex = new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error parsing player file Item Block- '{0}'", pc.PlayerName), exception);
                            Log.ErrorFormat(CultureInfo.InvariantCulture, "Error parsing player file Item Block - '{0}'", pc.PlayerName);
                            Log.ErrorException(exception);
                            throw ex;
                        }

                        try
                        {
                            string outfile = string.Concat(Path.Combine(GamePathResolver.TQVaultSaveFolder, pc.PlayerName), " Export.txt");
                            using (StreamWriter outStream = new StreamWriter(outfile, false))
                            {
                                outStream.WriteLine("Number of Sacks = {0}", pc.numberOfSacks);

                                int sackNumber = 0;
                                if (pc.sacks != null)
                                {
                                    foreach (SackCollection sack in pc.sacks)
                                    {
                                        if (!sack.IsEmpty)
                                        {
                                            outStream.WriteLine();
                                            outStream.WriteLine("SACK {0}", sackNumber);

                                            int itemNumber = 0;
                                            foreach (Item item in sack)
                                            {
                                                object[] params1 = new object[20];

                                                params1[0] = itemNumber;
                                                params1[1] = ItemProvider.ToFriendlyName(item);
                                                params1[2] = item.PositionX;
                                                params1[3] = item.PositionY;
                                                params1[4] = item.Seed;
                                                ////params1[5] =

                                                outStream.WriteLine("  {0,5:n0} {1}", params1);
                                                itemNumber++;
                                            }
                                        }

                                        sackNumber++;
                                    }
                                }
                            }
                        }
                        catch (IOException exception)
                        {
                            Log.ErrorFormat(exception, "Error writing Export file - '{0}'"
                                            , string.Concat(Path.Combine(GamePathResolver.TQVaultSaveFolder, pc.PlayerName), " Export.txt")
                                            );
                        }
                    }

                    // Process the equipment block
                    if (foundEquipment && !pc.IsVault)
                    {
                        try
                        {
                            ParseEquipmentBlock(pc, equipmentOffset, reader);
                        }
                        catch (ArgumentException exception)
                        {
                            var ex = new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error parsing player file Equipment Block - '{0}'", pc.PlayerName), exception);
                            Log.ErrorFormat(ex, "Error parsing player file Equipment Block - '{0}'", pc.PlayerName);
                            throw ex;
                        }

                        try
                        {
                            string outfile = string.Concat(Path.Combine(GamePathResolver.TQVaultSaveFolder, pc.PlayerName), " Equipment Export.txt");
                            using (StreamWriter outStream = new StreamWriter(outfile, false))
                            {
                                if (!pc.EquipmentSack.IsEmpty)
                                {
                                    int itemNumber = 0;
                                    foreach (Item item in pc.EquipmentSack)
                                    {
                                        object[] params1 = new object[20];

                                        params1[0] = itemNumber;
                                        params1[1] = ItemProvider.ToFriendlyName(item);
                                        params1[2] = item.PositionX;
                                        params1[3] = item.PositionY;
                                        params1[4] = item.Seed;
                                        ////params1[5] =

                                        outStream.WriteLine("  {0,5:n0} {1}", params1);
                                        itemNumber++;
                                    }
                                }
                            }
                        }
                        catch (IOException exception)
                        {
                            Log.ErrorFormat(exception, "Error writing Export file - '{0}'"
                                            , string.Concat(Path.Combine(GamePathResolver.TQVaultSaveFolder, pc.PlayerName), " Equipment Export.txt")
                                            );
                        }
                    }

                    if (playerReader.FoundPlayerInfo && !pc.IsVault)
                    {
                        try
                        {
                            playerReader.Read(reader);
                            pc.PlayerInfo = playerReader.GetPlayerInfo();
                        }
                        catch (ArgumentException exception)
                        {
                            var rethrowex = new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error parsing player player info Block - '{0}'", pc.PlayerName), exception);
                            Log.ErrorException(rethrowex);
                            throw rethrowex;
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Find character data in player.chr file
        /// </summary>
        public PlayerInfo ReadPlayerInfo(PlayerCollection pc)
        {
            var pi = new PlayerInfo();

            pi.Modified = false;

            var headerVersion = TQData.ReadIntAfter(pc.rawData, "headerVersion");

            pi.HeaderVersion = headerVersion.valueAsInt;

            var playerCharacterClass = TQData.ReadCStringAfter(pc.rawData, "playerCharacterClass");

            pi.PlayerCharacterClass = playerCharacterClass.valueAsString;

            var playerClassTag = TQData.ReadCStringAfter(pc.rawData, "playerClassTag");

            pi.Class = playerClassTag.valueAsString;

            var money = TQData.ReadIntAfter(pc.rawData, "money", playerClassTag.nextOffset);

            pi.Money = money.valueAsInt;

            var masteriesAllowed = TQData.ReadIntAfter(pc.rawData, "masteriesAllowed", money.nextOffset);

            pi.MasteriesAllowed = masteriesAllowed.valueAsInt;

            var difficultyUnlocked = TQData.ReadIntAfter(pc.rawData, "temp");            // first "temp" / first "block"

            pi.DifficultyUnlocked = difficultyUnlocked.valueAsInt;

            var hasBeenInGame = TQData.ReadIntAfter(pc.rawData, "hasBeenInGame", difficultyUnlocked.nextOffset);

            pi.HasBeenInGame = hasBeenInGame.valueAsInt;

            var currentStatscharLevel = TQData.ReadIntAfter(pc.rawData, "currentStats.charLevel", hasBeenInGame.nextOffset);

            pi.CurrentLevel = currentStatscharLevel.valueAsInt;

            var currentStatsexperiencePoints = TQData.ReadIntAfter(pc.rawData, "currentStats.experiencePoints", currentStatscharLevel.nextOffset);

            pi.CurrentXP = currentStatsexperiencePoints.valueAsInt;

            var modifierPoints = TQData.ReadIntAfter(pc.rawData, "modifierPoints", currentStatsexperiencePoints.nextOffset);

            pi.AttributesPoints = modifierPoints.valueAsInt;

            var skillPoints = TQData.ReadIntAfter(pc.rawData, "skillPoints", modifierPoints.nextOffset);

            pi.SkillPoints = skillPoints.valueAsInt;

            var baseStrength = TQData.ReadFloatAfter(pc.rawData, "temp", difficultyUnlocked.nextOffset);            // first "temp" after first one (difficultyUnlocked)

            pi.BaseStrength = Convert.ToInt32(baseStrength.valueAsFloat);

            var baseDexterity = TQData.ReadFloatAfter(pc.rawData, "temp", baseStrength.nextOffset);            // second "temp" after first one

            pi.BaseDexterity = Convert.ToInt32(baseDexterity.valueAsFloat);

            var baseIntelligence = TQData.ReadFloatAfter(pc.rawData, "temp", baseDexterity.nextOffset);            // third "temp" after first one

            pi.BaseIntelligence = Convert.ToInt32(baseIntelligence.valueAsFloat);

            var baseHealth = TQData.ReadFloatAfter(pc.rawData, "temp", baseIntelligence.nextOffset);            // fourth "temp" after first one

            pi.BaseHealth = Convert.ToInt32(baseHealth.valueAsFloat);

            var baseMana = TQData.ReadFloatAfter(pc.rawData, "temp", baseHealth.nextOffset);            // fifth "temp" after first one

            pi.BaseMana = Convert.ToInt32(baseMana.valueAsFloat);

            var playTimeInSeconds = TQData.ReadIntAfter(pc.rawData, "playTimeInSeconds", baseMana.nextOffset);

            pi.PlayTimeInSeconds = playTimeInSeconds.valueAsInt;

            var numberOfDeaths = TQData.ReadIntAfter(pc.rawData, "numberOfDeaths", playTimeInSeconds.nextOffset);

            pi.NumberOfDeaths = numberOfDeaths.valueAsInt;

            var numberOfKills = TQData.ReadIntAfter(pc.rawData, "numberOfKills", numberOfDeaths.nextOffset);

            pi.NumberOfKills = numberOfKills.valueAsInt;

            var experienceFromKills = TQData.ReadIntAfter(pc.rawData, "experienceFromKills", numberOfKills.nextOffset);

            pi.ExperienceFromKills = experienceFromKills.valueAsInt;

            var healthPotionsUsed = TQData.ReadIntAfter(pc.rawData, "healthPotionsUsed", experienceFromKills.nextOffset);

            pi.HealthPotionsUsed = healthPotionsUsed.valueAsInt;

            var manaPotionsUsed = TQData.ReadIntAfter(pc.rawData, "manaPotionsUsed", healthPotionsUsed.nextOffset);

            pi.ManaPotionsUsed = manaPotionsUsed.valueAsInt;

            var maxLevel = TQData.ReadIntAfter(pc.rawData, "maxLevel", manaPotionsUsed.nextOffset);

            pi.MaxLevel = maxLevel.valueAsInt;

            var numHitsReceived = TQData.ReadIntAfter(pc.rawData, "numHitsReceived", maxLevel.nextOffset);

            pi.NumHitsReceived = numHitsReceived.valueAsInt;

            var numHitsInflicted = TQData.ReadIntAfter(pc.rawData, "numHitsInflicted", numHitsReceived.nextOffset);

            pi.NumHitsInflicted = numHitsInflicted.valueAsInt;

            var greatestDamageInflicted = TQData.ReadIntAfter(pc.rawData, "greatestDamageInflicted", numHitsInflicted.nextOffset);

            pi.GreatestDamageInflicted = greatestDamageInflicted.valueAsInt;

            var greatestMonsterKilledName = TQData.ReadUnicodeStringAfter(pc.rawData, "(*greatestMonsterKilledName)[i]", greatestDamageInflicted.nextOffset);

            pi.GreatestMonster = greatestMonsterKilledName.valueAsString;

            var greatestMonsterKilledLevel = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLevel)[i]", greatestMonsterKilledName.nextOffset);

            pi.GreatestMonsterKilledLevel = greatestMonsterKilledLevel.valueAsInt;

            var greatestMonsterKilledLifeAndMana = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLifeAndMana)[i]", greatestMonsterKilledLevel.nextOffset);

            pi.GreatestMonsterKilledLifeAndMana = greatestMonsterKilledLevel.valueAsInt;

            var greatestMonsterKilledName2 = TQData.ReadUnicodeStringAfter(pc.rawData, "(*greatestMonsterKilledName)[i]", greatestMonsterKilledLifeAndMana.nextOffset);

            var greatestMonsterKilledLevel2 = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLevel)[i]", greatestMonsterKilledName2.nextOffset);

            var greatestMonsterKilledLifeAndMana2 = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLifeAndMana)[i]", greatestMonsterKilledLevel2.nextOffset);

            var greatestMonsterKilledName3 = TQData.ReadUnicodeStringAfter(pc.rawData, "(*greatestMonsterKilledName)[i]", greatestMonsterKilledLifeAndMana2.nextOffset);

            var greatestMonsterKilledLevel3 = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLevel)[i]", greatestMonsterKilledName3.nextOffset);

            var greatestMonsterKilledLifeAndMana3 = TQData.ReadIntAfter(pc.rawData, "(*greatestMonsterKilledLifeAndMana)[i]", greatestMonsterKilledLevel3.nextOffset);

            var criticalHitsInflicted = TQData.ReadIntAfter(pc.rawData, "criticalHitsInflicted", greatestMonsterKilledLifeAndMana3.nextOffset);

            pi.CriticalHitsInflicted = criticalHitsInflicted.valueAsInt;

            var criticalHitsReceived = TQData.ReadIntAfter(pc.rawData, "criticalHitsReceived", criticalHitsInflicted.nextOffset);

            pi.CriticalHitsReceived = criticalHitsReceived.valueAsInt;

            // Parse skills collection
            var firstblock  = TQData.BinaryFindKey(pc.rawData, "begin_block");
            var secondblock = TQData.BinaryFindKey(pc.rawData, "begin_block", firstblock.nextOffset);
            var max         = TQData.ReadIntAfter(pc.rawData, "max", secondblock.nextOffset);
            // Loop of sub block
            int nextOffset = max.nextOffset;

            for (var i = 0; i < max.valueAsInt; i++)
            {
                var begin_block     = TQData.ReadIntAfter(pc.rawData, "begin_block", nextOffset);
                var skillName       = TQData.ReadCStringAfter(pc.rawData, "skillName", nextOffset);
                var skillLevel      = TQData.ReadIntAfter(pc.rawData, "skillLevel", nextOffset);
                var skillEnabled    = TQData.ReadIntAfter(pc.rawData, "skillEnabled", nextOffset);
                var skillSubLevel   = TQData.ReadIntAfter(pc.rawData, "skillSubLevel", nextOffset);
                var skillActive     = TQData.ReadIntAfter(pc.rawData, "skillActive", nextOffset);
                var skillTransition = TQData.ReadIntAfter(pc.rawData, "skillTransition", nextOffset);
                pi.SkillRecordList.Add(new SkillRecord()
                {
                    skillActive     = skillActive.valueAsInt,
                    skillEnabled    = skillEnabled.valueAsInt,
                    skillLevel      = skillLevel.valueAsInt,
                    skillName       = skillName.valueAsString,
                    skillSubLevel   = skillSubLevel.valueAsInt,
                    skillTransition = skillTransition.valueAsInt,
                });
                nextOffset = skillTransition.nextOffset;
            }

            return(pi);
        }
Exemplo n.º 30
0
 void initAddPlayerWindow(PlayerCollection playerList)
 {
     this.Players = playerList;
     Players.Clear();
     Player one = new Player("Frank", "Furters", "Necrons",false,0);
     Players.Add(one);
     Player two = new Player("Joe (AI:4)", "Shmoes", "Orks",true,4);
     Players.Add(two);
     InitializeComponent();
     initIconSets();
     lbxPlayerList.ItemsSource = Players;
     lbxPlayerList.UpdateLayout();
 }
Exemplo n.º 31
0
		public void AddKingdomSupply(PlayerCollection players, Type cardType)
		{
			// Minimum required -- Need to do this first to figure out what kind of card it is (silly, I know)
			Supply newSupply = new Supply(this._Game, players, cardType, 8);
			if ((newSupply.Category & Category.Victory) == Category.Victory)
			{
				// Victory supply piles should be 12 in 3+ player games
				if (NumPlayers > 2)
					newSupply.AddTo(_BaseVictoryCards - 8);
			}
			else  // Not a Victory card, so there should be 10
			{
				newSupply.AddTo(2);
			}

			_SupplyPiles[cardType] = newSupply;
			_SupplyKeys = null;
		}
Exemplo n.º 32
0
        public override PlayerCollection DisplayGetPlayers()
        {
            PlayerCollection toReturn = new PlayerCollection();

            switch( this.Mode )
            {
                case graphicsMode.CLI:
                    bool dbg = true;
                    string data = String.Empty;
                    string cancelChar = "d";
                    Console.WriteLine( "Enter the names of the players. Press <ENTER> after every player. Type '{0}' when done.", cancelChar );
                    do
                    {
                        data = Console.ReadLine();
                        if( ( data.Equals( cancelChar, StringComparison.OrdinalIgnoreCase ) || data.Equals( String.Empty ) ) && toReturn.Count == 0 )
                        {
                            Console.WriteLine( "You must enter at least 1 valid player name." );
                            data = cancelChar + "crap";
                        }
                        else if( !data.Equals( cancelChar, StringComparison.OrdinalIgnoreCase ) && !data.Equals( String.Empty ) )
                        {
                            toReturn.Add( new Player( data, "" ) );
                            Console.WriteLine( "{0} has joined the game!", data );
                            Console.WriteLine();
                        }
                        //bool a = !data.Equals( String.Empty );
                        bool b = !data.Equals( cancelChar, StringComparison.OrdinalIgnoreCase );
                        bool c = toReturn.Count <= 5;
                        dbg = b & c;
                    }
                    while( dbg );
                    break;
            }
            return toReturn;
        }
 private void StartSingle()
 {
     //_thisData.NetworkStatus = EnumNetworkStatus.SinglePlayer;
     _data.MultiPlayer = false;
     _playerList       = new PlayerCollection <P>();
 }
Exemplo n.º 34
0
 public override void DisplayPlayerOrder( PlayerCollection order )
 {
     switch( this.Mode )
     {
         case graphicsMode.CLI:
             Console.Write( "Turn order is: " );
             foreach( Player p in order )
             {
                 Console.Write( p.Name + ", " );
             }
             Console.WriteLine();
             break;
     }
 }
Exemplo n.º 35
0
 public override void BeforeStart()
 {
     base.BeforeStart();
     Players = new PlayerCollection();
     Manager = new ResearchManager(this);
 }
Exemplo n.º 36
0
		public Game(int numHumanPlayers, IEnumerable<String> playerNames, IEnumerable<Type> aiTypes, GameSettings settings)
		{
			this.State = GameState.Setup;
			this.Settings = settings;

			_Players = new PlayerCollection();
			// Add human players
			for (int i = 0; i < numHumanPlayers; i++)
				_Players.Add(new Players.Human(this, playerNames.ElementAt(i)));
			// Add AI players
			for (int i = numHumanPlayers; i < playerNames.Count(); i++)
				try
				{
					_Players.Add((Player)aiTypes.ElementAt(i).GetConstructor(new Type[] { typeof(Game), typeof(String) }).Invoke(new Object[] { this, playerNames.ElementAt(i) }));
				}
				catch (TargetInvocationException tie)
				{
					if (tie.InnerException != null)
						throw tie.InnerException;
				}

			_Players.Setup(this);

			Utilities.Shuffler.Shuffle<Player>(_Players);

			if (playerNames.Count() > 4)
				_EndgameSupplies = 4;

			this.State = GameState.CardSelection;
		}
Exemplo n.º 37
0
        public PlayerCollection PlayersWithHighestStrength( PlayerCollection PlayersToCheck )
        {
            PlayerCollection toReturn = new PlayerCollection();
            toReturn.Add( PlayersToCheck[0] );
            for( int i = 1; i < PlayersToCheck.Count; i++ )
            {

                if( PlayersToCheck[i].TotalStrength > toReturn[0].TotalStrength )
                {
                    toReturn.Clear();
                    toReturn.Add( PlayersToCheck[i] );
                }
                else if( PlayersToCheck[i].NumBuildings == toReturn[0].NumBuildings )
                {
                    toReturn.Add( PlayersToCheck[i] );
                }
                else
                {
                } // do nothing
            }
            return toReturn;
        }
Exemplo n.º 38
0
		public void Load(String filename)
		{
			if (this.State != GameState.Unknown)
				return;

			//try
			//{
				XmlDocument xdGame = new XmlDocument();

				xdGame.LoadXml(Utilities.StringUtility.Decrypt(Utilities.StringUtility.Unzip(System.IO.File.ReadAllBytes(filename))));
				//xdGame.Load("gamedump.xml");

				XmlNode xn = xdGame.SelectSingleNode("game/rng");
				if (xn != null)
				{
					MemoryStream msRandom = new MemoryStream(Convert.FromBase64String(xn.InnerText));
					BinaryFormatter bf = new BinaryFormatter();
					this.RNG = (Random)bf.Deserialize(msRandom);
					msRandom.Close();
				}

				xn = xdGame.SelectSingleNode("game/start_time");
				if (xn != null)
					this.StartTime = DateTime.Parse(xn.InnerText);

				this.State = GameState.Setup;

				xn = xdGame.SelectSingleNode("game/settings/GameSettings");
				if (xn != null)
				{
					Cards.CardCollection allCards = Cards.CardCollection.GetAllCards(c => true);
					XmlSerializer myDeserializer = new XmlSerializer(typeof(GameSettings), GetAllSerializingTypes(allCards).ToArray());
					using (StringReader sr = new StringReader(xn.OuterXml))
					{
						this.Settings = (GameSettings)myDeserializer.Deserialize(sr);
					}
				}

				_Table = new Table(this);
				XmlNodeList xnl = xdGame.SelectNodes("game/players/player");
				this._Players = new PlayerCollection();
				foreach (XmlNode xnPlayer in xnl)
				{
					Player player = Player.Load(this, xnPlayer);
					this._Players.Add(player);
					this.Table.AddPlayer(player);
				}

				xn = xdGame.SelectSingleNode("game/table");
				if (xn == null)
					return;
				this.Table.Load(xn);

				this._Players.Setup(this);

				xn = xdGame.SelectSingleNode("game/state");
				if (xn != null)
					this.State = (GameState)Enum.Parse(typeof(GameState), xn.InnerText, true);

				this.TurnsTaken.Load(this, xdGame.SelectSingleNode("game/turns"));

				xn = xdGame.SelectSingleNode("game/activeplayer");
				if (xn != null && !String.IsNullOrEmpty(xn.InnerText))
				{
					this.ActivePlayer = this.Players.FirstOrDefault(p => p.UniqueId == new Guid(xn.InnerText));
					this.ActivePlayer.SetCurrentTurn(this.TurnsTaken.Last());
				}
			//}
			//catch (Exception ex)
			//{
			//    throw ex;
			//}
		}
Exemplo n.º 39
0
 public PlayerCollection PlayersWithLowestBuildingCount( PlayerCollection PlayersToCheck )
 {
     PlayerCollection toReturn = new PlayerCollection();
     toReturn.Add( PlayersToCheck[0] );
     for( int i = 1; /* skipping the first player in the list */ i < PlayersToCheck.Count; i++ )
     {
         if( PlayersToCheck[i].NumBuildings < toReturn[0].NumBuildings )
         {
             toReturn.Clear();
             toReturn.Add( PlayersToCheck[i] );
         }
         else if( PlayersToCheck[i].NumBuildings == toReturn[0].NumBuildings )
         {
             toReturn.Add( PlayersToCheck[i] );
         }
         else
         {
         } // do nothing
     }
     return toReturn;
 }
Exemplo n.º 40
0
 public PlayerCollection PlayersWithLowestGoodsCount( PlayerCollection PlayersToCheck )
 {
     PlayerCollection toReturn = new PlayerCollection();
     toReturn.Add( PlayersToCheck[0] );
     for( int i = 1; /* skipping the first player in the list */ i < PlayersToCheck.Count; i++ )
     {
         if( PlayersToCheck[i].GoodsCount < toReturn[0].GoodsCount )
         {
             toReturn.Clear();
             toReturn.Add( PlayersToCheck[i] );
         }
         else if( PlayersToCheck[i].GoodsCount == toReturn[0].GoodsCount )
         {
             toReturn.Add( PlayersToCheck[i] );
         }
         else // do nothing
         {
         }
     }
     return toReturn;
 }
Exemplo n.º 41
0
 /// <summary>
 /// Attempts to save the file.
 /// </summary>
 /// <param name="fileName">Name of the file to save</param>
 public void Save(PlayerCollection pc, string fileName)
 {
     byte[] data = Encode(pc);
     File.WriteAllBytes(fileName, data);
 }
Exemplo n.º 42
0
        /// <summary>
        /// Updates the list of client names in the window
        /// </summary>
        /// <param name="players">The list of players to add</param>
        public void UpdateClientList(List<Player> players)
        {
            if (this.InvokeRequired)
            {
                PlayerListCallback d = UpdateClientList;
                Invoke(d, new List<Player>[] { players });
            }
            else
            {

                if (dgvPlayers.DataSource == null)
                    dgvPlayers.DataSource = pc;

                // Try to keep the same selection on update
                string selected = null;
                if (pc.Count > 0 && dgvPlayers.SelectedRows.Count > 0)
                {
                    selected = (from DataGridViewRow row in dgvPlayers.Rows where row.Selected select pc[row.Index]).First().name;
                }

                // Update the data source and control
                //dgvPlayers.SuspendLayout();

                pc = new PlayerCollection(new PlayerListView());
                Player.players.ForEach(p => pc.Add(p));

                //dgvPlayers.Invalidate();
                dgvPlayers.DataSource = pc;
                // Reselect player
                if (selected != null)
                {
                    for (int i = 0; i < Player.players.Count; i++)
                        for (int j = 0; j < dgvPlayers.Rows.Count; j++)
                            if (String.Equals(dgvPlayers.Rows[j].Cells[0].Value, selected))
                                dgvPlayers.Rows[j].Selected = true;
                }

                dgvPlayers.Refresh();
                //dgvPlayers.ResumeLayout();
            }
        }
Exemplo n.º 43
0
        public void LoadLists <P>(PlayerCollection <P> thisList) where P : class, IPlayerItem, new()
        {
            int x = 0;
            int y;

            GridHelper.AddAutoRows(_mainGrid !, thisList.Count());
            co.TrueFalseConverter thisT = null !;
            co.CurrencyConverter  thisC = null !;
            if (_rowList.Any(Items => Items.UseTrueFalseConverter == true))
            {
                thisT        = new co.TrueFalseConverter();
                thisT.UseAbb = UseAbbreviationForTrueFalse;
            }
            if (_rowList.Any(Items => Items.UseCurrencyConverter == true))
            {
                thisC = new co.CurrencyConverter();
            }
            foreach (var thisItem in thisList)
            {
                x += 1;
                y  = 0;
                foreach (var thisBind in _rowList !)
                {
                    Label thisLabel = new Label();
                    thisLabel.BindingContext = thisItem;
                    thisLabel.TextColor      = Color.Aqua;
                    if (thisBind.UseTrueFalseConverter == true)
                    {
                        Binding tss = new Binding(thisBind.MainPath);
                        tss.Converter = thisT;
                        thisLabel.SetBinding(Label.TextProperty, tss);
                    }
                    else if (thisBind.UseCurrencyConverter == true)
                    {
                        Binding css = new Binding(thisBind.MainPath);
                        css.Converter = thisC;
                        thisLabel.SetBinding(Label.TextProperty, css);
                    }
                    else
                    {
                        thisLabel.SetBinding(Label.TextProperty, new Binding(thisBind.MainPath));
                    }
                    if (thisBind.VisiblePath != "")
                    {
                        Binding otherBind = new Binding(thisBind.VisiblePath);
                        thisLabel.SetBinding(IsVisibleProperty, otherBind);
                    }
                    if (thisBind.RightMargin > 0)
                    {
                        thisLabel.Margin = new Thickness(0, 0, thisBind.RightMargin, 0);
                    }
                    else
                    {
                        thisLabel.HorizontalOptions       = LayoutOptions.Start;
                        thisLabel.HorizontalTextAlignment = TextAlignment.Start;
                    }
                    GridHelper.AddControlToGrid(_mainGrid !, thisLabel, x, y);
                    y += 1;
                }
            }
        }