/// <summary> /// Checks if the client is in a game. /// If so, the model attemps to fetch his opponent. /// if the opponent exists, a reply is sent to him. /// otherwise the function exists. /// if the game does not exist the function exists. /// </summary> /// <param name="from">the client that sent the command.</param> /// <param name="commandParsed">The parsed command.</param> public override void Execute(object from, string[] commandParsed) { string move = commandParsed[1]; int commandType = 4; object otherClient; PlayAnswer ans = new PlayAnswer(); // retrieve game MultiplayerGame game = model.IsClientInGame(from); if (game == null) { return; } // get the second player from the game game.RetrieveOtherClient(from, out otherClient); // a client tries to play while he's the only one in the game if (otherClient == null) { return; } ans.Name = game.GetName(); ans.Move = move; string reply = new Answer().GetJSONAnswer(commandType, ans); model.CompletedTask(otherClient, new View.MessageEventArgs(reply)); }
/// <summary> /// </summary> public PlayerListHeader(MultiplayerGame game) { Game = game; Size = new ScalableVector2(590, 36); Tint = Color.Black; Alpha = 0f; Count = new SpriteTextBitmap(FontsBitmap.GothamRegular, "(0/16) Players") { Parent = this, Alignment = Alignment.TopRight, FontSize = 16, }; Status = new SpriteTextBitmap(FontsBitmap.GothamRegular, "Waiting to start") { Parent = this, Alignment = Alignment.TopLeft, FontSize = 16, }; // ReSharper disable once ObjectCreationAsStatement new Sprite { Parent = this, Alignment = Alignment.TopCenter, Size = new ScalableVector2(Width, 2), Y = Status.Y + Status.Height + 12, Alpha = 0.85f }; }
public dynamic Join(Player player, string roomId) { dynamic ret; try { MultiplayerGame multiplayerGame = null; if ((multiplayerGame = _mastermindRepository.GetRoomWaitingforPlayer(roomId)) == null) { Room room = new Room(roomId); multiplayerGame = new MultiplayerGame(room); multiplayerGame.SetupNewGame(); multiplayerGame.SetPlayer(player); _mastermindRepository.Insert(multiplayerGame); ret = new { Gamekey = multiplayerGame.Gamekey, RoomId = room.RoomId, Message = "You are joined. Waiting for the second player!" }; } else { multiplayerGame.SetPlayer(player); multiplayerGame.Room.SetRoomIsFull(); _mastermindRepository.Replace(multiplayerGame); ret = new { Gamekey = multiplayerGame.Gamekey, RoomId = multiplayerGame.Room.RoomId, Message = "You are joined. Please wait for start the game." }; } } catch (Exception ex) { throw ex; } return(ret); }
/// <inheritdoc /> /// <summary> /// </summary> /// <param name="game"></param> public JoinPasswordedGameDialog(MultiplayerGame game) : base(0) { Game = game; FadeTo(0.85f, Easing.Linear, 150); CreateContent(); }
/// <summary> /// </summary> public void CreateGame() { if (MapManager.Selected.Value == null) { NotificationManager.Show(NotificationLevel.Error, "You cannot create a game without having a map selected!"); return; } if (string.IsNullOrEmpty(GameName.Textbox.RawText) || string.IsNullOrWhiteSpace(GameName.Textbox.RawText)) { NotificationManager.Show(NotificationLevel.Error, "You must provide a valid game name."); return; } DialogManager.Show(new JoiningGameDialog(JoiningGameDialogType.Creating)); ThreadScheduler.Run(() => { var game = MultiplayerGame.CreateCustom(MultiplayerGameType.Friendly, GameName.Textbox.RawText, Password.Textbox.RawText, int.Parse(MaxPlayers.Selector.SelectedItemText.Text), MapManager.Selected.Value.ToString(), MapManager.Selected.Value.MapId, MapManager.Selected.Value.MapSetId, Enum.Parse <MultiplayerGameRuleset>(Ruleset.Selector.SelectedItemText.Text.Replace("-", "_")), AutoHostRotation.Selector.SelectedItemText.Text == "Yes", (byte)MapManager.Selected.Value.Mode, MapManager.Selected.Value.DifficultyFromMods(ModManager.Mods), MapManager.Selected.Value.Md5Checksum, MapManager.Selected.Value.GetDifficultyRatings(), MapManager.Selected.Value.GetJudgementCount(), MapManager.Selected.Value.GetAlternativeMd5()); OnlineManager.Client.CreateMultiplayerGame(game); }); Dialog.Close(); }
public void Replace(MultiplayerGame game) { var originalGame = _multiplayerGameCollection.Find(g => g._id == game._id) .ToList().First(); _multiplayerGameCollection.ReplaceOne(c => c._id == originalGame._id, game); }
private void RecycleCurrentGame() { games.Add(currentGame); currentGameIndex++; currentGame = new MultiplayerGame(currentGameIndex); }
/// <summary> /// Attempts to fetch a game from the model's data. /// If the game does not exist, a check is performed to see if the sending client is in a different game. /// if so, the function closes. /// Otherwise we create the game, and add the client to the game. /// Otherwise, if the game exists, the model attemps to add the client to the game. /// if succeeded, the game now contains 2 different client, so a maze is generated, /// given a name, and sent to the first client. /// then a different starting position is given to the same maze and it is sent to the second client. /// if the client could not be added to the game the function exists. /// </summary> /// <param name="from">the client that sent the command.</param> /// <param name="commandParsed">The parsed command.</param> public override void Execute(object from, string[] commandParsed) { string name = commandParsed[1]; int commandType = 3; MultiplayerGame g = model.GetMultiplayerGame(name); // game does not exist if (g == null) { // client is already in a different multiplayer game if (model.IsClientInGame(from) != null) { return; } // otherwise create a game IMaze maze = GenerateOption.CreateMaze(1); MultiplayerGame game = new MultiplayerGame(model, name, maze); game.AddClient(from); model.AddMultiplayerGame(name, game); } // game exists else { // add second(different) client to game, and if the game had not been started yet if (g.AddClient(from) && !g.IsInProgress()) { g.GameStarted(); string reply; IMaze maze = g.GetMaze(); IMaze secondMaze; object client; string mazeName; // generate answer for first client mazeName = name + "_1"; this.model.AddMaze(mazeName, maze); GenerateAnswer firstClient = BuildMaze(maze, mazeName); // change starting position for second client mazeName = name + "_2"; secondMaze = maze.CreateMazeChangeStartPosition(); this.model.AddMaze(mazeName, secondMaze); GenerateAnswer secondClient = BuildMaze(secondMaze, mazeName); // first client g.RetrieveOtherClient(from, out client); reply = BuildReply(name, commandType, firstClient, secondClient); model.CompletedTask(client, new View.MessageEventArgs(reply)); // second client ('from' is the second player) client = from; reply = BuildReply(name, commandType, secondClient, firstClient); model.CompletedTask(client, new View.MessageEventArgs(reply)); } } }
public Boolean CreateGame(MultiplayerGame game) { this.Connect(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "INSERT INTO `games` (username, gamename, mapname, ip) " + "VALUES('" + game.username + "', '" + game.gamename + "', '" + game.mapname + "', '" + game.hostIP + "');"; Socket. command.ExecuteNonQuery(); this.Disconnect(); }
void Start() { Debug.Log ("!!! MULTIPLAYER INITIATED !!!"); _instance = this; bf = BattlefieldScript.Instance; bfc = bf.bf; su = Submarine.Instance; sh = Ship.Instance; la = LanguageScript.Instance; mo = move.Instance; reward = new Reward (false, 5); }
private MultiplayerGameView GetMultiplayerGameView(MultiplayerGame game) => new MultiplayerGameView { Id = game.Id, Timestamp = game.Timestamp, NumberOfPlayers = game.NumberOfPlayers, Usernames = game.Usernames, NumberOfOrbs = game.NumberOfOrbs, Seed = game.Seed, Altar = game.Altar, Score = game.Score };
/// <summary> /// /// </summary> /// <param name="game"></param> /// <param name="playTrackOnFirstUpdate"></param> public MultiplayerScreen(MultiplayerGame game, bool playTrackOnFirstUpdate = false) { Game = game; PlayTrackOnFirstUpdate = playTrackOnFirstUpdate; SetRichPresence(); OnlineManager.Client.OnGameStarted += OnGameStarted; OnlineManager.Client.OnGameCountdownStart += OnCountdownStart; OnlineManager.Client.OnGameCountdownStop += OnCountdownStop; View = new MultiplayerScreenView(this); }
private async Task RunMultiplayerGame <TGame>(params SocketUser[] players) where TGame : MultiplayerGame { var existingGame = Games.GetForChannel(Context.Channel.Id); if (existingGame != null) { await ReplyAsync(existingGame.UserId.Contains(Context.User.Id) ?$"You're already playing a game in this channel!\nUse `{Prefix}cancel` if you want to cancel it." : $"There is already a different game in this channel!\nWait until it's finished or try doing `{Prefix}cancel`"); return; } var game = MultiplayerGame.CreateNew <TGame>(Context.Channel.Id, players, Services); Games.Add(game); while (!game.AllBots && game.BotTurn) { game.BotInput(); // When a bot starts } var gameMessage = await ReplyAsync(game.GetContent(), game.GetEmbed()); game.MessageId = gameMessage.Id; if (game.AllBots) { while (game.State == State.Active) { try { game.BotInput(); if (game.MessageId != gameMessage.Id) { gameMessage = await game.GetMessage(); } game.CancelRequests(); if (gameMessage != null) { await gameMessage.ModifyAsync(game.GetMessageUpdate(), game.GetRequestOptions()); } } catch (Exception e) when(e is OperationCanceledException || e is TimeoutException || e is HttpException) { } await Task.Delay(Bot.Random.Next(1000, 2001)); } Games.Remove(game); } }
// Initialization. void Awake() { if (!_instance) { _instance = this; } logger.info("Initializing Game object."); PromptManager = new MultiplayerPrompt(promptObj, promptTxt, gameStatus); NormalMode(); discardButton.GetComponent <Button>().onClick.AddListener(discardHandler); showHandButton.GetComponent <Button>().onClick.AddListener(unflipHand); showPlayerButton.GetComponent <Button>().onClick.AddListener(OpenShowPlayer); exitShowPlayerButton.GetComponent <Button>().onClick.AddListener(CloseShowPlayer); }
/// <summary>Attempts to create a <typeparamref name="TGame"/> for this context.</summary> public async Task StartNewMPGameAsync(CommandContext ctx, params DiscordUser[] players) { if (await CheckGameAlreadyExistsAsync(ctx)) { return; } var game = StartNewGame(await MultiplayerGame.CreateNewAsync <TGame>(ctx.Channel.Id, players, Services)); while (await game.IsBotTurnAsync()) { await game.BotInputAsync(); // When a bot starts } await RespondGameAsync(ctx); }
private MultiplayerGame GetAvailableGame() { if (currentGame == null) { currentGame = new MultiplayerGame(currentGameIndex); } //Not available situation if (currentGame.isReady) { RecycleCurrentGame(); } return(currentGame); }
public void Setup() { Rep = new Mock <IPlayerRepository>(); MessageService = new Mock <IMessageService>(); Servise = new GameServices(Rep.Object, MessageService.Object); Player = new PlayerModel() { Name = "Alexey", Scores = new Dictionary <string, int>() }; MultiPlayer = new MultiplayerGame(Player, MessageService.Object); Validator = new Mock <IValidator>(); ControlServices = new Mock <IControlServices>(); MultiPlayer.gameResources.GameType = "Multiplayer"; }
/// <summary> /// Checks if a given client is in a game. If so, he is removed, and if the game contains 0 players /// it is removed from the model. /// Otherwise, nothing is done. /// </summary> /// <param name="from">the client that sent the command.</param> /// <param name="commandParsed">The parsed command.</param> public override void Execute(object from, string[] commandParsed) { MultiplayerGame game = model.IsClientInGame(from); if (game == null) { return; } game.RemoveClient(from); // game is empty if (game.Count == 0) { model.RemoveMultiplayerGame(game.GetName()); } }
public void Post(ICollection <string> playerNames, int numberOfOrbs, int seed, int altar, int score, string code) { var game = new MultiplayerGame { Timestamp = DateTimeOffset.Now, NumberOfPlayers = playerNames.Count, Usernames = string.Join("; ", playerNames), NumberOfOrbs = numberOfOrbs, Seed = seed, Altar = altar, Score = score, Code = code }; DbContext.MultiplayerGames.Add(game); DbContext.SaveChanges(); }
private bool IsFinished(MultiplayerGame currentGame, out string resultMessage) { resultMessage = ""; if (currentGame.IsSolved()) { resultMessage = "Game is solved. Congratulations!"; } if (currentGame.Timeout()) { resultMessage = "Games has expired. Please, start over!"; } if (currentGame.CodeBreaker.TryLimitExpired()) { resultMessage = "You already reached the limit of tries. Please, start over!"; } return(currentGame.IsSolved() || currentGame.Timeout() || currentGame.CodeBreaker.TryLimitExpired()); }
private void StartGameButtonClick(object sender, RoutedEventArgs e) { if (this.CheckAllFields()) { MessageBox.Show("You must fill in all text fields!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error); } else { Player firstPlayer = new Player(this.FirstPlayerName.Text); Player secondPlayer = new Player(this.SecondPlayerName.Text); Category gameCategory = new Category(this.Category.Text); Word gameWord = new Word(this.Word.Text); WordChecker checker = new WordChecker(gameWord); MultiplayerGame game = new MultiplayerGame(firstPlayer, secondPlayer, gameCategory, gameWord, checker); MultiplayerGameUI gameUI = new MultiplayerGameUI(game); this.NavigationService.Navigate(gameUI); } }
public void ChooseGameType() { MessageService.ChooseGameTypeMessage(); switch (new ControlService().ReadIntFromConsole(new GameTypeValidator())) { case 1: var soloGame = new SoloGame(Player, MessageService); soloGame.PlayOneRound(); break; case 2: var multiPlayer = new MultiplayerGame(Player, MessageService); multiPlayer.PlayOneRound(); break; default: break; } }
public void PostSolo(int numberOfPlayers, int numberOfOrbs, int seed, int altar, int score, string code) { var username = DbContext.GetUsername(GopUser.GetCurrentUser(HttpContext)); var usernames = string.Join("; ", Enumerable.Repeat(username, numberOfPlayers)); var game = new MultiplayerGame { Timestamp = DateTimeOffset.Now, NumberOfPlayers = numberOfPlayers, Usernames = usernames, NumberOfOrbs = numberOfOrbs, Seed = seed, Altar = altar, Score = score, Code = code }; DbContext.MultiplayerGames.Add(game); DbContext.SaveChanges(); }
/// <summary>Attempts to create a <typeparamref name="TGame"/> for this context.</summary> public async Task RunGameAsync(params SocketUser[] players) { if (await CheckGameAlreadyExistsAsync()) { return; } StartNewGame(await MultiplayerGame.CreateNewAsync <TGame>(Context.Channel.Id, players, Services)); while (!Game.AllBots && Game.BotTurn) { await Game.BotInputAsync(); // When a bot starts } var msg = await ReplyGameAsync(); if (Game.AllBots) // Bot loop { while (Game.State == GameState.Active) { try { await Game.BotInputAsync(); msg = await UpdateGameMessageAsync(); if (msg == null) { break; } } catch (OperationCanceledException) { } catch (TimeoutException) { } catch (HttpException) { } // All of these are connection-related and ignorable in this situation await Task.Delay(Program.Random.Next(2500, 4001)); } EndGame(); } }
//SERVER ACTIONS private void CreateNewPlayer(ServerData data) { Payload payload = DatagramToPayload(data.datagram); currentGame = GetAvailableGame(); if (payload != null && string.IsNullOrEmpty(payload.clientID)) { Player player = new Player(data.endPoint); currentGame.AddPlayer(player); playerList.Add(player.endPoint, currentGame.index - 1); payload.clientID = player.clientID; data.datagram = DataSerializer.SerializePayload(payload); listener.Send(data.datagram, data.datagram.Length, data.endPoint.Address.ToString(), data.endPoint.Port); } if (currentGame.isReady) { RecycleCurrentGame(); } }
private void DoGameLogics(ServerData data) { Payload payload = DatagramToPayload(data.datagram); if (payload != null && !string.IsNullOrEmpty(payload.clientID)) { int gamesRunning = games.Count; if (gamesRunning > 0) { int gameIndex = playerList[data.endPoint]; if (gameIndex <= gamesRunning - 1) { MultiplayerGame game = games[gameIndex]; if (game != null && game.isReady) { game.DoLogics(listener, payload.clientID, data.datagram); } } } } }
public MultiplayerGameUI(MultiplayerGame game) { InitializeComponent(); this.game = game; this.FirstPlayer.Content = this.game.Player.PlayerName; this.SecondPlayer.Content = this.game.SecondPlayer.PlayerName; this.Category.Content = this.game.Category.CategoryName; if (this.game.Word.GameWord.Contains(' ')) { this.WordLength.Content = this.game.Word.GameWord.Length - 1; } else { this.WordLength.Content = this.game.Word.GameWord.Length; } this.wordBuilder = new WordBuilder(this.WordPanel, this.game.Word); this.hangman = new Hangman(this.HangmanDrawing); this.letterCount = 0; wordBuilder.BuildWord(this.game.Word); }
/// <summary> /// Removes the game from the list entirely. /// </summary> /// <param name="game"></param> public void DeleteGame(MultiplayerGame game) { var view = (LobbyScreenView)View; view.MatchContainer.DeleteObject(game); }
/// <summary> /// If the match currently isn't in the list, it'll add it. /// Otherwise, it'll update the contents of the game. /// </summary> /// <param name="game"></param> public void AddOrUpdateGame(MultiplayerGame game) { var view = (LobbyScreenView)View; view.MatchContainer.AddOrUpdateGame(game); }
void Start() { multiplayerP = FindObjectOfType <MultiplayerGame>(); }
/// <summary> /// </summary> public MultiplayerMap(MultiplayerScreen screen, MultiplayerGame game) : base(new ScalableVector2(682, 86), new ScalableVector2(682, 86)) { Screen = screen; Game = game; Size = new ScalableVector2(650, 86); Image = UserInterface.MapPanel; DownloadButton = new ImageButton(UserInterface.BlankBox, OnDownloadButtonClicked) { Parent = this, Alignment = Alignment.MidCenter, Size = new ScalableVector2(Width - 4, Height - 4), Alpha = 0 }; Background = new Sprite { Parent = this, Size = new ScalableVector2(Height * 1.70f, Height - 4), Alignment = Alignment.MidLeft, X = 2, Image = MapManager.Selected.Value == BackgroundHelper.Map && MapManager.Selected.Value.Md5Checksum == Game.MapMd5 ? BackgroundHelper.RawTexture: UserInterface.MenuBackground, Alpha = MapManager.Selected.Value == BackgroundHelper.Map && MapManager.Selected.Value.Md5Checksum == Game.MapMd5 ? 1 : 0 }; AddContainedDrawable(Background); var diffName = GetDifficultyName(); ArtistTitle = new SpriteTextBitmap(FontsBitmap.GothamRegular, game.Map.Replace($"[{diffName}]", "")) { Parent = this, X = Background.X + Background.Width + 16, Y = 12, FontSize = 16 }; AddContainedDrawable(ArtistTitle); Mode = new SpriteTextBitmap(FontsBitmap.GothamRegular, "[" + ModeHelper.ToShortHand((GameMode)game.GameMode) + "]") { Parent = this, X = ArtistTitle.X, Y = ArtistTitle.Y + ArtistTitle.Height + 8, FontSize = 14 }; AddContainedDrawable(Mode); DifficultyRating = new SpriteTextBitmap(FontsBitmap.GothamRegular, $"{game.DifficultyRating:0.00}") { Parent = this, X = Mode.X + Mode.Width + 8, Y = Mode.Y, FontSize = 14, Tint = ColorHelper.DifficultyToColor((float)game.DifficultyRating) }; AddContainedDrawable(DifficultyRating); DifficultyName = new SpriteTextBitmap(FontsBitmap.GothamRegular, " - \"" + diffName + "\"") { Parent = this, X = DifficultyRating.X + DifficultyRating.Width + 2, Y = Mode.Y, FontSize = 14, }; AddContainedDrawable(DifficultyName); Creator = new SpriteTextBitmap(FontsBitmap.GothamRegular, "Mods: None") { Parent = this, X = Mode.X, Y = DifficultyRating.Y + DifficultyRating.Height + 8, FontSize = DifficultyRating.FontSize }; AddContainedDrawable(Creator); BackgroundHelper.Loaded += OnBackgroundLoaded; OnlineManager.Client.OnGameMapChanged += OnGameMapChanged; OnlineManager.Client.OnChangedModifiers += OnChangedModifiers; OnlineManager.Client.OnGameHostSelectingMap += OnGameHostSelectingMap; ModManager.ModsChanged += OnModsChanged; BackgroundHelper.Load(MapManager.Selected.Value); UpdateContent(); }
public override void Initialize(string networkAddress, int networkHostId, int networkConnectionId, HostTopology hostTopology) { base.Initialize(networkAddress, networkHostId, networkConnectionId, hostTopology); Game = NetworkManager.singleton.GetComponent <MultiplayerGame>(); }