public override void Release() { if (ObserversList != null) ObserversList.Clear(); ObserversList = null; VisiblePlayers = null; VisibleNpcs = null; VisibleItems = null; if (Ai != null) Ai.Release(); Ai = null; if (_lifeStats != null) _lifeStats.Release(); _lifeStats = null; GameStats = null; Position = null; BindPoint = null; Instance = null; Target = null; EffectsLock = null; base.Release(); }
public BoardPoint Post(AiConfig aiConfig) { IAi ai = CreateAiObject(aiConfig.TurnPiece, aiConfig.AiName); var board = aiConfig.GetBoard(); return(ai.HitPiece(board)); }
public TicTacToeGame(IUser user, IAi aI, GameSettings.gameSetting setting) { _user = user; _aI = aI; Setting = setting; }
public Simulation(Level originalLevel, SimulationParameters parameters, IAi ai, IRover rover) { OriginalLevel = originalLevel ?? throw new ArgumentNullException(nameof(originalLevel)); Parameters = parameters ?? throw new ArgumentNullException(nameof(parameters)); Ai = ai ?? throw new ArgumentNullException(nameof(ai)); Rover = rover ?? throw new ArgumentNullException(nameof(rover)); }
private async void BeginRender_Click(object sender, EventArgs e) { beginRender.Enabled = false; IAi ai = DemoAi.Create(DemoResult.AiIdentifier, DemoResult.Parameters); Level originalLevel = DemoResult.OriginalLevel; MutableLevel workingLevel = originalLevel.AsMutable(); using (var source = new System.Threading.CancellationTokenSource()) { IRover rover = new ReportingRover( new Rover(workingLevel, DemoResult.Parameters), new Progress <TerrainUpdate>(UpdateTerrain), new Progress <PositionUpdate>(UpdateRoverPosition), new Progress <StatsUpdate>(UpdateStats), source.Token ); Simulation sim = new Simulation(originalLevel, DemoResult.Parameters, ai, rover); _renderData = RenderData.GenerateBlank(originalLevel.BottomRight, rover.Position); try { await Task.Run(sim.Simulate, source.Token); } catch (OperationCanceledException) { // Ignore this exception, since it'll only happen when we've already closed the form } catch (OutOfPowerOrMovesException) { // This is to be expected if an AI doesn't keep track of their power or moves } } }
public Game(Map map, IAi ai) { Map = map; this.ai = ai; TurnsCount = 0; BadShots = 0; }
public GameSimulationResult(IAi gamer, ScoreData gamerScore, Exception lastException, double optionsUsed, StatValue turnTime) { ScoreData = gamerScore; Gamer = gamer; LastException = lastException; TurnTime = turnTime; OptionsUsed = optionsUsed; }
public Game(Map map, IAi ai) { Map = map; //это приведение не нужно и потенциально опасно, достаточно как и везде поменять тип поля ai на IAi this.ai = ai; TurnsCount = 0; BadShots = 0; }
public GameField(Form start, IAi aiMode = null) { _field = new string[9]; _ai = aiMode; _start = start; _oWins = 0; _xWins = 0; _deadHeats = 0; InitializeComponent(); }
public DummyPlayerBot() { Ai = null; LevelIndex = -1; AiFactories = new Dictionary <int, IAiFactory>(); AiFactories.Add(0, new LambdaAiFactory((v, i) => new FastKillAi(v))); AiFactories.Add(1, new LambdaAiFactory((v, i) => new SmartAi(v, i))); history = new Queue <Location>(); historySize = 20; }
public Unit(string name, Side owner, IAi ai) { Name = name; Owner = owner; Ai = ai; Facing = Direction.North; Health = 100; Sensor = new Sensor(); Sensor.Health = Health; Coordinates = new Tuple <int, int>(-1, -1); }
private void BeginRender_Click(object sender, EventArgs e) { IAi ai = DemoAi.Create(DemoResult.Parameters); Level level = DemoResult.ProtoLevel.Generate(); _rover = new Rover(level, DemoResult.Parameters); _stats = RoverStats.Create(DemoResult.Parameters); _state = VisibleState.GenerateBlank(level.BottomRight, _rover.Position); _actionEnumerator = ai.Simulate(_rover.Accessor).GetEnumerator(); beginRender.Enabled = false; UpdateTimer.Start(); }
private static void ExportFrames(CompletedSimulation sim, IAiFactory aiFactory, String outputDir) { const Int32 tileSize = 10; IAi ai = aiFactory.Create(sim.Parameters); Level level = sim.ProtoLevel.Generate(); Rover rover = new Rover(level, sim.Parameters); VisibleState state = VisibleState.GenerateBlank(level.BottomRight, rover.Position); using var actionEnumerator = ai.Simulate(rover.Accessor).GetEnumerator(); Int32 maxFrameCount = sim.Parameters.InitialMovesLeft; Int32 filenameDigits = (Int32)Math.Ceiling(Math.Log10(maxFrameCount)) + 1; String fileBase = Path.Combine(outputDir, $"frame-{sim.ProtoLevel.Seed}-"); DirectoryInfo dir = new DirectoryInfo(outputDir); if (dir.Exists) { foreach (var file in dir.EnumerateFiles()) { file.Delete(); } } else { dir.Create(); } Int32 width = level.Width * tileSize; Int32 height = level.Height * tileSize; using Bitmap bitmap = new Bitmap(width, height); using Graphics surface = Graphics.FromImage(bitmap); Update update = new Update(terrain: rover.Adjacent); Int32 frameIndex = 0; do { if (!state.Apply(update)) { continue; } GdiRenderer.Draw(surface, width, height, state); String suffix = frameIndex.ToString().PadLeft(filenameDigits, '0'); String filename = fileBase + suffix + ".png"; bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png); frameIndex++; }while (actionEnumerator.MoveNext() && rover.Perform(actionEnumerator.Current, out update)); }
public override void Release() { if (ObserversList != null) { ObserversList.Clear(); } ObserversList = null; VisiblePlayers = null; VisibleNpcs = null; VisibleItems = null; VisibleGathers = null; if (Ai != null) { Ai.Release(); } Ai = null; if (_lifeStats != null) { _lifeStats.Release(); } _lifeStats = null; GameStats = null; Position = null; BindPoint = null; Instance = null; Target = null; if (VisualEffect != null) { VisualEffect.Release(); } VisualEffect = null; if (Effects != null) { for (int i = 0; i < Effects.Count; i++) { Effects[i].Release(); } } Effects = null; EffectsLock = null; base.Release(); }
public Turn MakeTurn(LevelView levelView, IMessageReporter messageReporter) { if (Ai == null || !levelView.Field.GetCellsOfType(CellType.Exit).First().Equals(Ai.Exit) || MonsterCount < levelView.Monsters.Count()) { LevelIndex++; if (IsLastLevel(levelView)) { Ai = new ArenaDestroyerAi(levelView); } else if (AiFactories.ContainsKey(LevelIndex)) { Ai = AiFactories[LevelIndex].CreateBot(levelView, LevelIndex); } else { Ai = AiFactories[AiFactories.Keys.OrderBy(k => Math.Abs(k - LevelIndex)).First()].CreateBot(levelView, LevelIndex); } history = new Queue <Location>(historySize); } MonsterCount = levelView.Monsters.Count(); var isAttack = false; var action = Ai.Iteration(levelView, messageReporter, out isAttack); if (!isAttack) { history.Enqueue(levelView.Player.Location); if (history.Count > historySize) { history.Dequeue(); if (new HashSet <Location>(history).Count < (historySize * Ai.CriticalPercentageInactivity / 100)) { messageReporter.ReportMessage("T"); history.Clear(); if (levelView.Monsters.Any(m => m.Location.IsInRange(levelView.Player.Location, 1))) { messageReporter.ReportMessage("A"); return(Turn.Attack(levelView.Monsters.First(m => m.Location.IsInRange(levelView.Player.Location, 1)).Location - levelView.Player.Location)); } var solve = Ai.HandleCycle(levelView); if (solve != null) { return(solve); } return(Turn.Step((StepDirection) new Random().Next(0, 4))); } } } return(action); }
public void StartGame(IAi aiModule) { _ai = aiModule; //use the aiModule to calculate the computer movements. (probably inject to logic!) _model = new MillModel(); // nézemodell létrehozása _viewModel = new MillViewModel(_model); //_viewModel.GameEnded += GameEnded; // nézet létrehozása _view = new MainWindow(); _view.DataContext = _viewModel; _view.Show(); }
public void StartGame(IAi aiModule) { _ai = aiModule; _model = new GameLogic(); _model.CpuTurn += ModelCpuTurn; _view = new MainWindow(); _viewModel = new GrundyViewModel(_model); _viewModel.GameEndEvent += ModelGameEnd; //message display event: //_viewModel.InfoEvent += (sender, args) => MessageBox.Show(args.Text); _view.DataContext = _viewModel; _view.Closing += _view_Closing; _view.Show(); }
public RenderViewModel(IAiFactory aiFactory, CompletedSimulation simulation) { Ai = aiFactory ?? throw new ArgumentNullException(nameof(aiFactory)); Simulation = simulation ?? throw new ArgumentNullException(nameof(simulation)); Start = ReactiveCommand.CreateFromObservable(() => { IAi ai = Ai.Create(Simulation.Parameters); Level level = Simulation.ProtoLevel.Generate(); Rover rover = new Rover(level, Simulation.Parameters); return(Observable.Create <(RoverAction action, Update update)>(obs => { return Task.Run(async() => { var actionEnumerator = ai.Simulate(rover.Accessor).GetEnumerator(); while (actionEnumerator.MoveNext() && rover.Perform(actionEnumerator.Current, out Update update)) { obs.OnNext((actionEnumerator.Current, update)); Int32 delay = actionEnumerator.Current.Instruction switch { Instruction.Move => 75, Instruction.CollectSample => 50, _ => 0 }; if (delay != 0) { await Task.Delay(delay); } } }); })); }); Stats = Start.Aggregate(RoverStats.Create(Simulation.Parameters), (s, update) => s.Add(update.action, update.update)); State = this .WhenAnyObservable(m => m.Start) .Select(update => update.update) .Scan(VisibleState.GenerateBlank(Simulation.Parameters), (state, update) => { state.Apply(update); return(state); }); }
/// <summary> /// MainGame constructor /// The board is made out of hexagones /// 0,0 is on the top left and /// 7,7 is on the bottom right. /// </summary> public MainGame() { _log.Debug("Starting Game"); Board = new Plateau(8, 8); _pointManager = new PointHelper(); _isolationHelper = new IsolationVerificationHelper(Board); _endGameHelper = new EndGameHelper(); _movementHelper = new MovementVerificationHelper(Board); _aiEasy = new AiEasy(Board); _aiMedium = new AiMedium(Board); // her would the AI hard initialization Players = new List <IPlayer>(); CurrentPlayer = null; StateChanged?.Invoke(this, null); //sets the game in th ready state }
public void StartGame(IAi aiModule) { _ai = aiModule; //use the aiModule to calculate the computer movements. _model = new Logic(); // nézemodell létrehozása _viewModel = new TicTacToeViewModel(_model); _viewModel.GameEnded += GameEnded; _viewModel.CpuStep += CpuStep; // nézet létrehozása _view = new MainWindow(); _view.DataContext = _viewModel; _view.Show(); Testing test = new Testing(); UnitTesting unitTest = new UnitTesting(); }
private static AiMoveDecision GetNextMove(IAi ai, State state, bool eatExceptions, Dictionary <IAi, Exception> lastException) { try { return(ai.GetNextMove(state, new Services(state))); } catch (Exception e) { lastException[ai] = e; if (eatExceptions) { return(AiMoveDecision.Pass(state.punter, e.ToString())); } else { throw; } } }
public void init() { PreLoad(); _ai = new Ai(); games = new List<IGame>(); Type igame = typeof(IGame); var types = AppDomain.CurrentDomain.GetAssemblies(). SelectMany(p => p.GetTypes()). Where(p => igame.IsAssignableFrom(p) && !igame.Equals(p)); foreach (var type in types) { IGame g = (IGame)Activator.CreateInstance(type); String gameName = type.Assembly.FullName.Split(',')[0]; if (gameName != "FrameWork") { games.Add(g); GameAdded(this, new GameAddedEventArgs(games.Count - 1, gameName)); } } }
private void WriteTotal(IAi ai, List <int> shots, int crashes, int badShots, int gamesPlayed) { if (shots.Count == 0) { shots.Add(1000 * 1000); } shots.Sort(); var median = shots.Count % 2 == 1 ? shots[shots.Count / 2] : (shots[shots.Count / 2] + shots[(shots.Count + 1) / 2]) / 2; var mean = shots.Average(); var sigma = Math.Sqrt(shots.Average(s => (s - mean) * (s - mean))); var badFraction = (100.0 * badShots) / shots.Sum(); var crashPenalty = 100.0 * crashes / settings.CrashLimit; var efficiencyScore = 100.0 * (settings.Width * settings.Height - mean) / (settings.Width * settings.Height); var score = efficiencyScore - crashPenalty - badFraction; var headers = FormatTableRow(new object[] { "AiName", "Mean", "Sigma", "Median", "Crashes", "Bad%", "Games", "Score" }); var message = FormatTableRow(new object[] { ai.Name, mean, sigma, median, crashes, badFraction, gamesPlayed, score }); resultsLog.Info(message); Console.WriteLine(); Console.WriteLine("Score statistics"); Console.WriteLine("================"); Console.WriteLine(headers); Console.WriteLine(message); }
public override void Release() { if (ObserversList != null) { ObserversList.Clear(); } ObserversList = null; VisiblePlayers = null; VisibleNpcs = null; VisibleItems = null; if (Ai != null) { Ai.Release(); } Ai = null; if (_lifeStats != null) { _lifeStats.Release(); } _lifeStats = null; GameStats = null; Position = null; BindPoint = null; Instance = null; Target = null; EffectsLock = null; base.Release(); }
public Exception GetLastException(IAi ai) { return(lastException.TryGetValue(ai, out var ex) ? ex : null); }
public override void Release() { if (ObserversList != null) ObserversList.Clear(); ObserversList = null; VisiblePlayers = null; VisibleNpcs = null; VisibleItems = null; VisibleGathers = null; if (Ai != null) Ai.Release(); Ai = null; if (_lifeStats != null) _lifeStats.Release(); _lifeStats = null; GameStats = null; Position = null; BindPoint = null; Instance = null; Target = null; if (VisualEffect != null) VisualEffect.Release(); VisualEffect = null; if (Effects != null) for (int i = 0; i < Effects.Count; i++) Effects[i].Release(); Effects = null; EffectsLock = null; base.Release(); }
public Strategy(IAi ai) { this.ai = ai; }
public Tuple <ReplayMeta, ReplayData> RunGame(IAi ai) { var setup = connection.ReadSetup(); var state = new State { map = setup.map, punter = setup.punter, punters = setup.punters, settings = setup.settings }; AiSetupDecision setupDecision; try { setupDecision = ai.Setup(state, new Services(state)); } catch { var handshake = JsonConvert.SerializeObject(new HandshakeIn { you = botName }); var input = JsonConvert.SerializeObject(setup, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); File.WriteAllText($@"error-setup-{DateTime.UtcNow.ToString("O").Replace(":", "_")}.json", $@"{handshake.Length}:{handshake}{input.Length}:{input}"); throw; } if (!state.settings.futures && setupDecision.futures?.Any() == true) { throw new InvalidOperationException($"BUG in Ai {ai.Name} - futures are not supported"); } state.aiSetupDecision = new AiInfoSetupDecision { name = ai.Name, version = ai.Version, futures = setupDecision.futures, reason = setupDecision.reason }; connection.WriteSetupReply(new SetupOut { ready = setup.punter, futures = setupDecision.futures }); var allMoves = new List <Move>(); var serverResponse = connection.ReadNextTurn(); while (!serverResponse.IsScoring()) { var moves = serverResponse.move.moves.OrderBy(m => m.GetPunter()).ToArray(); moves = moves.Skip(setup.punter).Concat(moves.Take(setup.punter)).ToArray(); var gameplay = JsonConvert.SerializeObject(serverResponse, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); allMoves.AddRange(moves); state.ApplyMoves(moves); AiMoveDecision moveDecision; try { moveDecision = ai.GetNextMove(state, new Services(state)); } catch { var handshake = JsonConvert.SerializeObject(new { you = "kontur.ru" }); File.WriteAllText($@"error-turn-{DateTime.UtcNow.ToString("O").Replace(":", "_")}.json", $@"{handshake.Length}:{handshake}{gameplay.Length}:{gameplay}"); throw; } var aiInfoMoveDecision = new AiInfoMoveDecision { name = ai.Name, version = ai.Version, move = moveDecision.move, reason = moveDecision.reason }; state.ValidateMove(aiInfoMoveDecision); state.lastAiMoveDecision = aiInfoMoveDecision; connection.WriteMove(moveDecision.move); serverResponse = connection.ReadNextTurn(); } var stopIn = serverResponse.stop; allMoves.AddRange(stopIn.moves); var meta = new ReplayMeta(DateTime.UtcNow, ai.Name, ai.Version, "", setup.punter, setup.punters, stopIn.scores); var data = new ReplayData(setup.map, allMoves, state.aiSetupDecision.futures); return(Tuple.Create(meta, data)); }
public ConsoleUI(IGame pStatus, IAi pAi) { status = pStatus; ai = pAi; }
public SingleTargetAi(int timeToSimulate, IStateEvaluator evaluator, IAi fastEnemyAi) { this.timeToSimulate = timeToSimulate; this.evaluator = evaluator; this.fastEnemyAi = fastEnemyAi; }
public CompilationResult(IAi ai) { IsOk = true; Ai = ai; }
public MakeDecisionCommand(IAi ai, AiContext context, F32 time) { this.ai = ai; this.context = context; ai.SetDecisionTime(context.CurrentTime, time); }