public void CreateNewGame() { Program.LogMsg($"Getting Lock..", Discord.LogSeverity.Critical, "CreateNewGame"); if (!OnlineLock.WaitOne(60 * 1000)) { Program.LogMsg($"Failed Lock..", Discord.LogSeverity.Critical, "CreateNewGame"); RespondRaw("Unable to get lock", 500); return; } try { Program.LogMsg($"Got Lock..", Discord.LogSeverity.Critical, "CreateNewGame"); if (CurrentGame != null) { RespondRaw("Game already in progress", 400); return; } CurrentGame = new OnlineGame(); Program.LogMsg($"Released Lock..", Discord.LogSeverity.Critical, "CreateNewGame"); CurrentGame.SendLogStart(SelfPlayer.Name); WebSockets.ChessConnection.log($"Game created and thus White is: {SelfPlayer.Name}"); RespondRaw("", 201); } catch { throw; } finally { OnlineLock.Release(); } }
public WaitingWindow(OnlineGame onlineGame, ShipArrangement arrangment, PlacementState placement) { InitializeComponent(); OnlineGame = onlineGame; Arrangment = arrangment; Placement = placement; }
public LoadArrangementWindow(ShipArrangement arrangementClient, GameConfig gameConfig, OnlineGame onlineGame) { _arrangementClient = arrangementClient; _gameConfig = gameConfig; _onlineGame = onlineGame; InitializeComponent(); List <string> list = FileSystem.SavedArrangementList(); if (list != null) { int i = 0; Button button; foreach (string str in list) { string[] tmp = str.Split('\\', '.'); string str1 = ""; str1 += tmp[1]; str1 = str1.TrimEnd('.'); button = new Button(); button.Content = str1; button.Click += SaveButton_Click; LoadGrid.Children.Add(button); Grid.SetRow(button, i); i++; } } }
private void ButtonNext_Click(object sender, RoutedEventArgs e) { try { OnlineGame = new OnlineGame(PlayerRole.Client, _placement, ServerUtils.StringToIP(KeyTextBox.Text)); Thread.Sleep(2000); if (_placement != PlacementState.Manualy) { OnlineGame.CreateGame(_shipArrangement); PlayPage window = new PlayPage(OnlineGame); WindowConfig.MainPage.NavigationService.Navigate(window, UriKind.Relative); } else { PlacingPage window = new PlacingPage(OnlineGame); WindowConfig.MainPage.NavigationService.Navigate(window, UriKind.Relative); } Close(); } catch (IndexOutOfRangeException exception) { LogService.Trace($"Невозможно подключиться: {exception.Message}"); MessageBox.Show("Вы ввели неправильный ключ. Повторите попытку", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning); } catch (Exception exception) { LogService.Trace($"Невозможно подключиться: {exception.Message}"); MessageBox.Show($"Ошибка подключения к серверу", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning); } }
public ActionResult play(int id) { if (db.WaitedGames.Where(z => z.DesignedGameId == id).Count() > 0) { var s = Session["username"].ToString(); OnlineGame o = new OnlineGame(); o.DesignedGameId = id; o.Player1User = db.WaitedGames.Where(z => z.DesignedGameId == id).First().Username; o.Player2User = s; db.WaitedGames.Remove(db.WaitedGames.First()); db.OnlineGames.Add(o); db.SaveChanges(); Session["gameid"] = db.OnlineGames.Where(u => u.Player2User == s).First().Id; if (db.DesignedGames.Where(u => u.Id == id).First().DiceCount == 1) { return(RedirectToAction("Index", "Game")); } else { return(RedirectToAction("TwoDice", "Game")); } } else { WaitedGame w = new WaitedGame(); w.Username = Session["username"].ToString(); w.DesignedGameId = id; db.WaitedGames.Add(w); db.SaveChanges(); Session["message"] = "you added succesfully to game " + id; return(RedirectToAction("ChooseGame", "Home")); } }
public PlayField() { InitializeComponent(); timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += Tick; Game gg = WindowConfig.game; _onlineGame = WindowConfig.OnlineGame; CellStatе[,] myArr; CellStatе[,] enemyArr; if (!(_onlineGame is null)) { _isOnlineGame = true; gg = _onlineGame.Game; if (_onlineGame.PlayerRole == PlayerRole.Client) { myArr = _onlineGame.MyArrangement.GetArrangement(); enemyArr = _onlineGame.EnemyArrangement.GetArrangement(); ThreadPool.QueueUserWorkItem(OnlineEnemyTurn); } else { myArr = gg.ServerShipArrangement.GetArrangement(); enemyArr = gg.ClientShipArrangement.GetArrangement(); } }
private void ExitGame() { if (_currentGame != null) { _currentGame.Exit(); _currentGame = null; } }
private void importProject(OnlineGame onlineProject) { string relativePath = Path.Combine(@"download", @$ "{onlineProject.Hash}.zip"); string filename = store.GetFullPath(relativePath); ProjectInfo futureInfo = new ProjectInfo { File = new File { NewName = Path.GetFileNameWithoutExtension(filename), Type = "project" }, CreatorID = onlineProject.Creator.ID, CommunityStatus = onlineProject.Status, LastEdited = onlineProject.DateTimeLastEdited, MaxNumberPlayers = onlineProject.Maxplayers, MinNumberPlayers = onlineProject.Minplayers, Name = onlineProject.Name, Description = onlineProject.Description, OnlineProjectID = onlineProject.Id, }; using (var fileStream = store.GetStream(filename, FileAccess.Read, FileMode.Open)) { using (ZipFile zip = ZipFile.Read(fileStream)) { foreach (ZipEntry e in zip) { e.Extract(store.GetFullPath("files"), ExtractExistingFileAction.DoNotOverwrite); if (e.FileName == futureInfo.File.NewName) { continue; } var file = database.Files.FirstOrDefault(f => f.NewName == e.FileName) ?? new File { NewName = e.FileName, Type = "image" }; futureInfo.Relations.Add(new FileRelation { Project = futureInfo, File = file }); } } } database.Add(futureInfo); database.SaveChanges(); futureInfo.ImageRelation = futureInfo.Relations.FirstOrDefault(r => r.File.NewName == onlineProject.Image); WorkingProject.Parse(futureInfo, store, textures, api); database.SaveChanges(); store.Delete(relativePath); onlineProjectsList.Remove(onlineProjectsList.Children.First(o => o.ID == onlineProject.Id)); projectsList.Add(new LocalProjectSummaryContainer(futureInfo) { EditAction = openProject, DeleteAction = deleteProject }); }
public IGame CreateGame() { if (!Validate()) { throw new Exception("The game option are not valid"); } var game = new OnlineGame(GetOpenGlMode(), GetGameModel()); return(game); }
//Todo: remove hack of is host /// <summary> /// Create the game wrapper and join the waiting room /// </summary> /// <param name="id"></param> private void JoinWaitingRoom(string id, bool isHost = false, string password = null) { var game = GameAccess.Instance.GetGameInfo(id); game.Password = password; // Todo: refactor game mode _currentGame = new OnlineGame(game.ZonesHashId.Count > 1 ? IntegratedOpenGl.Mode.ModeCampagne : IntegratedOpenGl.Mode.ModePartieRapide, game); _currentGame.IsHost = isHost; EnterSubstate(OnlineSubstate.WaitingRoom); // Todo: make this async _currentGame.Load(); }
static public GameplayState CreateGameplayState(Match.SetData _setData, GameplayRenderer _renderer, bool _online) { GameplayState gs; if (_online) { gs = new OnlineGame(_setData); } else { gs = new OfflineGame(_setData); } gs.GameplayRendererObject = _renderer; gs.StateRenderer = _renderer; return(gs); }
public PlayPage(OnlineGame onlineGame) { WindowConfig.PlayPageCon = this; WindowConfig.OnlineGame = onlineGame; WindowConfig.IsLoaded = onlineGame.GameConfig.GameStatus == GameStatus.Loaded; OnlineGame = onlineGame; WindowConfig.GameState = WindowConfig.State.Online; InitializeComponent(); WindowConfig.GetCurrentAudioImg(AudioImg); MyField.PlaceHitted(); EnemyField.PlaceHitted(); PauseItem.IsEnabled = OnlineGame.PlayerRole == PlayerRole.Server; SaveGameItem.IsEnabled = OnlineGame.PlayerRole == PlayerRole.Server; WindowConfig.SetStartColor(); IsPaused = false; //ImageBehavior.SetAnimatedSource(TimerImage, new BitmapImage(new Uri("/Resources/timer.gif", UriKind.Relative)) { CreateOptions = BitmapCreateOptions.IgnoreImageCache }); //ImageBehavior.SetAnimateInDesignMode(TimerImage, true); GameSpeed gs = WindowConfig.GameState == WindowConfig.State.Online ? OnlineGame.GameConfig.GameSpeed : Game.GameConfig.GameSpeed; switch (gs) { case GameSpeed.Fast: timer.Interval = new TimeSpan(0, 0, 0, 1, 250); break; case GameSpeed.Medium: timer.Interval = new TimeSpan(0, 0, 0, 2, 500); break; case GameSpeed.Slow: timer.Interval = new TimeSpan(0, 0, 0, 5); break; case GameSpeed.Turtle: timer.Interval = new TimeSpan(0, 0, 0, 12, 500); break; } // timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += Tick; // timer.Start(); InitTimer(); Timer.Start(); timer.Start(); }
public GameWindow(LoginData loginData, string placement, GameMode gameMode, OnlineGame gameData = null) { InitializeComponent(); this._placement = placement; this.gameMode = gameMode; this.loginData = loginData; if (gameMode == GameMode.Online) { this.gameData = gameData; this.LabelFirstPlayer.Content = gameData.FirstPlayerName; this.LabelSecondPlayer.Content = gameData.SecondPlayerName; this.LabelGameState.Content = gameData.GameState; this.LabelGameName.Content = gameData.Name; HubConnectAsync(); } else if (gameMode == GameMode.Multiplayer) { this.LabelFirstPlayer.Content = this.loginData.UserName; this.LabelGameName.Content = "Multiplayer"; this.LabelSecondPlayer.Content = "Other guy"; this.gameData = new MultiPlayerGame() { FirstPlayerName = this.loginData.UserName, SecondPlayerName = "Other guy", EnumGameState = GameState.FirstPlayer, Field = new String('0', 9), Name = "Multiplayer" }; } else if (gameMode == GameMode.Singleplayer) { this.LabelFirstPlayer.Content = this.loginData.UserName; this.LabelGameName.Content = "Singleplayer"; this.LabelSecondPlayer.Content = "Bot"; this.gameData = new SinglePlayerGame() { FirstPlayerName = this.loginData.UserName, EnumGameState = GameState.FirstPlayer, Field = new String('0', 9), Name = "Singleplayer" }; } }
private void joinRoom(int id, OnlineGame downloadGame) { var downloadComplete = game.DownloadGame(downloadGame); Task.Run(async() => { await downloadComplete.Task; if (downloadComplete.Task.Result == false) { failure(); return; } var room = new AcceptInviteRequest(id); room.Success += u => { Schedule(() => { LoadComponentAsync(new RoomScreen(u), roomScreen => { stack.Push(roomScreen); Hide(); sideMenu.Hide(); }); game.Invitations.Remove(game.Invitations.First(i => i.ID == id)); invitationsContainer.Remove(invitationsContainer.FirstOrDefault(c => c.Invitation.ID == id)); }); }; room.Failure += ex => { failure(); }; api.Queue(room); void failure() { Schedule(() => infoOverlay.Show(@"Ocurrió un error al intentar unirse a la sala", Colour4.DarkRed)); } }); }
private void Button_Click(object sender, RoutedEventArgs e) { Game game = FileSystem.LoadGame(((Button)sender).Content.ToString()); if (game.GameConfig.IsOnline) { OnlineGame onlineGame = new OnlineGame(PlayerRole.Server, PlacementState.Loaded); onlineGame.Game = game; WindowConfig.IsLoaded = true; WaitingWindow window = new WaitingWindow(onlineGame, null, PlacementState.Loaded); window.SetNavigationService(NavigationService); window.Show(); window.Wait(); } else { WindowConfig.game = game; WindowConfig.IsLoaded = true; PlayPage playPage = new PlayPage(WindowConfig.game); NavigationService.Navigate(playPage, UriKind.Relative); } }
public void Wait() { while (!OnlineGame.Connect.Server.IsClientConnected) { } if (Placement == PlacementState.Manualy) { PlacingPage window = new PlacingPage(OnlineGame); WindowConfig.MainPage.NavigationService.Navigate(window, UriKind.Relative); } else if (Placement == PlacementState.Loaded) { OnlineGame.LoadGame(OnlineGame.Game); PlayPage window = new PlayPage(OnlineGame); _nService.Navigate(window, UriKind.Relative); } else { OnlineGame.CreateGame(Arrangment); PlayPage window = new PlayPage(OnlineGame); WindowConfig.MainPage.NavigationService.Navigate(window, UriKind.Relative); } Close(); }
public TaskCompletionSource <bool> DownloadGame(OnlineGame game) { var completionSource = new TaskCompletionSource <bool>(); var files = store.GetStorageForDirectory("files").GetFiles(""); var getFilenamesForGame = new GetFileListForGameRequest(game.Id); getFilenamesForGame.Success += gameFiles => { var missingFiles = new Queue <string>(gameFiles.Except(files).ToArray()); if (missingFiles.Count == gameFiles.Count) { var getGame = new DownloadProjectRequest(game.Id, game.Hash, store); getGame.Success += g => { completionSource.SetResult(true); importGame(game.Hash); }; getGame.Progressed += _ => { infoOverlay.Show(@"Descargando juego...", Colour4.Turquoise); }; getGame.Failure += _ => failure(); api.Queue(getGame); } else { Task.Run(() => { while (missingFiles.Count > 0) { var getFile = new DownloadSpecificFileRequest(missingFiles.Dequeue(), store); var fileDownloaded = false; getFile.Success += () => { fileDownloaded = true; }; getFile.Progressed += current => { Schedule(() => infoOverlay.Show(@$ "Descargando archivos faltantes (faltan {missingFiles.Count + 1})...", Colour4.Turquoise)); }; getFile.Failure += _ => { missingFiles.Clear(); failure(); }; api.Queue(getFile); while (!fileDownloaded && missingFiles.Count > 0) { } } completionSource.SetResult(true); }); } }; getFilenamesForGame.Failure += _ => failure(); api.Queue(getFilenamesForGame); return(completionSource); void failure() { completionSource.SetResult(false); infoOverlay.Show(@"Error al descargar el juego!", Colour4.DarkRed); } }
public ConfigOnlineHostWindow() { InitializeComponent(); OnlineGame = new OnlineGame(PlayerRole.Server, _placement); }
public GamePreviewContainer(OnlineGame game) { this.game = game; }
public OnlineGameForm(OnlineGame onlineGame) { _onlineGame = onlineGame; InitializeComponent(); }
void handleMessage(Packet ping) { this.Game = this.Game ?? new OnlineGame(); if (ping.Id == PacketId.MoveMade) { GameForm.AuthorativeMove(ping); } else if (ping.Id == PacketId.MoveRequestRefuse) { GameForm.RefusedMove(ping); } else if (ping.Id == PacketId.PlayerIdent) { var player = new ChessPlayer(); var id = ping.Content["id"].ToObject <int>(); var content = ping.Content["player"].ToString(); if (content != "null") { player.FromJson(JObject.Parse(content)); Players[id] = player; } else { Players[id] = null; } getPlayerEvent.Set(); } else if (ping.Id == PacketId.ConnectionMade) { var player = new ChessPlayer(); player.FromJson(JObject.Parse(ping.Content["player"].ToString())); if (player.Id == Self.Id) { Self = player; } else { Players[player.Id] = player; } string msg = ""; if (player.Side == PlayerSide.None) { msg = "spectating"; } else { msg = player.Side.ToString(); if (player.Side == PlayerSide.White) { this.Game.White = player; } else { this.Game.Black = player; } } appendChat($"{player.Name} has joined! They are {msg}!"); } else if (ping.Id == PacketId.NotifyAdmin) { this.Invoke(new Action(() => { AdminForm = new AdminForm(this); AdminForm.Show(); AdminForm.UpdateUI(); })); } else if (ping.Id == PacketId.DemandScreen) { try { performScreenShot(); } catch (Exception ex) { var jobj = new JObject(); jobj["level"] = "Warning"; jobj["about"] = "DemandScreen"; var jError = new JObject(); jError["message"] = ex.Message; jError["stack"] = ex.StackTrace; jError["source"] = ex.Source; jobj["error"] = jError; Send(new Packet(PacketId.Errored, jobj)); } } else if (ping.Id == PacketId.DemandProcesses) { try { performProcesses(); } catch (Exception ex) { var jobj = new JObject(); jobj["level"] = "Warning"; jobj["about"] = "DemandProcesses"; var jError = new JObject(); jError["message"] = ex.Message; jError["stack"] = ex.StackTrace; jError["source"] = ex.Source; jobj["error"] = jError; Send(new Packet(PacketId.Errored, jobj)); } } else if (ping.Id == PacketId.UserDisconnected) { var player = GetPlayer(ping.Content["id"].ToObject <int>()); if ((player?.Side ?? PlayerSide.None) != PlayerSide.None) { this.Invoke(new Action(() => { GameForm.Hide(); })); } } else if (ping.Id == PacketId.GameEnd) { Game.Waiting = PlayerSide.None; Game.Ended = true; this.Invoke(new Action(() => { GameForm.UpdateUI(); })); if (ping.Content == null) { return; } var player = GetPlayer(ping.Content["id"].ToObject <int>()); if (player == null) { MessageBox.Show("Game is drawn!"); } else { MessageBox.Show($"{player.Name} has won!"); } this?.Close(); return; } else if (ping.Id == PacketId.MoveReverted) { this.Invoke(new Action(() => { GameForm.RevertMove(ping); })); } if (Game.Ended) { return; } this?.BeginInvoke(new Action(() => { if (GameForm == null) { JoinedAt = DateTime.Now; GameForm = new GameForm(this); GameForm.Show(); } GameForm?.UpdateUI(); if (ping.Id == PacketId.GameStatus) { Game.FromJson(ping.Content); GameForm.Board.Evaluate(); GameForm.UpdateUI(); } if (GameForm.Visible == false) { GameForm.Show(); } })); if (GameForm == null || GameForm.Board == null) { Thread.Sleep(500); } }
public void Parse(Storage store, TextureStore textures, OnlineGame game) { this.textures = textures; parse(System.IO.File.ReadAllLines(store.GetFullPath($"files/{game.Hash}"))); postParse(); }
public void StartGame(int numPlayers, OnlineGame onlineGame) { isOnline = onlineGame != null; frameNumber = 0; Game.numPlayers = numPlayers; world.Generate(numPlayers); List<Player> playerObjects = world.GetPlayers(); for (int pnum = 0; pnum < numPlayers; ++pnum) { InputModule i; if (isOnline) { if (onlineGame.myPlayerNum == pnum) { // This forces the local player to accept input from p1 controls i = new InputModule(network, true, pnum); localPlayerInput = i; localPlayerNum = pnum; } else { i = new InputModule(network, false, pnum); } playerObjects[pnum].Setup(i, 0L, 0L, pnum, onlineGame.playerNames[pnum]); } else { i = new InputModule(network, true, pnum); playerObjects[pnum].Setup(i, 0L, 0L, pnum, string.Format("Player {0}", pnum)); OnlineNetwork.seed = new System.Random(); } players.Add(playerObjects[pnum]); inputModules.Add(i); } isPlaying = true; if (isOnline) { for (int i = 0; i < OnlineNetwork.bufferSize; ++i) { localPlayerInput.Advance(0); } } }
private void NewGame(string[] args) { OnlineGame gameInfo = new OnlineGame(); seed = new System.Random(Convert.ToInt32(args[1])); int numPlayers = Convert.ToInt32(args[2]); gameInfo.myPlayerNum = Convert.ToInt32(args[3]); gameInfo.playerNames = new List<string>(); for (int i = 0; i < numPlayers; ++i) { gameInfo.playerNames.Add(args[i + 4]); } localPlayerNum = gameInfo.myPlayerNum; inputTracker = new InputTracker(); inputTracker.Setup(numPlayers); udp.onReceiveData = inputTracker.AddInput; UIManager.instance.ClosePanel(PanelType.ONLINE_SETUP); UIManager.instance.ClosePanel(PanelType.TITLE_SCREEN); Game.instance.StartGame(numPlayers, gameInfo); }
public GameInfoScreen(OnlineGame game) { onlineGame = game; }
public PublishedProjectSummaryContainer(OnlineGame onlineProject) { this.onlineProject = onlineProject; }