public SeasonSimulationResult PerformSimulation(IStrategy strategy, SeasonSimulationOptions options) { if (strategy == null) throw new ArgumentNullException("strategy"); var allPlayers = GetPlayersForFirstGameweek(); var maxGameweek = CalculateMaxGameweek(options.MaximumGameweek); _logger.Log(Tag.Simulation, string.Concat("Max gameweek is ", maxGameweek)); var startingTeam = options.UseSavedInitialTeam ? SelectInitialTeamByIds(allPlayers, options.InitialTeamPlayerIds) : strategy.PickStartingTeam(allPlayers); _logger.Log(Tag.Simulation, "Starting team picked"); LogHelper.LogTeam(startingTeam, _logger); if (options.ChooseInitialTeamOnly) { return new SeasonSimulationResult(); } var seasonState = _decisionActioner.ValidateAndApplyStartingTeam(startingTeam, allPlayers); _logger.Log(Tag.Simulation, "Applied starting team"); return SimulateSeason(seasonState, strategy, maxGameweek); }
public QuoteProvider(IStrategy owner) { _owner = owner; _lastPeek = new DateTime(1900, 1, 1); _timer = new Timer(1000); _timer.Elapsed += new ElapsedEventHandler(OnTick); }
public void run() { try { remoteProcessClient.WriteToken(token); int teamSize = remoteProcessClient.ReadTeamSize(); remoteProcessClient.WriteProtocolVersion(); Game game = remoteProcessClient.readGameContext(); IStrategy[] strategies = new IStrategy[teamSize]; for (int strategyIndex = 0; strategyIndex < teamSize; ++strategyIndex) { strategies[strategyIndex] = new MyStrategy(); } PlayerContext playerContext; while ((playerContext = remoteProcessClient.ReadPlayerContext()) != null) { Trooper playerTrooper = playerContext.Trooper; Move move = new Move(); strategies[playerTrooper.TeammateIndex].Move(playerTrooper, playerContext.World, game, move); remoteProcessClient.WriteMove(move); } } finally { remoteProcessClient.Close(); } }
// Changing strategies public void SwitchStrategy() { if (strategy is Strategy1) strategy = new Strategy2(); else strategy = new Strategy1(); }
public static void register(IStrategy strat) { if (strat != null) { registry.Put(strat.Name, strat); } }
public void Update() { KeyboardState keyState = Keyboard.GetState(); strategy = new Move(animator, transform); if ((keyState.IsKeyDown(Keys.R))) { GameWorld.Instance.Completed = true; } if ((keyState.IsKeyDown(Keys.D)) || (keyState.IsKeyDown(Keys.A)) || (keyState.IsKeyDown(Keys.S)) || (keyState.IsKeyDown(Keys.W))) { strategy = new Move(animator, transform); if (keyState.IsKeyDown(Keys.D)) { direction = Direction.Right; strategy.Update(ref direction); } else if (keyState.IsKeyDown(Keys.A)) { direction = Direction.Left; strategy.Update(ref direction); } else if (keyState.IsKeyDown(Keys.S)) { direction = Direction.Front; strategy.Update(ref direction); } else if (keyState.IsKeyDown(Keys.W)) { direction = Direction.Back; strategy.Update(ref direction); } } }
public Template(IStrategy strategy, String templateText, String[] namespaces, params Variable[] variables) { _strategy = strategy; this.templateText = templateText; this.namespaces = namespaces; this.variables = variables; }
/// <summary> /// 增加一个策略,和关注的股票价格 /// </summary> /// <param name="code">股票代码</param> /// <param name="strategy">策略实例</param> public void AddStock(String code, IStrategy strategy) { if (stockDataCache[code] == null) { stockDataCache[code] = new StockDataQueue(); } stockDataCache[code].OnStockDataChange += strategy.OnStockDataChanged; }
public StrategyControl(IStrategy strategy) { InitializeComponent(); this.strategy = strategy; // load my stock pool LoadMyStockPool(); }
public StringPrinter() { nc = new NCPrint(); lc = new LCPrint(); uc = new UCPrint(); strat = nc; }
public ComplexStrategy(IStrategy[] innerStrategies, string name, long quantity, IStrategy defaultStrategy, StrategyType strategyType) { _innerStrategies = innerStrategies; _name = name; _quantity = quantity; _defaultStrategy = defaultStrategy; _strategyType = strategyType; }
public ConfigurationContext BuildConfigurationContext(BaseFeature feature, IStrategy strategy) { if (string.IsNullOrWhiteSpace(Key)) { throw new ArgumentException("Missing 'Key' parameter for '" + strategy.GetType().Name + "' strategy for '" + feature.Name + "' feature"); } return new ConfigurationContext(this); }
public GuardianAgentSession(Agent agent, string process, IStrategy redStrategy, IStrategy yellowStrategy, double e1, double e2) { this.Agent = agent; this.TargetProcess = process; this.RedStrategy = redStrategy; this.YellowStrategy = yellowStrategy; this.E1 = e1; this.E2 = e2; }
public ReachabilityStrategyCalculationAlgorithm(ITestGraph testGraph, IStrategy strategy) { if (this.testGraph == null) { throw new ArgumentNullException("testGraph"); } this.testGraph = testGraph; this.strategy = new QuickGraph.Algorithms.TestGames.Strategy(); this.performanceComparer = new PairPreOrderPerformanceComparer(); }
// Update is called once per frame void Update() { if (Input.GetKeyDown (KeyCode.Alpha1)) s = new Strategy1 (); if (Input.GetKeyDown (KeyCode.Alpha2)) s = new Strategy2 (); if (Input.GetKeyDown (KeyCode.Alpha3)) s = new Strategy3 (); s.Method (this.gameObject); }
public void SwitchStrategy() { if (strategy is QueueLinearFloodFill) { strategy = strategy2; } else { strategy = strategy1; } }
/// <summary> /// 在行情市场中登记一个策略,当关注股票价格发生变动的时候,即时提醒策略。 /// </summary> /// <param name="strategy">策略实例</param> public void RegisterStrategy(IStrategy strategy) { foreach (string code in strategy.StockPool) { if (!StockMarketManager.bidCache.ContainsKey(code)) { StockMarketManager.bidCache.Add(code, new BidCacheQueue()); } StockMarketManager.bidCache[code].OnBidChange += strategy.OnStockDataChanged; } }
public RecognizedAgent(string name, double res, IStrategy redStrategy, IStrategy yellowStrategy, double p1, double p2) { Name = name; m_P1 = p1; m_P2 = p2; m_Res = res; m_RedStrategy = redStrategy; m_YellowStrategy = yellowStrategy; }
public PythonStrategyControl() { InitializeComponent(); this.strategy = createStrategy(); engine = IronPython.Hosting.Python.CreateEngine(); scope = engine.CreateScope(); // load my stock pool LoadMyStockPool(); }
public FoxWatchMainController(IStrategy strategy, DBOutEnum dbOutEnum) { _strategy = strategy; Boolean bDBOut_InRunning = false; if (dbOutEnum == DBOutEnum.Enable) { bDBOut_InRunning = true; } _foxCaptureController = new FoxWatchCaptureController(bDBOut_InRunning); }
static Strategies() { DEPTH = new DepthStrategy(); BREADTH = new BreadthStrategy(); RECENCY = new RecencyStrategy(); registry = new GenericHashMap<String, IStrategy>(); { registry.Put(DEPTH.Name, DEPTH); registry.Put(BREADTH.Name, BREADTH); registry.Put(RECENCY.Name, RECENCY); } }
private void ProcessStrategy(IStrategy strategy) { foreach (var quote in this.quotes) { strategy.ProcessQuote(quote); } if (Interlocked.Decrement(ref numberOfTasks) == 0) { signal.Set(); } }
private static String GenerateHTMLForImage(Image img, IStrategy strategy) { // Create table . Table tbl = new Table(); // Convert image. strategy.generateTable(img, tbl); // Table to HTML. HTMLBuilder builder = new HTMLBuilder(); tbl.accept(builder); return builder.HTML; }
public void SetUp() { _gameweek = 1; _team = TeamCreationHelper.CreateTestTeam(); _allPlayers = new List<Player>(); _seasonState = new SeasonState {CurrentTeam = _team, AllPlayers = _allPlayers, Gameweek = _gameweek}; _intitialTeamSelectorMock = new Mock<IInitialTeamSelectorStrategy>(); _playerScorePredictorMock = new Mock<IPlayerScorePredictor>(); _teamGameweekSelectorMock = new Mock<ITeamGameweekSelector>(); _transferSelectorStrategyMock = new Mock<ITransferSelectorStrategy>(); _complexStrategy = new ComplexStrategy(new Mock<ILogger>().Object, _intitialTeamSelectorMock.Object, _playerScorePredictorMock.Object, _teamGameweekSelectorMock.Object, _transferSelectorStrategyMock.Object); }
public BackTest( IEventBus eventBus, IDataHandler bars, IStrategy strategy, IPortfolio portfolio, IExecutionHandler executionHandler) { this.eventBus = eventBus; this.bars = bars; this.strategy = strategy; this.portfolio = portfolio; this.executionHandler = executionHandler; this.stopWatch = new Stopwatch(); }
public static void Main(string[] args) { // Some pre-processing filters. IFilter[] filters = new IFilter[] { new BMPConvert(), // new DynamicRangeReduce(), }; // Find all strategies and instantiate. Type[] strategy_types = Assembly .GetExecutingAssembly() .GetTypes() .Where( type => typeof(IStrategy).IsAssignableFrom(type) && typeof(IStrategy) != type ) .ToArray(); IStrategy[] strategies = new IStrategy[strategy_types.Length]; for(int t = 0; t < strategy_types.Length; ++t) { strategies[t] = (IStrategy) Activator.CreateInstance(strategy_types[t]); } StringBuilder html = new StringBuilder(); html.Append ("<html><body>"); foreach(string arg in args) { // Load image from arguments. Image bmp = Image.FromFile(arg); // Run through filters. foreach(IFilter filter in filters) { bmp = filter.filter (bmp); } // Run through each strategy. html.AppendFormat ("<div><h2>{0}</h2>", arg); foreach(IStrategy strategy in strategies) { String table = GenerateHTMLForImage(bmp, strategy); html.AppendFormat ("<h3>{0}</h3><p>{1} bytes</p><div>{2}</div>", strategy.Name, table.Length, table); } html.Append ("</div>"); } html.Append ("</body>"); // Dump to console. Console.Write (html.ToString ()); }
void DetermineAction(int first, int second) { if (first > second) { this.strategy = new Subtract(); } else if (first < second) { this.strategy = new Add(); } else { this.strategy = new Multiply(); } }
public void CopyData(string sourcePath, string destPath) { FileAttributes attr = File.GetAttributes(sourcePath); if (attr.HasFlag(FileAttributes.Directory)) { actionStrategy = GetActions(ActionObjects.FolderShell); actionStrategy.Copy(sourcePath, destPath, null); } else { string name = sourcePath.Substring(sourcePath.LastIndexOf('\\') + 1); actionStrategy = GetActions(ActionObjects.FileShell); actionStrategy.Copy(sourcePath, destPath, name); } }
public void run() { try { remoteProcessClient.WriteToken(token); int teamSize = remoteProcessClient.ReadTeamSize(); IStrategy[] strategies = new IStrategy[teamSize]; TankType[] tankTypes = new TankType[teamSize]; for (int strategyIndex = 0; strategyIndex < teamSize; ++strategyIndex) { IStrategy strategy = new MyStrategy(); strategies[strategyIndex] = strategy; tankTypes[strategyIndex] = strategy.SelectTank(strategyIndex, teamSize); } remoteProcessClient.WriteSelectedTanks(tankTypes); PlayerContext playerContext; while ((playerContext = remoteProcessClient.ReadPlayerContext()) != null) { Tank[] playerTanks = playerContext.Tanks; if (playerTanks.Length != teamSize) { break; } Move[] moves = new Move[teamSize]; for (int strategyIndex = 0; strategyIndex < teamSize; ++strategyIndex) { Move move = new Move(); moves[strategyIndex] = move; strategies[strategyIndex].Move(playerTanks[strategyIndex], playerContext.World, move); } remoteProcessClient.WriteMoves(moves); } } finally { remoteProcessClient.Close(); } }
public Agent(IStrategy strategy, List<Account> accounts) { this._strategy = strategy; _accounts = accounts; _bStart = false; AgentManager.Ins().Register(this); ScheduleManager.Ins().AddSchedule(this); foreach (Account account in accounts) { account.SetAgent(this); } this._strategy.TakeOverRemainPosition(); }
public StrategyPrice(IStrategy strat) { //test }
// Обычно Контекст позволяет заменить объект Стратегии во время // выполнения. public void SetStrategy(IStrategy strategy) { this._strategy = strategy; }
public static double Test(IStrategy strategy) { var numDecks = Settings.Current.TestSettings.NumDecks; var numRounds = Settings.Current.TestSettings.NumRounds; var betAmount = Settings.Current.TestSettings.BetAmount; var blackjackPayout = Settings.Current.TestSettings.BlackjackPayout; var shoe = new Shoe(numDecks); var dealerHand = new Hand(); var playerHand = new Hand(); var playerHands = new List <Hand>(); var playerBets = new List <double>(); var playerChips = 0d; for (var n = 0; n < numRounds; n++) { if (shoe.NeedsShuffle) { shoe.Shuffle(); shoe.CutCards(); shoe.BurnCard(); } playerHand.Cards.Clear(); dealerHand.Cards.Clear(); playerHand.Cards.Add(shoe.NextCard()); dealerHand.Cards.Add(shoe.NextCard()); playerHand.Cards.Add(shoe.NextCard()); dealerHand.Cards.Add(shoe.NextCard()); playerHands.Clear(); playerHands.Add(playerHand); playerBets.Clear(); playerBets.Add(betAmount); playerChips -= betAmount; // 1. if the player has blackjack if (playerHand.FinalValue == Hand.MAX_VALUE) { // if the dealer also has blackjack if (dealerHand.FinalValue == Hand.MAX_VALUE) { // it's a tie; return the bet playerChips += playerBets[0]; } else { // the player won; return the bet plus a matching amount multiplied by the blackjack payout playerChips += playerBets[0] + playerBets[0] * blackjackPayout; } // move to the next hand continue; } // 2. if the dealer has blackjack if (dealerHand.FinalValue == Hand.MAX_VALUE) { // move to the next hand continue; } // 3. play the player's hand plus any split hands for (var h = 0; h < playerHands.Count; h++) { playerHand = playerHands[h]; var gameState = GameState.PlayerDrawing; while (gameState == GameState.PlayerDrawing) { if (playerHand.FinalValue == Hand.MAX_VALUE) { // if a split hand has blackjack if (playerHand.Cards.Count == 2) { // return the bet plus a matching amount multiplied by the blackjack payout playerChips += playerBets[h] + playerBets[h] * blackjackPayout; playerBets[h] = 0; } // automatically stand at 21 gameState = GameState.DealerDrawing; break; } // stand, hit, double, or split var action = strategy.GetAction(playerHand, dealerHand); // if attempting to double with more than 2 cards, then hit instead if (action == Action.Double && playerHand.Cards.Count > 2) { action = Action.Hit; } switch (action) { case Action.Stand: gameState = GameState.DealerDrawing; break; case Action.Hit: // deal the next card playerHand.Cards.Add(shoe.NextCard()); // if the player busted if (playerHand.FinalValue > Hand.MAX_VALUE) { playerBets[h] = 0; gameState = GameState.PlayerBusted; } else if (playerHand.FinalValue == Hand.MAX_VALUE) { // automatically stand at 21 gameState = GameState.DealerDrawing; } break; case Action.Double: // double the bet playerChips -= betAmount; playerBets[h] += betAmount; // deal one and only one card playerHand.Cards.Add(shoe.NextCard()); // if the player busted if (playerHand.FinalValue > Hand.MAX_VALUE) { playerBets[h] = 0; gameState = GameState.PlayerBusted; } else { gameState = GameState.DealerDrawing; } break; case Action.Split: // add the split hand var splitHand = new Hand(); splitHand.Cards.Add(playerHand.Cards[1]); playerHand.Cards[1] = shoe.NextCard(); splitHand.Cards.Add(shoe.NextCard()); playerHands.Add(splitHand); // add the extra bet playerChips -= betAmount; playerBets.Add(betAmount); break; } } } // 4. if the player has any "active" hands remaining (i.e. hands with a non-zero bet), then play the dealer hand if (playerBets.Sum() > 0) { var gameState = GameState.DealerDrawing; // the dealer must draw until 17 or busted while (dealerHand.FinalValue < Hand.DEALER_STAND_VALUE) { // deal the next card dealerHand.Cards.Add(shoe.NextCard()); // if the dealer busted if (dealerHand.FinalValue > Hand.MAX_VALUE) { // payoff each active player hand for (var h = 0; h < playerHands.Count; h++) { // return the bet plus a matching amount playerChips += playerBets[h] * 2; } gameState = GameState.DealerBusted; break; } } // if the dealer has not busted if (gameState != GameState.DealerBusted) { var dealerHandFinalValue = dealerHand.FinalValue; // compare the dealer hand to each player hand for (var h = 0; h < playerHands.Count; h++) { var playerHandFinalValue = playerHands[h].FinalValue; if (playerHandFinalValue == dealerHandFinalValue) { // it's a tie; return the bet playerChips += playerBets[h]; } else if (playerHandFinalValue > dealerHandFinalValue) { // the player won; return the bet plus a matching amount playerChips += playerBets[h] * 2; } else { // the player lost } } } } } return(playerChips); }
public void ChangeStrategy(IStrategy strategy) { this.Strategy = strategy; }
/// <summary> /// Not supported, will throw an error. /// </summary> /// <param name="strategy">Not used.</param> public void AddStrategy(IStrategy strategy) { throw new TrainingError( "Strategies are not supported by this training method."); }
public PrimitiveCalculator() { this.currentStrategy = InitialStrategy; }
protected virtual bool IsSkipped(int taskSize, IStrategy strategy) { return(false); }
public StrategyContext(string type, IStrategy strategy) { _type = type; _strategy = strategy; }
public Context(IStrategy strategy) { this._strategy = strategy; }
public PaymentContext(IStrategy str) { strategy = str; }
public PaymentContext(EStrategy str) { strategy = dic[str]; }
public Player(Mark mark, IStrategy strategy) { this.mark = mark; this.strategy = strategy; }
private void BtnBrowse_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "dll files (*.dll)|*.dll|All files (*.*)|*.*"; // 过滤文件类型 openFileDialog.ShowReadOnly = true; // 设定文件是否只读 if (openFileDialog.ShowDialog() == DialogResult.OK) { TxtStrategyFileName.Text = openFileDialog.SafeFileName; // 获取文件名 _strStrategyFullName = openFileDialog.FileName; // 获取包含完整路径的文件名 string strStrategyCachePath = Application.StartupPath + "\\StrategyCache\\"; // StrategyCache目录 string strCachedStrategyFullName = strStrategyCachePath + openFileDialog.SafeFileName; // Cache的dll文件 try { if (!System.IO.Directory.Exists(strStrategyCachePath)) { // 策略缓存目录不存在则新建 System.IO.Directory.CreateDirectory(strStrategyCachePath); } //// 如果已经加载过策略dll则先卸载前一次加载策略所使用的应用程序域即可卸载已加载的dll文件 //if (_appDomainForStrategy != null) //{ // AppDomain.Unload(_appDomainForStrategy); // _appDomainForStrategy = null; // StrategyInterface = null; //} //System.IO.File.Copy(_strStrategyFullName, strCachedStrategyFullName, true); //added by liushu 20110307 if (string.Compare(_strStrategyFullName, strCachedStrategyFullName) != 0) { //如果加载策略时不是直接在StrategyCache目录中添加的 if (_appDomainForStrategy != null) { //如果此队伍已经加载过dll,则先卸载前一次加载策略所使用的应用程序域即可卸载之前加载的dll策略文件 AppDomain.Unload(_appDomainForStrategy); _appDomainForStrategy = null; StrategyInterface = null; } System.IO.File.Copy(_strStrategyFullName, strCachedStrategyFullName, true); } } catch (System.IO.IOException) {//当有两支队伍加载同一个策略文件时会出现异常现象,这时 strCachedStrategyFullName = strCachedStrategyFullName.Replace(".dll", string.Format(" {0:0000}{1:00}{2:00} {3:00}{4:00}{5:00}.dll", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second)); System.IO.File.Copy(_strStrategyFullName, strCachedStrategyFullName, true); } catch { MessageBox.Show("策略加载异常"); } #region 使用AppDomain加载策略组件dll _appDomainForStrategy = AppDomain.CreateDomain("Server AppDomain For Strategy" + TeamId); // 使用AppDomain创建策略接口工厂类(StrategyInterfaceFactory)实例 StrategyInterfaceFactory factory = (StrategyInterfaceFactory)_appDomainForStrategy.CreateInstance( "URWPGSim2D.StrategyLoader", typeof(StrategyInterfaceFactory).FullName).Unwrap(); // 使用策略接口工厂类实例创建策略接口实例 StrategyInterface = factory.Create(strCachedStrategyFullName, "URWPGSim2D.Strategy.Strategy", null); #endregion BtnReady.Enabled = true; // 半场交换队伍名称显示错误修正 LiYoubing 20110520 int teamId = TeamId; if (MyMission.Instance().ParasRef.IsExchangedHalfCourt == true && MyMission.Instance().ParasRef.TeamCount == 2) { teamId = (TeamId + 1) % 2; } MyMission.Instance().TeamsRef[teamId].Para.Name = StrategyInterface.GetTeamName(); } }
public Context(IStrategy strategy) { _strategy = strategy; }
public PrimitiveCalculator() { this.defaultStrategy = new AdditionStrategy(); }
public SomeClass(ISomeStrategyFactory strategyFactory) { IStrategy strat = strategyFactory.GetStrategy("HelloStrategy"); strat.Execute(); }
public LogProvider(ILogProviderHost host, ILogProviderFactory factory, IConnectionParams connectParams, IStrategy strategy) : base(host, factory, connectParams) { try { this.strategy = strategy; this.azureConnectParams = new AzureConnectionParams(connectionParams); this.table = strategy.CreateTable(this.azureConnectParams.Account); StartLiveLogThread("WAD listening thread"); } catch (Exception e) { trace.Error(e, "Failed to initialize WAD reader. Disposing what has been created so far."); Dispose(); throw; } }
public Context(IStrategy stategy) { }
public void ChangeStrategy(IStrategy strategy) { this.currentStrategy = strategy; }
public void SetStrategy(IStrategy strategy) { _strategy = strategy; Query = strategy.GetQuery(); }
public GenerateReportRequest(IStrategy strategy) { SetStrategy(strategy); }
/// <inheritdoc/> public void AddStrategy(IStrategy strategy) { }
/// <summary> /// Get the value of the association on this object. /// </summary> /// <param name="strategy"> /// The strategy. /// </param> /// <returns> /// The association value. /// </returns> public override object Get(IStrategy strategy) { return(strategy.GetAssociation(this)); }
/// <summary> /// 方法实例化 /// </summary> /// <param name="strategy"></param> public void StrategyMethod(IStrategy strategy) { this.Strategy = strategy; Strategy.StrategyMethod(); }
public void SetCarCreation(IStrategy strategy) { _strategy = strategy; }
public OrderService(IUserRepository userRepository, IShopRepository shopRepository, IOrdersRepository ordersRepository, IProductRepository productRepository, IPriceRepository priceRepository, IImageRepository imageRepository, IStrategy _strategy, ShopsChecker _shopsChecker) { imgRepo = imageRepository; shopRepo = shopRepository; ordersRepo = ordersRepository; productRepo = productRepository; shopsChecker = _shopsChecker; strategy = _strategy; }
// Обычно Контекст принимает стратегию через конструктор, а также // предоставляет сеттер для её изменения во время выполнения. public Fight(IStrategy strategy) { this._strategy = strategy; }
public void ChangeStrategy(char mode) { StrategyChanger changer = new StrategyChanger(mode); this.defaultStrategy = changer.GetStrategy(); }
public TReturn ToBuilders <T, TReturn>(IStrategy <T> strategy, SqlConfig setting, T rawData) where TReturn : class { return(strategy.GetBuilder <TReturn>(this.Data, setting, rawData)); }
public Bot(FourInARowFormController controller, int player) { _controller = controller; _me = player; _strategy = new AlphaBetaStrategyWithOrdering(new ImmediateEvaluatorOnlyEmptyCells(), 4); }