public ClientSession(ISocketTask socket, Guid sessionID, IClusterClient clusterClient) { m_Socket = socket; SessionID = sessionID; socket.MessageEncoder = new MessageEncoder(); socket.MessageDecoder = new MessageDecoder(); m_Socket.OnDisconnect += OnDisconnect; m_Socket.OnMessage += OnMessage; try { m_ClientSessionGrain = clusterClient.GetGrain <IPlayerGrain>(sessionID); var obj = clusterClient.CreateObjectReference <IGatewayGrainObserver>(this).GetAwaiter().GetResult(); m_ClientSessionGrain.Subscribe(obj).Wait(); } catch (Exception e) { Logger.Warn(e); } socket.Startup(); }
private async Task <Guid> QuickMatch(int playerId) { IPlayerGrain player = GrainClient.GrainFactory.GetGrain <IPlayerGrain>(playerId); Guid roomId = await player.QuickMatch(); Console.WriteLine("Player {0} joined game room {1}", playerId, roomId); return(roomId); }
public async Task setup(IPlayerGrain player) { try { mapFileName = HttpContext.Current.Server.MapPath(mapFileName); if (!File.Exists(mapFileName)) { Trace.WriteLine("Unable to load map file: " + mapFileName, "Error"); throw new Exception("Unable to load map file: " + mapFileName); //return; } var rand = new Random(); var bytes = File.ReadAllText(mapFileName); JavaScriptSerializer deserializer = new JavaScriptSerializer(); var data = deserializer.Deserialize <MapInfo>(bytes); //var rooms = new List<IRoomGrain>(); foreach (var room in data.Rooms) { var roomGr = await MakeRoom(room, player.GetPrimaryKey()); if (room.Id >= 0) { await player.AddRoom(roomGr); } } //await player.SetupRooms(); foreach (var thing in data.Things) { await MakeThing(player, thing); } foreach (var monster in data.Monsters) { await MakeMonster(monster, player); } foreach (var npc in data.NPCs) { await MakeNpc(npc, player); } var thingIds = data.Things.Select(t => t.Id).ToArray(); var monsterIds = data.Monsters.Select(m => m.Id).ToArray(); var npcIds = data.NPCs.Select(n => n.Id).ToArray(); //await player.InitGameState(thingIds, monsterIds, npcIds); await player.InitGameState(data); } catch (Exception ex) { Trace.TraceError("Error with setup: " + ex.Message); Trace.TraceError("Error with setup STACK TRACE: " + ex.StackTrace); } }
Task ICharacterGrain.SetInfo(CharacterInfo info, IPlayerGrain player) { this.State.npcInfo = (NPCInfo)info; this.State.playerGrain = player; if (info.MovesRandomly) { mMoveTimer = RegisterTimer((_) => Move(), null, TimeSpan.FromSeconds(120), TimeSpan.FromMinutes(2)); } return(State.WriteStateAsync()); }
async internal static Task<string> GetDescriptorForState(IGameStateGrain gameState, List<Descriptor> descriptors, IPlayerGrain playerGrain) { if (descriptors != null && descriptors.Count > 0) { if (descriptors.Count == 1) { if (descriptors[0].SetFlags != null && descriptors[0].SetFlags.Count > 0) { await gameState.SetGameStateFlags(descriptors[0].SetFlags); } return descriptors[0].Text; } else { foreach (var descriptor in descriptors) { if (descriptor.IsDefault != true) { bool conditionsFailed = false; foreach (var flag in descriptor.Flags) { var gs = GrainFactory.GetGrain<IGameStateGrain>(playerGrain.GetPrimaryKey()); if ((await gs.GetStateForKey(flag.Key)) != flag.Value) conditionsFailed = true; } if (conditionsFailed == false) { if (descriptor.SetFlags != null && descriptor.SetFlags.Count > 0) { await gameState.SetGameStateFlags(descriptor.SetFlags); } return descriptor.Text; //return descriptor; } } } if (descriptors[0].SetFlags != null && descriptors[0].SetFlags.Count > 0) { try { await gameState.SetGameStateFlags(descriptors[0].SetFlags); } catch (Exception ex) { Trace.TraceError("Error setting game state flags: " + ex.Message); return "error"; } } return descriptors[0].Text; } } return "No Descriptors"; }
public async Task setup(IPlayerGrain player) { try { mapFileName = HttpContext.Current.Server.MapPath(mapFileName); if (!File.Exists(mapFileName)) { Trace.WriteLine("Unable to load map file: " + mapFileName, "Error"); throw new Exception("Unable to load map file: " + mapFileName); //return; } var rand = new Random(); var bytes = File.ReadAllText(mapFileName); JavaScriptSerializer deserializer = new JavaScriptSerializer(); var data = deserializer.Deserialize<MapInfo>(bytes); //var rooms = new List<IRoomGrain>(); foreach (var room in data.Rooms) { var roomGr = await MakeRoom(room, player.GetPrimaryKey()); if (room.Id >= 0) await player.AddRoom(roomGr); } //await player.SetupRooms(); foreach (var thing in data.Things) { await MakeThing(player, thing); } foreach (var monster in data.Monsters) { await MakeMonster(monster, player); } foreach (var npc in data.NPCs) { await MakeNpc(npc, player); } var thingIds = data.Things.Select(t => t.Id).ToArray(); var monsterIds = data.Monsters.Select(m => m.Id).ToArray(); var npcIds = data.NPCs.Select(n => n.Id).ToArray(); //await player.InitGameState(thingIds, monsterIds, npcIds); await player.InitGameState(data); } catch (Exception ex) { Trace.TraceError("Error with setup: " + ex.Message); Trace.TraceError("Error with setup STACK TRACE: " + ex.StackTrace); } }
private async Task MakeNpc(NPCInfo data, IPlayerGrain player) { var npcGrain = GrainFactory.GetGrain <INPCGrain>(player.GetPrimaryKey().ToString() + "Npc" + data.Id); await npcGrain.SetInfo(data, player); IRoomGrain room = GrainFactory.GetGrain <IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + data.StartIn); await npcGrain.SetRoomGrain(room); await npcGrain.SetPlayerGuid(await player.GetPlayerGuid()); await player.AddNpc(npcGrain); }
private async Task NonReentrantRegisterPlayer(IPlayerGrain player, PlayerInfo playerInfo) { this.playersInLobby.Add(new Tuple <IPlayerGrain, PlayerInfo>(player, playerInfo)); if (this.playersInLobby.Count == MAX_PLAYERS) { var gameServer = GameServerGrainFactory.GetGrain(Guid.NewGuid()); await gameServer.StartGame(this.playersInLobby.Select(_ => _.Item1).ToList()); this.playersInLobby.Clear(); } }
async Task IPlayerRegistrationGrain.Register(IPlayerObserver playerObserver) { var playerId = this.GetPrimaryKey(); // first have someone else to wait for future notifications from the GameServerGrain IPlayerGrain playerInGame = PlayerGrainFactory.GetGrain(playerId); // Forward subscription to the corresponding PlayerInGameGrain and trigger lobby service. var playerInfo = await playerInGame.Subscribe(playerObserver); // *then* ask to start a GameServerGrain via lobby await _lobby.RegisterPlayer(playerInGame, playerInfo); }
public IPlayerGrain GetPlayerGrain() { //定时器 var dis = RegisterTimer((obj) => Task.CompletedTask, new Program(), TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1)); //提醒 var rem = RegisterOrUpdateReminder(new Guid().ToString(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(30)).Result; UnregisterReminder(rem); IPlayerGrain player = GrainFactory.GetGrain <IPlayerGrain>(new Guid()); return(player); }
public Task JoinGame(IGameGrain game, IPlayerGrain player) { var primaryKey = game.GetPrimaryKey(); if (_activeGames.ContainsKey(primaryKey)) { return(TaskDone.Done); } _activeGames.Add(primaryKey, game); _activePlayers.Add(primaryKey, player); Console.WriteLine(" -- {0,-10} -- {1} joined a game.", "Account", _username); return(TaskDone.Done); }
static async Task <IClusterClient> RunWatcher() { try { // Connect to local silo var config = ClientConfiguration.LocalhostSilo(); var client = new ClientBuilder().UseConfiguration(config).Build(); await client.Connect(); // Hardcoded player ID Guid playerId = new Guid("{2349992C-860A-4EDA-9590-000000000006}"); IPlayerGrain player = client.GetGrain <IPlayerGrain>(playerId); IGameGrain game = null; while (game == null) { Console.WriteLine("Getting current game for player {0}...", playerId); try { game = await player.GetCurrentGame(); if (game == null) // Wait until the player joins a game { await Task.Delay(5000); } } catch (Exception exc) { Console.WriteLine("Exception: ", exc.GetBaseException()); } } Console.WriteLine("Subscribing to updates for game {0}...", game.GetPrimaryKey()); // Subscribe for updates var watcher = new GameObserver(); await game.SubscribeForGameUpdates( await client.CreateObjectReference <IGameObserver>(watcher)); Console.WriteLine("Subscribed successfully. Press <Enter> to stop."); return(client); } catch (Exception exc) { Console.WriteLine("Unexpected Error: {0}", exc.GetBaseException()); throw; } }
public async Task Leave(IPlayerGrain player) { logger.LogInformation($"Player {player.GetPrimaryKeyString()} left the game"); info.Players.Remove(player); logger.LogInformation($"Game {info.Key} now has {info.Players.Count} players"); // TODO: This can fail, update with correct error handling await stream.OnNextAsync(new PlayerLeftMessage() { PlayerId = player.GetPrimaryKeyString() }); }
private async Task MakeMonster(MonsterInfo data, IPlayerGrain player) { //var monsterGrain = MonsterGrainFactory.GetGrain(data.Id); //var monsterGrain = MonsterGrainFactory.GetGrain(Guid.NewGuid()); var monsterGrain = GrainFactory.GetGrain <IMonsterGrain>(player.GetPrimaryKey().ToString() + "Monster" + data.Id); //var room = await player.GetRandomRoom(); await monsterGrain.SetInfo(data, player); IRoomGrain room = GrainFactory.GetGrain <IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + data.StartIn); await monsterGrain.SetRoomGrain(room); await monsterGrain.SetPlayerGuid(await player.GetPlayerGuid()); await player.AddMonster(monsterGrain); }
/// <summary> /// Simulates a companion application that connects to the game that a particular player is currently part of /// and subscribes to receive live notifications about its progress. /// </summary> static void Main(string[] args) { try { var config = ClientConfiguration.LocalhostSilo(); GrainClient.Initialize(config); // Hardcoded player ID Guid playerId = new Guid("{2349992C-860A-4EDA-9590-000000000006}"); IPlayerGrain player = GrainClient.GrainFactory.GetGrain <IPlayerGrain>(playerId); IGameGrain game = null; while (game == null) { Console.WriteLine("Getting current game for player {0}...", playerId); try { game = player.GetCurrentGame().Result; if (game == null) // Wait until the player joins a game { game = null; Thread.Sleep(5000); } } catch (Exception exc) { Console.WriteLine("Exception: ", exc.GetBaseException()); } } Console.WriteLine("Subscribing to updates for game {0}...", game.GetPrimaryKey()); // Subscribe for updates var watcher = new GameObserver(); game.SubscribeForGameUpdates(GrainClient.GrainFactory.CreateObjectReference <IGameObserver>(watcher).Result).Wait(); // Block main thread so that the process doesn't exit. Updates arrive on thread pool threads. Console.WriteLine("Subscribed successfully. Press <Enter> to stop."); Console.ReadLine(); } catch (Exception exc) { Console.WriteLine("Unexpected Error: {0}", exc.GetBaseException()); } }
public async Task Join(IPlayerGrain player) { logger.LogInformation($"Player {player.GetPrimaryKeyString()} joined the game"); if (info.Players.Contains(player)) { logger.LogInformation($"Player {player.GetPrimaryKeyString()} was already in the game!"); throw new Exception("Player was already in this game!"); } info.Players.Add(player); logger.LogInformation($"Game {info.Key} now has {info.Players.Count} players"); // TODO: This can fail, update with correct error handling await stream.OnNextAsync(new PlayerJoinedMessage() { PlayerId = player.GetPrimaryKeyString() }); }
async Task ILobbyGrain.RegisterPlayer(IPlayerGrain player, PlayerInfo playerInfo) { List <Tuple <IPlayerGrain, PlayerInfo> > playerSet = null; var newPlayer = new Tuple <IPlayerGrain, PlayerInfo>(player, playerInfo); lock (_lock) // do the collection mgmt operations in a locked section, do awaiting the game server spawn outside { this.playersInLobby.Add(newPlayer); if (this.playersInLobby.Count == MAX_PLAYERS) { playerSet = this.playersInLobby; this.playersInLobby = new List <Tuple <IPlayerGrain, PlayerInfo> >(); } } if (playerSet != null) { var gameServer = GameServerGrainFactory.GetGrain(Guid.NewGuid()); await gameServer.StartGame(playerSet.Select(_ => _.Item1).ToList()); } }
private async Task MakeThing(IPlayerGrain player, Thing thing) { //IRoomGrain roomGrain = await player.GetRoomGrainByRoomId(thing.FoundIn); IRoomGrain roomGrain = GrainFactory.GetGrain<IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + thing.FoundIn); await roomGrain.Drop(thing); }
public Task ChangeOwnership(IPlayerGrain player) { _owner = player; Console.WriteLine(" -- {0,-10} -- {1} changed hands.", "Star", _name); return(TaskDone.Done); }
Task IRoomGrain.Exit(IPlayerGrain player) { State.players.Remove(player); return(State.WriteStateAsync()); }
private async Task MakeNpc(NPCInfo data, IPlayerGrain player) { var npcGrain = GrainFactory.GetGrain<INPCGrain>(player.GetPrimaryKey().ToString() + "Npc" + data.Id); await npcGrain.SetInfo(data, player); IRoomGrain room = GrainFactory.GetGrain<IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + data.StartIn); await npcGrain.SetRoomGrain(room); await npcGrain.SetPlayerGuid(await player.GetPlayerGuid()); await player.AddNpc(npcGrain); }
private async Task MakeThing(IPlayerGrain player, Thing thing) { //IRoomGrain roomGrain = await player.GetRoomGrainByRoomId(thing.FoundIn); IRoomGrain roomGrain = GrainFactory.GetGrain <IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + thing.FoundIn); await roomGrain.Drop(thing); }
async internal static Task <string> GetDescriptorForState(IGameStateGrain gameState, List <Descriptor> descriptors, IPlayerGrain playerGrain) { if (descriptors != null && descriptors.Count > 0) { if (descriptors.Count == 1) { if (descriptors[0].SetFlags != null && descriptors[0].SetFlags.Count > 0) { await gameState.SetGameStateFlags(descriptors[0].SetFlags); } return(descriptors[0].Text); } else { foreach (var descriptor in descriptors) { if (descriptor.IsDefault != true) { bool conditionsFailed = false; foreach (var flag in descriptor.Flags) { var gs = GrainFactory.GetGrain <IGameStateGrain>(playerGrain.GetPrimaryKey()); if ((await gs.GetStateForKey(flag.Key)) != flag.Value) { conditionsFailed = true; } } if (conditionsFailed == false) { if (descriptor.SetFlags != null && descriptor.SetFlags.Count > 0) { await gameState.SetGameStateFlags(descriptor.SetFlags); } return(descriptor.Text); //return descriptor; } } } if (descriptors[0].SetFlags != null && descriptors[0].SetFlags.Count > 0) { try { await gameState.SetGameStateFlags(descriptors[0].SetFlags); } catch (Exception ex) { Trace.TraceError("Error setting game state flags: " + ex.Message); return("error"); } } return(descriptors[0].Text); } } return("No Descriptors"); }
private async Task MakeMonster(MonsterInfo data, IPlayerGrain player) { //var monsterGrain = MonsterGrainFactory.GetGrain(data.Id); //var monsterGrain = MonsterGrainFactory.GetGrain(Guid.NewGuid()); var monsterGrain = GrainFactory.GetGrain<IMonsterGrain>(player.GetPrimaryKey().ToString() + "Monster" + data.Id); //var room = await player.GetRandomRoom(); await monsterGrain.SetInfo(data, player); IRoomGrain room = GrainFactory.GetGrain<IRoomGrain>(player.GetPrimaryKey().ToString() + "Room" + data.StartIn); await monsterGrain.SetRoomGrain(room); await monsterGrain.SetPlayerGuid(await player.GetPlayerGuid()); await player.AddMonster(monsterGrain); }
Task IRoomGrain.Enter(IPlayerGrain player) { State.players.Add(player); return(State.WriteStateAsync()); }
public async Task ProcessActionMessage(IPlayerGrain player, GameMessage message) { await actionMessageHandler.ProcessMessage(message); }