Beispiel #1
0
 public Agency(string Name, int Money, int Billboards, Strategies Strategy)
 {
     agencyName = Name;
     agencyDeposit = Money;
     agencyBillboardsCount = Billboards;
     agencyStrategy = Strategy;
 }
Beispiel #2
0
 public void GetData(out string Name, out int Money, out int Billboards, out Strategies Strategy)
 {
     Name = agencyName;
     Money = agencyDeposit;
     Billboards = agencyBillboardsCount;
     Strategy = agencyStrategy;
 }
 public static IGameStrategy createStrategy(Strategies s, int maxPlayer)
 {
     if (s.Equals(Strategies.SimpleGameStrategy))
     {
         return new SimpleGameStrategy(maxPlayer);
     }
     return null;
 }
Beispiel #4
0
 public bool createGame(string gameName, Strategies strategy, int maxPlayer)
 {
     bool ok = false;
     ILobbyCallback callback = OperationContext.Current.GetCallbackChannel<ILobbyCallback>();
     if (subscribers.ContainsKey(callback))
     {
         UserAccount user = subscribers[callback];
         ok = server.createGame(gameName, StrategyFactory.createStrategy(strategy, maxPlayer));
     }
     return ok;
 }
        public void tryStrategyChange()
        {
            if (observedPayoffs == null)  return;
            try
            {
                int target = Utils.rnd.Next(observedPayoffs.Values.Count);
                int i = 0;
                object[] keys = new object[observedPayoffs.Count];
                observedPayoffs.Keys.CopyTo(keys, 0);
                foreach (int[] entry in observedPayoffs.Values)
                {
                    if (i == target)
                    {
                        if (keys[i] is Human && ((Human)keys[i]).isAlive() && parentEnvironment.get(((Human)keys[i]).x, ((Human)keys[i]).y) is Human)
                        {
                            if (entry[0] > payoff)
                            {
                                int diff = entry[0] - (int)payoff;
                                if (diff > reproductionThreshold) diff = reproductionThreshold;

                                double probability = 100.0 * diff / reproductionThreshold;

                                probs += ((int)(probability * 10) / 10.0).ToString() + " ";

                                if (Utils.rnd.Next(80) < (int)probability)
                                {
                                    parentEnvironment.lastCounts = ("Strategy change " + this.strategy.ToString() + "-> " + ((Strategies)entry[2]).ToString() + "\r\n") + parentEnvironment.lastCounts;
                                    strategy = (Strategies)entry[2];
                                }
                            }
                        }
                        else {
                            observedPayoffs.Remove(keys[i]);
                            tryStrategyChange();
                        }
                        break;
                    }
                    i++;
                }
            }
            catch (Exception ex) { }
        }
        public override bool Step()
        {
            base.Step();
            payoff -= 1;

            bool d = true;
            if (age > maxAge && payoff > 0)
            {
                payoff = 0; //die
                diedAtStep = parentEnvironment.steps;
                if (!base.src.Contains("caveman_dead"))
                    parentEnvironment.lastCounts = ("Died from old age " + this.strategy.ToString() + "\r\n") + parentEnvironment.lastCounts;
                d = false;
            }

            if (payoff <= 0)
            {
                if (parentEnvironment.steps - diedAtStep <= 2)
                {
                    base.setImg("caveman_dead");
                    payoff--;
                }
                else
                {
                    if (d)
                        parentEnvironment.lastCounts = ("Died from malnourishment " + this.strategy.ToString() + "\r\n") + parentEnvironment.lastCounts;
                    parentEnvironment.remove(this);
                }
                return true;
            }
            else if (diedAtStep > 0) {
                parentEnvironment.remove(this);
                return true;
            }
            else
            {
                bool success;
                switch (strategy)
                {
                    case Strategies.Cooperator:
                        success = hunterStep();
                        break;
                    case Strategies.Defector:
                        success = hunterStep();
                        break;
                    case Strategies.Punisher:
                        success = punisherStep();
                        break;
                    default:
                        success = lonerStep();
                        break;
                }

                if (payoff > reproductionThreshold)
                {
                    //reproduce and reset payoff
                    Strategies strat = strategy;
                    payoff -= reproductionCost;
                    Human child = new Human(parentEnvironment);
                    child.init();
                    child.strategy = strat;
                    bool reproduced = false;
                    for (int i = -1; i <= 1 && !reproduced; i++)
                    {
                        for (int j = -1; j <= 1; j++)
                        {
                            if (parentEnvironment.get(x + i, y + j) == null)
                            {
                                success &= parentEnvironment.add(child, x + i, y + j);
                                reproduced = true;
                                break;
                            }
                        }
                    }
                }

                //update average observed payoffs of all humans
                List<Entity> humansInSight = parentEnvironment.getAllInLOS(x, y, this);
                if (humansInSight.Count > 0)
                    foreach (Human h in humansInSight)
                    {
                        if (h == null) continue;
                        int[] entry;
                        if (!observedPayoffs.ContainsKey(h))
                        {
                            entry = new int[4];
                            entry[0] = (int)h.payoff;
                            entry[1] = 1;
                            entry[2] = (int)h.strategy;
                            entry[3] = h.signaling ? 1 : 0;
                            observedPayoffs[h] = entry;
                        }
                        else
                        {
                            entry = (int[])observedPayoffs[h];
                            entry[3] = h.signaling ? 1 : 0;
                            if (entry[2] != (int)h.strategy)
                            { //human changed strategy
                                entry[2] = (int)h.strategy;
                                entry[1] = 1;
                                entry[0] = (int)h.payoff;
                            }
                            else
                            {
                                int n = entry[1];
                                int sum = entry[0];
                                entry[1] = n + 1;
                                entry[0] = (int)(sum * n + h.payoff) / (n + 1);
                            }
                            observedPayoffs[h] = entry;
                        }
                    }

                if (Utils.rnd.Next((int)(1.0 / strategyMutation)) == 0) {
                    Strategies strat = (Strategies)Utils.rnd.Next(4);
                    while (strat == strategy || strat == (Strategies)blockedStrategy) strat = (Strategies)Utils.rnd.Next(4);
                    strategy = strat;
                }

                return success;
            }
        }
        public override void init()
        {
            strategy = (Strategies)Utils.rnd.Next(4);
            while (strategy == (Strategies)blockedStrategy) strategy = (Strategies)Utils.rnd.Next(4);

            payoff = minInitialPayoff + Utils.rnd.Next(minInitialPayoff);
            prevDistance = 1e9;
            prevGoal = null;
            maxAge = maxHumanAge / 2 + Utils.rnd.Next(maxHumanAge / 2);

            punisherGoals = new List<Human>();
            prevPunisherGoal = null;

            prevHunterGoal = null;
            prevHunterDistance = 1e6;
            prevMHunters = -1;

            diedAtStep = -1;

            observedPayoffs = new Hashtable();
        }
        private static Entities.Script CreateScript(Entities.ScriptConfiguration scriptConfiguration,
            Entities.ScriptManifest scriptManifest, Values.Configuration configuration,
            Strategies.ConfigInjector configInjector, string connectionString)
        {
            var scriptFileName = Path.Combine(Path.GetDirectoryName(configuration.Manifest.FilePath), scriptManifest.Path);
            if (!File.Exists(scriptFileName))
            {
                throw new DatabaseScripterException(ErrorCode.ScriptFileDoesNotExist, scriptFileName);
            }

            var command = File.ReadAllText(scriptFileName);

            return new Entities.Script(scriptManifest.Name,
                scriptManifest.Description,
                scriptConfiguration.Properties.Find("databaseName").Value,
                connectionString,
                scriptManifest.WrapInTransaction,
                (scriptManifest.CurrentVersion == null) ? null : new Values.Version(scriptManifest.CurrentVersion),
                (scriptManifest.NewVersion == null) ? null : new Values.Version(scriptManifest.NewVersion),
                configInjector.InjectConfig(command, scriptConfiguration.Properties));
        }
Beispiel #9
0
 public void ChangeMainData(string Name, Strategies Strategy)
 {
     agencyName = Name;
     agencyStrategy = Strategy;
 }
Beispiel #10
0
        /// <summary>
        /// Runs the script against the database
        /// </summary>
        /// <param name="databaseAdapter">The database adapter.</param>
        /// <returns></returns>
        private ErrorCode RunImplementation(Strategies.DatabaseAdapter databaseAdapter)
        {
            var errorCode = ErrorCode.Ok;

            if (WrapInTransaction)
            {
                if (!databaseAdapter.BeginTransaction())
                {
                    log.Error("Failed to begin the transaction on the database.");
                    return ErrorCode.DatabaseAdapterFailureAtBeginTransaction;
                }
            }

            if (null != CurrentVersion)
            {
                bool versionConfirmed;
                if (!databaseAdapter.ConfirmVersion(DatabaseName, CurrentVersion, out versionConfirmed))
                {
                    log.Error("Failed to check the current version of the database.");
                    return ErrorCode.DatabaseAdapterFailureAtConfirmVersion;
                }

                if (versionConfirmed)
                {
                    log.Info("The current version of the database is compatible with the script");
                }
                else
                {
                    log.Error("The current version of the database is not compatible with the script.");
                    return ErrorCode.IncorrectCurrentVersion;
                }
            };

            if (!databaseAdapter.RunCommand(DatabaseName, Command))
            {
                log.Error("Failed to execute the command on the database.");
                errorCode = ErrorCode.DatabaseAdapterFailureAtRunCommand;
            }

            if ((errorCode == ErrorCode.Ok) && (NewVersion != null))
            {
                if (!databaseAdapter.SetVersion(DatabaseName, NewVersion))
                {
                    log.Error("Failed to set the new version on the database.");
                    errorCode = ErrorCode.DatabaseAdapterFailureAtSetVersion;
                }
            }

            if ((errorCode == ErrorCode.Ok) && WrapInTransaction)
            {
                if (!databaseAdapter.CommitTransaction())
                {
                    log.Error("Failed to commit the transaction on the database.");
                    errorCode = ErrorCode.DatabaseAdapterFailureAtCommitTransaction;
                }
            }

            if (errorCode != ErrorCode.Ok)
            {
                if (WrapInTransaction)
                {
                    log.Warn("Rolling back the script transaction.");

                    if (!databaseAdapter.RollBackTransaction())
                    {
                        log.Error("An error occurred when rolling back the script transaction. You must check the database is in the correct state.");
                        errorCode = ErrorCode.DatabaseAdapterFailureAtRollbackTransaction;
                    }

                    log.Warn("The script transaction rolled back successfully");
                }
                else
                {
                    log.Warn("The script will not be rolled back. You must check the database is in the correct state.");
                }
            }

            return errorCode;
        }
Beispiel #11
0
        /// <summary>
        /// Runs the specified database adapter.
        /// </summary>
        /// <param name="databaseAdapter">The database adapter.</param>
        /// <returns></returns>
        public ErrorCode Run(Strategies.DatabaseAdapter databaseAdapter)
        {
            log.InfoFormat(CultureInfo.InvariantCulture, "{0} : running...", this);

            var errorCode = ErrorCode.Ok;

            if (!databaseAdapter.Connect(ConnectionString))
            {
                log.Error("Failed to connect to the database");
                errorCode = ErrorCode.DatabaseAdapterFailureAtConnect;
            }

            if (errorCode == ErrorCode.Ok)
            {
                errorCode = RunImplementation(databaseAdapter);
                databaseAdapter.Disconnect();
            }

            if (errorCode == ErrorCode.Ok)
            {
                log.InfoFormat(CultureInfo.InvariantCulture, "{0} : succeeded", this);
            }
            else
            {
                log.ErrorFormat(CultureInfo.InvariantCulture, "{0} : FAILED.", this);
            }

            return errorCode;
        }
Beispiel #12
0
 /// <summary>
 /// Sets all Strategies object instances. All existing 
 /// <c>Strategies</c> instances 
 /// are removed and replaced with this list. Calling this method with the 
 /// parameter value set to null removes all <c>Strategieses</c>.
 /// </summary>
 /// <remarks>
 /// <para>Version: 2.5</para>
 /// <para>Since: 1.5r1</para>
 /// </remarks>
 public void SetStrategieses( Strategies[] items)
 {
     SetChildren( InstrDTD.COMPONENT_STRATEGIES, items );
 }
Beispiel #13
0
 /// <summary>Adds a new <c>&lt;Strategies&gt;</c> child element.</summary>
 /// <param name="val">A Strategies object</param>
 /// <remarks>
 /// <para>The SIF specification defines the meaning of this element as: "Teaching/learning strategies uses in the learning resource. One per element."</para>
 /// <para>Version: 2.5</para>
 /// <para>Since: 1.5r1</para>
 /// </remarks>
 public void AddStrategies( Strategies val )
 {
     AddChild( InstrDTD.COMPONENT_STRATEGIES, val );
 }
Beispiel #14
0
 public bool createGame(String gameName, Strategies strategy, int maxPlayer)
 {
     return lobby.createGame(gameName, strategy, maxPlayer);
 }