private void EvaluatePopulation() { Scores = new Dictionary <Individual, int>(); for (int i = 0; i < Population.Count; i++) { Scores.Add(Population[i], 0); } for (int i = 0; i < Population.Count - 1; i++) { for (int j = i + 1; j < Population.Count; j++) { var individual1 = Population[i]; var individual2 = Population[2]; var game = new LocalGame(); int result = game.PlayGame(individual1.Player(), individual2.Player()); if (result == 1) { Scores[individual1]++; Scores[individual2]--; } else if (result == 2) { Scores[individual2]++; Scores[individual1]--; } } } }
public override void OnPlayerDamaged(ref int damage, ref byte type) { // disable this code for now if (!grant) { grant = true; /* * alex.SpawnOn(LocalGame, LocalPlayer); * GordonFreeman.SpawnOn(LocalGame, LocalPlayer); * InstaRepair.SpawnOn(LocalGame, LocalPlayer); * Weapon.SpawnOn(LocalGame, LocalPlayer); * WeaponOne.SpawnOn(LocalGame, LocalPlayer); * Hattus.SpawnOn(LocalGame, LocalPlayer); */ } return; damage = (3 * LocalGame.GetCurrentFloor()) * damage; //e.g 300%, 600%, 900%... dmg Type gameType = Utils.GetGameType("SoG.Game1"); dynamic game = LocalGame.GetUnderlayingGame(); dynamic player = game.xLocalPlayer; var function = ((TypeInfo)gameType).GetDeclaredMethods("_EntityMaster_AddItem").First(); //function.Invoke(LocalGame.GetUnderlayingGame(), new[] { GetModItemFromString("BagKnight"), player.xEntity.xTransform.v2Pos, player.xEntity.xRenderComponent.fVirtualHeight, player.xEntity.xCollisionComponent.ibitCurrentColliderLayer, Vector2.Zero }); //function.Invoke(LocalGame.GetUnderlayingGame(), new[] { GetModItemFromString("BananaMan"), player.xEntity.xTransform.v2Pos, player.xEntity.xRenderComponent.fVirtualHeight, player.xEntity.xCollisionComponent.ibitCurrentColliderLayer, Vector2.Zero }); }
/// <summary> /// All games that would be enabled if <paramref name="localGame"/> /// was the active game /// </summary> /// <param name="localGame"></param> /// <returns></returns> List <LocalGame> ActiveGames(LocalGame localGame) { List <LocalGame> activeGames = new List <LocalGame>(); if (GameOver()) { // no active games if the global game is over return(activeGames); } if (localGame != null && !localGame.GameOver()) { // return only the active game activeGames.Add(localGame); return(activeGames); } else { // return all unfinished games foreach (LocalGame game in localGames) { if (!game.GameOver()) { activeGames.Add(game); } } return(activeGames); } }
/// <summary> /// Returns a deep copy of the given global game /// </summary> /// <param name="globalGame"></param> /// <returns></returns> GlobalGame CopyGlobalGame(GlobalGame globalGame) { if (globalGame == null) { return(null); } LocalGame[,] localGames = new LocalGame[3, 3]; LocalGame activeGame = null; foreach (LocalGame game in globalGame.LocalGames) { localGames[game.Loc.Row, game.Loc.Col] = CopyLocalGame(game); if (game == globalGame.ActiveGame) { activeGame = localGames[game.Loc.Row, game.Loc.Col]; } } return(new GlobalGame( localGames, globalGame.Enabled, globalGame.P1, globalGame.P2, globalGame.P1Turn, activeGame )); }
public override void OnEnemyDamaged(Enemy enemy, ref int damage, ref byte type) { var currentFloor = (double)LocalGame.GetCurrentFloor(); var factor = 1 - 0.15 * currentFloor; damage = (int)Math.Floor(damage * factor); }
void InitializeGames() { int spotUIIndex = 0; int localGameUIIndex = 1; // first GameUI is global UI SpotUI[] spotUIs = GetComponentsInChildren <SpotUI>(); GameUI[] gameUIs = GetComponentsInChildren <GameUI>(); LocalGame[,] localGames = new LocalGame[3, 3]; for (int boardRow = 0; boardRow < 3; boardRow++) { for (int boardCol = 0; boardCol < 3; boardCol++) { // a grid of spots represents each local board Spot[,] spots = new Spot[3, 3]; for (int spotRow = 0; spotRow < 3; spotRow++) { for (int spotCol = 0; spotCol < 3; spotCol++) { // each spot SpotUI spotUI = spotUIs[spotUIIndex]; Spot spot = new Spot( new Location(spotRow, spotCol), null, true); spotUI.Spot = spot; spots[spotRow, spotCol] = spot; spotUIIndex++; } } // each local game Location loc = new Location(boardRow, boardCol); LocalGame localGame = new LocalGame(spots, true, loc); localGames[boardRow, boardCol] = localGame; gameUIs[localGameUIIndex].Game = localGame; localGameUIIndex++; } } Player p1 = menu ? Settings.NewPlayer(true, true) : Settings.p1; Player p2 = menu ? Settings.NewPlayer(false, true) : Settings.p2; // initialize the global game, its view and its controller GlobalGame game = new GlobalGame(localGames, true, p1, p2, true); if (p1 is AI) { ((AI)p1).Game = game; } if (p2 is AI) { ((AI)p2).Game = game; } GetComponent <GameUI>().Game = game; GetComponent <GameController>().Game = game; globalGame = game; }
public IGame CreateGame() { var game = new LocalGame(IntegratedOpenGl.Mode.ModePartieRapide) { Config = this }; return(game); }
private void OpenLocalGame(LocalGame localGame) { var formGameWindow = new FormGameWindow(); var gameWindowGui = formGameWindow.GetGameWindowGui(); gameWindowGui.SetGameData(localGame); localGame.SetGameView(gameWindowGui); formGameWindow.ShowDialog(); }
void SetActiveGame(LocalGame localGame) { List <LocalGame> activeGames = ActiveGames(localGame); foreach (LocalGame game in localGames) { SetEnabled(game, activeGames.Contains(game)); } activeGame = localGame; }
/// <summary> /// Return a deep copy of the given local game /// Listens to a new set of copied spots /// </summary> /// <param name="localGame"></param> /// <returns></returns> LocalGame CopyLocalGame(LocalGame localGame) { Spot[,] spots = new Spot[3, 3]; foreach (Spot spot in localGame.Spots) { // deep copy the array of spots spots[spot.Loc.Row, spot.Loc.Col] = CopySpot(spot); } return(new LocalGame(spots, localGame.Enabled, localGame.Loc)); }
public IGame CreateGame() { ConfigHelper.SaveConfig(Config); ConfigHelper.SaveDefaultZone(ObservableCollectionConverter.ConvertObservableCollection(MapConfig.SelectedZones).ConvertAll(ZoneModelConverter.ConvertZoneVM)); var game = new LocalGame(IntegratedOpenGl.Mode.ModeCampagne) { Config = this }; return(game); }
public void StartLocalGame(LocalGame localGame) { this._localGames.Add(localGame); localGame.Map.IsLocked = true; localGame.Map.OwnerId = localGame.UserId; // Sync map new MapRepository(new ApplicationDbContext()).UpdateMap(localGame.Map); // Launch task to sync the map AND its thumbnail Task.Run(async() => await this.SyncMapPeriodically(localGame.Map.Id, true, new MapRepository(new ApplicationDbContext()), localGame.SyncMapTaskCancellationToken.Token)); }
/// <summary> /// Toggles the outline of active games for the next turn, assuming /// the next active game will be <paramref name="nextActiveGame"/> /// </summary> /// <param name="nextActiveGame"></param> void Outline(LocalGame nextActiveGame, bool remove = false) { List <LocalGame> outlinedGames = base.GameOver() ? new List <LocalGame>() : ActiveGames(nextActiveGame); foreach (LocalGame game in localGames) { Color color = !remove && outlinedGames.Contains(game) ? OtherPlayer().Color : Color.clear; SetOutlined(game, color); } }
void SetEnabled(LocalGame localGame, bool value) { localGame.Enabled = value; foreach (Spot spot in localGame.Spots) { if (spot.Enabled != value && // don't bother doing nothing (!value || // can always disable a spot spot.Owner == null)) // can only enable empty spots { spot.Enabled = value; } } }
public static void StartLocalGame(Kingdom kingdom) { if (App.Context.CurrentGame != null) { App.Context.CurrentGame.CancelGame(); } Game game = new LocalGame(App.Context); App.Context.CurrentGame = game; game.GamePageModel.Kingdom = kingdom; game.PlayGame(); App.RootFrame.Navigate(typeof(GamePage)); game.ExitingGame += game_ExitingGame; }
private void bPlayLocal_Click(object sender, EventArgs e) { InGameForm ingameForm = new FormsPrototype.InGameForm(null, null, null); LocalGame game = GameBuilder.CreateLocalGame() .BlackPlayer(CreateAgentFromComboboxObject(ingameForm, this.cbBlack.SelectedItem, StoneColor.Black)) .WhitePlayer(CreateAgentFromComboboxObject(ingameForm, this.cbWhite.SelectedItem, StoneColor.White)) .Ruleset(RulesetType.Chinese) .Komi(7.5f) .BoardSize(new GameBoardSize((int)this.nLocalBoardSize.Value)) .Build(); ingameForm.LoadGame(game); ingameForm.Show(); }
public void StartGame() { var playingPlayers = GetAllLobbyPlayers().Where(x => x.PlayerPosition != PlayerPosition.Spectator).ToList(); if (playingPlayers.Count < 2) { throw new InvalidActionException("Not enough players."); } _server.OnClientConnected -= ServerOnOnClientConnected; _server.OnClientDisonnected -= ServerOnOnClientDisonnected; // TODO: postarat se o tyto handlery foreach (var lobbyPlayer in GetAllLobbyPlayers().Where(x => x.PlayerHandler != null)) { lobbyPlayer.PlayerHandler.GameStarting(); } // Game updaters var gameUpdaters = new List <IGameUpdater>(); var localGame = new LocalGame(_hostPlayer.PlayerId); gameUpdaters.Add(localGame); foreach (var lobbyPlayer in GetAllLobbyPlayers().Where(x => x.PlayerHandler != null)) { gameUpdaters.Add(new RemoteGameUpdater(lobbyPlayer.PlayerHandler.Receiver)); } var board = new BoardFactory().CreateBoard(); var gameSettings = new GameSettings(); // Build the game manager var gameManager = new GameManager(board, gameSettings, new MultipleGameUpdater(gameUpdaters), GetAllLobbyPlayers()); gameManager.DiceRolling = new DiceRolling(gameManager); gameManager.TurnLogic = new TurnLogic(gameManager); gameManager.Start(); var hostPlayer = gameManager.Players.Find(x => x.PlayerId == _hostPlayer.PlayerId); if (hostPlayer == null) { throw new FatalGameException("Invalid host player id"); } var hostPlayerController = new LocalPlayerController(hostPlayer); localGame.SetPlayerController(hostPlayerController); GameStarting?.Invoke(localGame); }
public override void OnPlayerKilled() { if (LocalGame.GetCurrentFloor() < 5) { Dialogue.AddDialogueLineTo(LocalGame, "I am not going to lie, but it's not looking good..."); } if (LocalGame.GetCurrentFloor() >= 5) { Dialogue.AddDialogueLineTo(LocalGame, "Looking but I am sorry to tell you, it's floor 10 now....just joking" + Environment.NewLine + "Grab your reward!"); questFinished = true; } }
public void StartLocalGame(IArtificialIntelligence aiPlayer, int aiDelayMs = 250) { IsInSinglePlayerMode = true; if (_localGame == null) { _localGame = new LocalGame { AiCommandDelay = aiDelayMs }; // TODO: WeakEventManager _localGame.SyncRequired += (sender, args) => { Application.Current.Dispatcher.Invoke(() => SyncLocalGame()); }; } _localGame.SetAi(aiPlayer); _localGame.InitGame(); SyncLocalGame(); }
public void TestSoundEmitter() { var engine = new LocalGame(); engine.AddSimulator(new AudioSimulator()); var emitter = new SoundEmitter(); emitter.Sound = SoundFactory.Load("Core\\TestSound.wav"); emitter.Playing = true; emitter.Loop = true; emitter = new SoundEmitter(); emitter.Sound = SoundFactory.Load("Core\\TestSoundAmbient.wav"); emitter.Playing = true; engine.Run(); }
private static Embed GenerateGameEmbed(LocalGame game) { EmbedBuilder builder = new EmbedBuilder { Title = game.Name, Description = game.Description, ImageUrl = game.BannerUri, ThumbnailUrl = game.PosterUri, Color = new Color(r: 163, g: 255, b: 0), Url = game.StorePageUrl, Author = new EmbedAuthorBuilder { IconUrl = "https://cdn.discordapp.com/attachments/598416605185310729/781731261525000232/epicgames_logo.png", Name = "Epic Games Store", Url = "https://www.epicgames.com/store/en-US/" }, Fields = new List <EmbedFieldBuilder> { new EmbedFieldBuilder { Name = "Developer", Value = game.Developer, IsInline = true }, new EmbedFieldBuilder { Name = "Publisher", Value = game.Publisher, IsInline = true }, new EmbedFieldBuilder { Name = "Available Until", Value = $"{game.EndDate.AddHours(11).ToString("dddd dd MMM yyyy - hh:mm tt")}\t(AEST w/Daylight Savings)\n" + $"{game.EndDate.ToString("dddd dd MMM yyyy - hh:mm tt")}\t(UTC)" }, } }; return(builder.Build()); }
public GlobalGame( LocalGame[,] localGames, bool enabled, Player p1, Player p2, bool p1Turn, LocalGame activeGame = null ) : base(enabled) { PopulateOwnerArray(localGames); this.localGames = localGames; this.p1 = p1; this.p2 = p2; this.p1Turn = p1Turn; nextMove = null; history = new Stack <Move>(); SetActiveGame(activeGame); future = new Stack <Move>(); canConfirm = false; canUndo = false; canRedo = false; canReset = false; availableSpots = new List <Spot>(); hasNextMove = false; // listen for when any spot in the game has been clicked foreach (LocalGame game in localGames) { foreach (Spot spot in game.Spots) { spot.Clicked += HandleSpotClicked; spot.EnabledChanged += HandleSpotEnabledChanged; if (game.Enabled && spot.Enabled) { availableSpots.Add(spot); } } } CheckWinner(); }
public void PlayBotGames(string[] args) { var localGame = new LocalGame { Verbose = args.Contains(VerboseArg) }; string gamesToPlayString = args.Where(gtp => gtp.StartsWith(GamesToPlayArg)) .Select(gtp => gtp.Substring(GamesToPlayArg.Length)).FirstOrDefault(); GamesToPlay = gamesToPlayString == null ? 100 : int.Parse(gamesToPlayString); int[] results = { 0, 0, 0 }; var player1 = new Player { Strategy = new AlphaBetaStrategy(new SimpleEvaluator(), 3) }; var player2 = new Player { Strategy = new AlphaBetaStrategy(new SimpleEvaluator(), 4) }; for (int gamesPlayed = 0; gamesPlayed < GamesToPlay; gamesPlayed++) { if (gamesPlayed % GameGroupSize == 0) { Console.WriteLine($"Playing next {GameGroupSize} games now @ game{gamesPlayed}"); } int result = localGame.PlayGame(player1, player2); results[result]++; } Console.WriteLine($"Draws: {results[0]}"); Console.WriteLine($"Player 1 wins(avg t= {player1.TimesPerMove.Average()}): {results[1]}"); Console.WriteLine($"Player 2 wins(avg t= {player2.TimesPerMove.Average()}: {results[2]}"); Console.WriteLine("All games played..."); }
private async Task AddScoreCollectionToHistory() { LocalGame game = new LocalGame(); game.NewGame(PlayerType.Computer, MainPage.Current.Deck); HandsFromServer hfs = game.ShuffleAndReturnAllCards(); List <CardView> crib = game.GetSuggestedCrib(PlayerType.Player, GameDifficulty.Hard); game.SendToCrib(PlayerType.Computer, crib); hfs.PlayerCards.Remove(crib[0]); hfs.PlayerCards.Remove(crib[1]); int scoreGuess = game.GetScore(PlayerType.Player, HandType.Regular); ScoreCollection scores = game.UpdateScore(PlayerType.Player, HandType.Regular, scoreGuess, GameDifficulty.Hard); List <CardView> cards = new List <CardView>(hfs.PlayerCards); _gridDeck.Items.Remove(hfs.SharedCard); _gridDeck.Items.Insert(0, hfs.SharedCard); await _view.AddToScoreHistory(cards, scores, PlayerType.Player); }
private void StartGameImmediately() { if (!Validate()) { return; } GamePlayer blackPlayer = BlackPlayer.Build(StoneColor.Black, TimeControl, BlackPlayerSettings); GamePlayer whitePlayer = WhitePlayer.Build(StoneColor.White, TimeControl, WhitePlayerSettings); BlackPlayerSettings.SaveAsInterfaceMementos(); WhitePlayerSettings.SaveAsInterfaceMementos(); LocalGame game = GameBuilder.CreateLocalGame(). BoardSize(SelectedGameBoardSize). Ruleset(SelectedRuleset). Komi(float.Parse(CompensationString, CultureInfo.InvariantCulture)). Handicap(Handicap). HandicapPlacementType( IsHandicapFixed ? HandicapPlacementType.Fixed : HandicapPlacementType.Free). WhitePlayer(whitePlayer). BlackPlayer(blackPlayer). Build(); Mvx.RegisterSingleton <IGame>(game); // Navigate to specific View Model if (_bundle.Style == GameCreationFormStyle.LocalGame) { OpenInNewActiveTab <LocalGameViewModel>(); } else { OpenInNewActiveTab <OnlineGameViewModel>(); } }
public void StartGame(Nou p1, IArtificialIntelligence p2) { P1 = p1; P2 = p2; if (Game != null) { Game.PropertyChanged -= Game_PropertyChanged; Game.SyncRequired -= Game_SyncRequired; } Round = 0; Game = new LocalGame(); Game.SetAi(p1, 1); Game.SetAi(p2, 2); Game.InitGame(); Game.AiCommandDelay = AiDelay; Game.PropertyChanged += Game_PropertyChanged; Game.SyncRequired += Game_SyncRequired; NeedsUiUpdate?.Invoke(this, EventArgs.Empty); ++Round; Task.Run(async() => await Game.AiPlayer1Move()); }
void SetOutlined(LocalGame game, Color color) { game.Outline = color; }
static void Main(string[] args) { // Given arguments saved to private properties CommandLine.Parser.Default.ParseArguments <Options>(args) .WithParsed(RunOptions) .WithNotParsed(HandleParseError); if (_stopArgsGiven) { return; } Log($"Chess ai vergiBlue [{_currentVersion}]"); while (true) { if (_gameMode <= 0) { // User did not explicitly set gamemode in command line arguments _gameMode = InputGameMode(); } if (_gameMode < 0) { break; } if (_gameMode == 1) { using var connection = new grpcClientConnection(_fullAddress); NetworkGame.Start(connection, _playerName, false); break; } else if (_gameMode == 2) { Log(Environment.NewLine); Log("Give player name: "); Console.Write(" > "); var playerName = Console.ReadLine() ?? _playerName; Log($"Chess ai {playerName} [{_currentVersion}]"); using var connection = new grpcClientConnection(_fullAddress); NetworkGame.Start(connection, playerName, false); break; } else if (_gameMode == 3) { LocalGame.Start(_minimumDelayBetweenMoves, null); } else if (_gameMode == 4) { LocalGame.Start(Math.Max(1000, _minimumDelayBetweenMoves), null); } else if (_gameMode == 5) { LocalGame.CustomStart(); } else if (_gameMode == 9) { using var connection = new grpcClientConnection(_fullAddress); NetworkGame.Start(connection, "Connection test AI", true); break; } else { break; } Log(Environment.NewLine); } }
protected override void OnWebSocketOpen() { var userToken = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token")); var mapIdString = this.Context.QueryString.Get("map_id"); Guid mapId; if (userToken == null || string.IsNullOrEmpty(mapIdString) || !Guid.TryParse(mapIdString, out mapId)) { this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters"); return; } this._warsimUser = this._gameManager.GetUser(userToken.UserId); if (this._warsimUser == null) { this.Sessions.CloseSession(this.ID, 2001, "This user isn't connected"); return; } var mapRepo = new MapRepository(new ApplicationDbContext()); var map = mapRepo.GetMapById(mapId); if (map == null) { this.Sessions.CloseSession(this.ID, 2002, "This map doesn't exist"); return; } var password = this.Context.QueryString.Get("map_password"); if (!map.ValidatePassword(password)) { this.Sessions.CloseSession(this.ID, 2003, "Wrong map password"); return; } if (map.IsLocked) { this.Sessions.CloseSession(this.ID, 2004, "This map is locked"); return; } this._localGame = new LocalGame { Map = map, UserId = this._warsimUser.UserId }; this._warsimUser.LocalGameWebSocketId = this.ID; this._gameManager.StartLocalGame(this._localGame); var localGameState = new LocalGameStateMessage { SceneObjects = map.SceneObjects }; this.Sessions.SendTo(EventBuilder.Build(localGameState).Serialize(), this._warsimUser.LocalGameWebSocketId); }
void HandleLocalWinnerChanged(object o, GameEventArgs e) { LocalGame localGame = (LocalGame)o; UpdateOwnerArray(localGame.Loc, localGame.Winner); }
private void OnHostGameStarting(LocalGame localGame) { LocalGame = localGame; OpenGameWindow = true; _view.CloseLobby(); }