// Use this for initialization void Start() { // Get the object used to communicate with the server. /*request = (FtpWebRequest)WebRequest.Create("ftp://www.funwall.net/"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential ("funwalladmin",""); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader("testfile.txt"); byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close();*/ instance = this; _game = new Game(); _game.Players.Add(new player("john", "img/avatars/ninja.png", 3403)); _game.Players.Add(new player("Reese", "img/avatars/cptamerica.png", 3403)); _game.Players.Add(new player("Belvedier", "img/avatars/ironman.png", 8458)); _game.Players.Add(new player("Excelcisior", "img/avatars/alien.png", 8384)); _game.Players.Add(new player("Blue", "img/avatars/thor.png", 8223)); _game.Players.Add(new player("Xavier", "img/avatars/geek.png", 3483)); }
public UnitBase(GameServer _server, Player player) : base(_server, player) { EntityType = Entity.EntityType.Unit; UnitType = UnitTypes.Default; EntityToAttack = null; Speed = .01f; Range = 50; AttackDelay = 100; AttackRechargeTime = 1000; SupplyUsage = 1; RangedUnit = false; StandardAttackDamage = 1; StandardAttackElement = Entity.DamageElement.Normal; State = UnitState.Agro; allowMovement = false; _moveXCompleted = false; _moveYCompleted = false; attackTimer = new Stopwatch(); attackTimer.Reset(); attackTimer.Stop(); rechargeTimer = new Stopwatch(); rechargeTimer.Restart(); updatedMovePositionTimer = new Stopwatch(); updatedMovePositionTimer.Start(); }
static void Main(string[] args) { var settings = ReadSettings(Program.Location + "Settings.xml"); Console.WriteLine("Name: " + settings.Name); Console.WriteLine("Port: " + settings.Port); Console.WriteLine("Player Limit: " + settings.MaxPlayers); Console.WriteLine("Starting..."); ServerInstance = new GameServer(settings.Port, settings.Name, settings.Gamemode); ServerInstance.PasswordProtected = settings.PasswordProtected; ServerInstance.Password = settings.Password; ServerInstance.AnnounceSelf = settings.Announce; ServerInstance.MasterServer = settings.MasterServer; ServerInstance.MaxPlayers = settings.MaxPlayers; ServerInstance.Start(settings.Filterscripts); Console.WriteLine("Started! Waiting for connections."); while (true) { ServerInstance.Tick(); } }
public bool IsMatch(GameServer server) { if (server.IsConnected == _isConnected) return true; else return false; }
public NetworkMultiplayer(bool createServer = false) : base(GameModes.Network) { if(createServer) GameServer = new GameServer(); //read network on each update Game.Instance.OnUpdate += ReadNetwork; //server config NetPeerConfiguration config = new NetPeerConfiguration("tank"); config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse); //server creation Client = new NetClient(config); Client.Start(); if (!createServer) { //check whether the user has a known server ListMenu serverMenu = new ListMenu("Do you want to connect to a given IP (if yes, enter in console)?", "tank.Code.YESORNOCHOOSENOW", ConnectionMethodSelectionCallback); Scene.Add(serverMenu); } else//we know that a local server must exist Client.DiscoverLocalPeers(14242); //register handler for receiving data OnClientData += IncomingHandler; //are we client, or are we dancer? if(!createServer) Console.WriteLine("client"); }
public static void Main() { server = new GameServer(9958); server.Ennable(); Console.ReadKey(); }
static void Main(string[] args) { var settings = ReadSettings(Program.Location + "Settings.xml"); Console.WriteLine("Name: " + settings.Name); Console.WriteLine("Port: " + settings.Port); Console.WriteLine("Player Limit: " + settings.MaxPlayers); Console.WriteLine("Starting..."); ServerInstance = new GameServer(settings.Port, settings.Name, settings.Gamemode); ServerInstance.PasswordProtected = settings.PasswordProtected; ServerInstance.Password = settings.Password; ServerInstance.AnnounceSelf = settings.Announce; ServerInstance.MasterServer = settings.MasterServer; ServerInstance.MaxPlayers = settings.MaxPlayers; ServerInstance.AllowDisplayNames = settings.AllowDisplayNames; ServerInstance.Start(settings.Filterscripts); Console.WriteLine("Started! Waiting for connections."); while (true) { ServerInstance.Tick(); System.Threading.Thread.Sleep(10); // Reducing CPU Usage (Win7 from average 15 % to 0-1 %, Linux from 100 % to 0-2 %) } }
public override void Initialize(GameServer server) { base.Initialize(server); _queryCount = 1; _queryResultCache = Hashtable.Synchronized(new Hashtable()); _server.MessageReceived += new MessageReceivedEventHandler(this.MessageReceived); }
/// <summary> /// Sends the result of server register /// </summary> /// <param name="server"></param> /// <param name="result">0 = success; 1 = duplicated index</param> public void RegisterResult(GameServer server, ushort result) { AG.RegisterResult registerResult = new AG.RegisterResult(); registerResult.Result = result; registerResult.CreateChecksum(); GameManager.Instance.Send(server, PacketManager.ToArray(registerResult)); }
public GameServerMultiplayer(GameServerSettings settings) { server = new GameServer<IServerPlayPacket, IClientPlayPacket>( serverPort, IPAddress.Parse(GameClientMultiplayer.multicastAddress)); server.OnReceiveClientPacket += OnReceiveClientPacket; this.settings = settings; connectedPlayers = new Dictionary<int, Player>(); }
public GameManager(RealmCore rCore) { RCore = rCore; Server = new GameServer(); Server.ClientDisconnected += Server_ClientDisconnected; Server.NewClientConntected += Server_NewClientConntected; Server.NewDataReceived += Server_NewDataReceived; Server.NewDataSended += Server_NewDataSended; Server.Started += Server_Started; Server.Stoped += Server_Stoped; }
protected override void Initialize() { if (AppSettings.Default.EnableServer) { GameServer server = new GameServer(new MapGenerator().Generate(30, 16), AppSettings.Default.ListenPort); server.Start(); } ApplyGraphicsSettings(); base.Initialize(); }
private void MessageReceived(GameServer server, IProtocol message) { if ((ProtocolDef)message.ProtocolId == ProtocolDef.g2e_exesql_def) { g2e_exesql protocol = message as g2e_exesql; bool success = ((FSEyeResult)protocol.nRetCode == FSEyeResult.fseye_success); bool done = ((FSEyeResult)protocol.nRetCode != FSEyeResult.mydb_more_result); UpdateQueryResultCache(protocol.nSessionID, protocol.szResult, done, success); } }
public LLApiServer(GameServer gameServer, int port, ushort maxConnections, ushort maxMessages) { GameServer = gameServer; Port = port; MaxConnections = maxConnections; MaxMessages = maxMessages; isConnected = false; Config = new ConnectionConfig(); int ReliableChannelId = Config.AddChannel(QosType.Reliable); int NonReliableChannelId = Config.AddChannel(QosType.Unreliable); Topology = new HostTopology(Config, MaxConnections); }
protected FS2RoleDataInfo Query(GameServer server, int roleId) { FS2RoleDataInfo roleInfo = null; ArrayList paramList = new ArrayList(); paramList.Add(roleId); string selectedFiled = string.Format("{0},{1},{2},{3},{4}", FS2TableString.RolesfirstFieldMoney,FS2TableString.RolesfirstFieldMoneyInBox, FS2TableString.RolesfirstFieldItemList,FS2TableString.RolesfirstFieldRoleName, FS2TableString.RolesfirstFieldId); string sqlCmdText = string.Format("SELECT {0} FROM {1} WHERE {2}='?';" ,selectedFiled, FS2TableString.RolesfirstTableName, FS2TableString.RolesfirstFieldId); SqlCommand cmd = new SqlCommand(sqlCmdText, paramList.ToArray()); if (!server.IsConnected) { LabelOpMsg.Visible = true; LabelOpMsg.Text = StringDef.NoConnectionAlert; return null; } SqlResult result = WebUtil.QueryGameServerDb(CurrentUser.Id,server,cmd); if (result != null && result.Success) { result.SetFieldType(new SqlDataType[]{ SqlDataType.UInt32, SqlDataType.UInt32, SqlDataType.Blob, SqlDataType.String, SqlDataType.Int32 }); object[] record; byte[] itemData; roleInfo = new FS2RoleDataInfo(); while ((record = result.ReadRecord())!=null) { if (record != null) { roleInfo.Money = (uint)record[0]; roleInfo.MoneyInBox = (uint)record[1]; itemData = (byte[])record[2]; if (itemData != null) { roleInfo.ItemList = FS2ItemDataInfo.Parse(itemData); //if (info != null) ItemList.Add(info); } roleInfo.RoleName = record[3] as string; roleInfo.RoleId = (int)record[4]; } } //RenderView(roleInfo); } return roleInfo; }
public ProjectileBase(GameServer _server, Player player, Vector2f startPosition, EntityBase target, float dmg, Entity.DamageElement element, float speed = 1) : base(_server, player) { EntityType = Entity.EntityType.Projectile; Start = startPosition; Target = target; Position = Start; BoundsSize = new Vector2f(5, 5); Damage = dmg; Element = element; Speed = speed; RemoveOnNoHealth = false; }
public static void HandleCommand(Session session, GameServer server, ChatTalkMessage message) { var t = typeof (ChatService); var s = message.Message.Substring(1); s = s.Split(' ')[0]; var m = t.GetMethod(s, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance); if (m != null && m.Name != "HandleCommand") { m.Invoke(null, new object[] {session, server, message}); } else session.SendMessage(new ChatTalkMessage("This command is not valid !")); }
public NetworkCommands() { _server = GameServer.Instance; _server.SockServ.AddCommand("echo", Echo_CMD); _server.SockServ.AddCommand("getsalt", GetSalt_CMD); _server.SockServ.AddCommand("login", Login_CMD); _server.SockServ.AddCommand("getterrain", GetTerrain_CMD); _server.SockServ.AddCommand("getstructures", GetStructures_CMD); _server.SockServ.AddCommand("createstructure", CreateStructure_CMD); _server.SockServ.AddCommand("changestructure", ChangeStructure_CMD); _server.SockServ.AddCommand("structurecommand", StructureCommand_CMD); _server.SockServ.AddCommand("inchat", Chat_CMD); _server.SockServ.AddCommand("getstructuresquads", GetSquadsOnStructure_CMD); }
protected GameModeBase(GameServer server) { map = new TileMap(); TiledMap = new TiledMap(); players = new List<Player>(); entityWorldIdToGive = 0; Server = server; entities = new Dictionary<ushort, EntityBase>(); entityToUpdate = 0; entityPositionUpdateTimer = new Stopwatch(); entityPositionUpdateTimer.Restart(); }
public BuildingBase(GameServer server, Player player) : base(server, player) { IsBuilding = true; BuildTime = 1000; elapsedBuildTime = 0; buildOrder = new List<string>(); EntityType = Entity.EntityType.Building; stopwatch = new Stopwatch(); Health = 1; MaxHealth = 100; }
/// <summary> /// Triggered when a client tries to connect /// </summary> /// <param name="ar"></param> private void AcceptCallback(IAsyncResult ar) { Socket listener = (Socket)ar.AsyncState; Socket client = listener.EndAccept(ar); // Starts to accept another connection listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); GameServer gs = new GameServer(client); client.BeginReceive( gs.NetData.Buffer, 0, Globals.MaxBuffer, SocketFlags.None, new AsyncCallback(ReadCallback), gs ); }
public static BuildingBase CreateBuilding(BuildingTypes building, GameServer server, Player player) { switch (building) { default: case BuildingTypes.Base: return CreateBuilding("base", server, player); break; case BuildingTypes.Supply: return CreateBuilding("supply", server, player); break; case BuildingTypes.GlueFactory: return CreateBuilding("gluefactory", server, player); break; } }
/// <summary> /// Called whenever a packet is received from a game client /// </summary> /// <param name="client"></param> /// <param name="packet"></param> public void PacketReceived(GameServer server, PacketStream packet) { byte[] data = packet.ToArray(); ConsoleUtils.HexDump(data, "Received from GameServer"); // Is it a known packet ID if (!PacketsDb.ContainsKey(packet.GetId())) { ConsoleUtils.ShowWarning("Unknown packet Id: {0}", packet.GetId()); return; } // Calls this packet parsing function Task.Factory.StartNew(() => { PacketsDb[packet.GetId()].Invoke(server, data); }); }
private void btnGetInfos_Click(object sender, EventArgs e) { // IP einlesen IPAddress ipAddr = IPAddress.Parse(textBox1.Text.Split(':')[0]); int port = 27015; if(textBox1.Text.Split(':').Length > 1) { port = int.Parse(textBox1.Text.Split(':')[1]); } if(currentGameServer == null || currentGameServer.IPAddress.ToString() != ipAddr.ToString()) { currentGameServer = GameServer.GetGameServer(ipAddr, port); } UpdateServerInfos(); }
public WorldManager(GameServer server) { _server = server; _worldFolders = new Dictionary<string, string> (); MainWorldDirectory = Directory.GetCurrentDirectory() + GameServer.sepChar + "Worlds" + GameServer.sepChar; if (!Directory.Exists (MainWorldDirectory)) { Directory.CreateDirectory (MainWorldDirectory); Logger.Log("World Directory created."); } string[] worldDirectories = Directory.GetDirectories (MainWorldDirectory); for (int i = 0; i < worldDirectories.Length; i++) { string folderName = Path.GetFileName(Path.GetDirectoryName(worldDirectories[i] + GameServer.sepChar)); _worldFolders[folderName] = worldDirectories[i] + GameServer.sepChar; //Logger.Log(folderName); } //Logger.Log ("World Manager initialized."); }
public StandardMelee(GameServer server, byte mplayers) : base(server) { MaxPlayers = mplayers; GameStatus = StatusState.WaitingForPlayers; idToGive = 0; SetMap("Resources/Maps/untitled.tmx"); var worker = UnitBase.CreateUnit(UnitTypes.Worker, Server, null); worker.Team = 1; worker.Position = new Vector2f(100, 500); //AddEntity(worker); var build = BuildingBase.CreateBuilding("standardBase", Server, null); build.Team = 1; build.Position = new Vector2f(100, 500); //AddEntity(build); }
public static bool SetRoleFrozen(int userId, GameServer server, string roleName, bool freeze) { if (server == null || !server.IsConnected) return false; //先更新数据库然后发GM指令 ArrayList paramList = new ArrayList(); string sqlCmdText = string.Format("UPDATE {0} SET {1}='?' WHERE {2}='?';", FS2TableString.RolesfirstTableName, FS2TableString.RolesfirstFieldNoLoginIn, FS2TableString.RolesfirstFieldRoleName); paramList.Add(freeze ? "1" : "0"); paramList.Add(roleName); SqlCommand sqlCmd = new SqlCommand(sqlCmdText, paramList.ToArray()); SqlResult result = WebUtil.QueryGameServerDb(userId, server, sqlCmd); if (result != null && result.Success) { //发GM指令设置Login标志位并把强制玩家下线 string gmCmd = string.Format("?gm ds SetLoginFlag({0})", freeze ? 1 : 0); server.DoPlugInAction(userId, LordControl.PlugInGuid, LordControl.ActionKeyExecuteGMCommand, roleName, gmCmd); if (freeze) server.DoPlugInAction(userId, LordControl.PlugInGuid, LordControl.ActionKeyExecuteGMCommand, roleName, WebConfig.GMCommandKickPlayer); FSEye.Security.LogSystem.TheInstance.WriteGMOperationLog(userId, freeze ? (int)GMOperation.FreezeRole : (int)GMOperation.UnfreezeRole, roleName, server.Id, string.Format(StringDef.GMMessageLog, AdminServer.TheInstance.SecurityManager.GetUser(userId).RealName, server.Name, roleName == null || roleName.Length == 0 ? string.Empty : string.Format("[{0}]", roleName), freeze ? StringDef.Freeze + StringDef.Role : StringDef.Unfreeze + StringDef.Role), (int)GMOpTargetType.Role); return true; } else { return false; } }
protected FS2RoleDataInfo Query(GameServer server, int roleId) { FS2RoleDataInfo roleInfo = null; ArrayList paramList = new ArrayList(); paramList.Add(roleId); string selectedFiled = string.Format("{0},{1}", FS2TableString.RolesfirstFieldSkillList, FS2TableString.RolesfirstFieldRoleName); string sqlCmdText = string.Format("SELECT {0} FROM {1} WHERE {2}='?';", selectedFiled, FS2TableString.RolesfirstTableName, FS2TableString.RolesfirstFieldId); SqlCommand cmd = new SqlCommand(sqlCmdText, paramList.ToArray()); if (!server.IsConnected) { LabelOpMsg.Text = StringDef.NoConnectionAlert; return null; } SqlResult result = WebUtil.QueryGameServerDb(CurrentUser.Id, server, cmd); if (result != null && result.Success) { result.SetFieldType(new SqlDataType[]{ SqlDataType.Blob, SqlDataType.String }); object[] record; byte[] skillData; roleInfo = new FS2RoleDataInfo(); while ((record = result.ReadRecord()) != null) { if (record != null) { skillData = (byte[])record[0]; if (skillData != null) { roleInfo.SkillList = FS2SkillDataInfo.Parse(skillData); } roleInfo.RoleName = record[1] as string; } } } return roleInfo; }
/// <summary> /// 查询游戏数据库 /// </summary> /// <param name="server">游戏服务器</param> /// <param name="cmd">SQL命令</param> /// <returns>查询结果</returns> /// <remarks>这个函数是同步的(会阻塞)</remarks> public static SqlResult QueryGameServerDb(int userId,GameServer server, SqlCommand cmd) { object outArg = null; //简单判断 if (!server.IsConnected) return null; if (server.DoPlugInAction(userId, GameServerDb.PlugInGuid, GameServerDb.ActionKeyQuery, ref outArg, "xxx", cmd)) { uint sessionId = (uint)outArg; for (int i = 0; i < WebConfig.GetQueryResultRetryTimes; i++) { Thread.Sleep(WebConfig.GetQueryResultDelay); SqlResult result = server.GetPlugInData(userId, GameServerDb.PlugInGuid, GameServerDb.DataKeyQueryResult, sessionId) as SqlResult; if (result != null) { return result; } } } return null; }
protected void Page_Load(object sender, EventArgs e) { if (!WebUtil.CheckPrivilege(WebConfig.FunctionGameServerServerDetail, OpType.READ, Session)) { Response.Redirect(WebConfig.PageNotEnoughPrivilege, true); } if (Request.Params["serverId"] != null) { if (!IsPostBack) { int serverId = int.Parse(Request.Params["serverId"]); m_server = TheAdminServer.GameServerManager.GetGameServer(serverId); if (m_server != null) { Session["SelectedGameServer"] = m_server; } else { Response.Redirect("GameServer.aspx"); } } else { if (Session["SelectedGameServer"] != null) { m_server = (GameServer)Session["SelectedGameServer"]; } else { Response.Redirect("GameServer.aspx"); } } } else { Response.Redirect("GameServer.aspx"); } }
public GameWorld(GameServer server) { this.server = server; this.playerManager = new PlayerManager(true); }
public ActionResult WdServers() { int UserId = BBRequest.GetUserId(); if (UserId > 0) { GameUser gu = new GameUser(); gu = gum.GetGameUser(UserId); ViewData["UserName"] = gu.UserName; ViewData["TjqfHref"] = "#"; ViewData["TjqfName"] = "暂无推荐区服"; ViewData["LLHref"] = "#"; ViewData["LLName"] = "暂无记录"; OnlineLog ol = new OnlineLog(); ol = new OnlineLogManager().GetLastLogin(UserId, g.Id); if (ol != null) { GameServer Llqf = sm.GetGameServer(ol.ServerId); if (Llqf.State == 1 || Llqf.State == 2) { ViewData["LLHref"] = "#"; } else { ViewData["LLHref"] = gm.LoginUrl(g.Id, UserId, Llqf.Id, 1); } ViewData["LLName"] = Llqf.Name; } if (g.tjqf > 0) { GameServer tjqf = sm.GetGameServer(g.tjqf); ViewData["TjqfHref"] = gm.LoginUrl(g.Id, UserId, tjqf.Id, 1); ViewData["TjqfName"] = tjqf.Name; } List <GameServer> gsList = new List <GameServer>(); gsList = sm.GetServersByGame(g.Id); string ServerHtml = ""; foreach (GameServer gs in gsList) { switch (gs.State) { case 1: ServerHtml += "<a><span class=\"yellow\"></span>" + gs.Name + "</a>"; break; case 2: ServerHtml += "<a><span class=\"gray\"></span>" + gs.Name + "</a>"; break; case 3: ServerHtml += "<a href=\"" + gm.LoginUrl(g.Id, UserId, gs.Id, 1) + "\"><span class=\"green\"></span>" + gs.Name + "</a>"; break; case 4: ServerHtml += "<a href=\"" + gm.LoginUrl(g.Id, UserId, gs.Id, 1) + "\"><span class=\"red\"></span>" + gs.Name + "</a>"; break; default: break; } } ViewData["gsHtml"] = ServerHtml; return(View()); } else { return(RedirectToAction("Wd")); } }
public ChatRoomController(GameServer server, ILogger <ChatRoomController> logger) { _server = server; _logger = logger; }
public MessageComponent(GameServer server) : base(server) { Timer = new GameServerTimer( TimeSpan.FromSeconds(ServerContextBase.Config.MessageClearInterval)); }
void Query(int offset) { try { int serverId = ServerDropDownList.SelectedServerId; GameServer server = ServerDropDownList.SelectedGameServer; if (server == null) { LabelOpMsg.Text = string.Format(StringDef.MsgCannotBeNone, StringDef.GameServer); return; } if (!server.IsConnected) { LabelOpMsg.Text = StringDef.NoConnectionAlert; return; } ArrayList paramList = new ArrayList(); StringBuilder searchCondition = new StringBuilder(); //searchCondition.Append(string.Format(" AND {0}>='{1}' AND {0} <'{2}'", FS2TableString.LogFieldLogTime, StartDate.SelectedDate, EndDate.SelectedDate.AddDays(-1))); if (StartDate.Selected) { searchCondition.Append(string.Format(" AND {0}>='{1}'", FS2TableString.MailFieldPostTime, StartDate.SelectedDate)); } if (EndDate.Selected) { searchCondition.Append(string.Format(" AND {0}<'{1}'", FS2TableString.MailFieldPostTime, EndDate.SelectedDate)); } string sender = TextBoxSender.Text; WebUtil.ValidateValueString(sender); if (sender.Length > 0) { if (CheckBoxSender.Checked) { searchCondition.Append(string.Format(" AND {0}='?'", FS2TableString.MailFieldSender)); paramList.Add(sender); } else { searchCondition.Append(string.Format(" AND {0} LIKE '%?%'", FS2TableString.MailFieldSender)); paramList.Add(sender); } } string receiver = TextBoxReceiver.Text; WebUtil.ValidateValueString(receiver); if (receiver.Length > 0) { if (CheckBoxReceiver.Checked) { searchCondition.Append(string.Format(" AND {0}='?'", FS2TableString.MailFieldReceiver)); paramList.Add(receiver); } else { searchCondition.Append(string.Format(" AND {0} LIKE '%?%'", FS2TableString.MailFieldReceiver)); paramList.Add(receiver); } } string filterNegative = TextBoxFilter.Text.Trim(); if (filterNegative != null && filterNegative.Length != 0) { if (CheckBoxFilter.Checked) { searchCondition.Append(string.Format(" AND {0}!='?'", FS2TableString.MailFieldSender)); paramList.Add(filterNegative); } else { searchCondition.Append(string.Format(" AND {0} NOT LIKE '%?%'", FS2TableString.MailFieldSender)); paramList.Add(filterNegative); } } string filterNegative1 = TextBoxFilter1.Text.Trim(); if (filterNegative1 != null && filterNegative1.Length != 0) { if (CheckBoxFilter1.Checked) { searchCondition.Append(string.Format(" AND {0}!='?'", FS2TableString.MailFieldSender)); paramList.Add(filterNegative1); } else { searchCondition.Append(string.Format(" AND {0} NOT LIKE '%?%'", FS2TableString.MailFieldSender)); paramList.Add(filterNegative1); } } string orderByType = string.Empty; switch (ListBoxOrderByType.SelectedIndex) { case 0: orderByType = "ASC"; break; case 1: orderByType = "DESC"; break; } string orderByStatement = string.Empty; switch (ListBoxOrderBy.SelectedIndex) { case 0: orderByStatement = string.Format(" ORDER BY {0} {1}", FS2TableString.MailFieldPostTime, orderByType); break; case 1: orderByStatement = string.Format(" ORDER BY {0} {1}", FS2TableString.MailFieldSender, orderByType); break; case 2: orderByStatement = string.Format(" ORDER BY {0} {1}", FS2TableString.MailFieldReceiver, orderByType); break; } if (searchCondition.Length != 0) { searchCondition.Remove(0, 4); searchCondition.Insert(0, "WHERE "); } int limitCount = _recordPerPage; string limitStatement = string.Format("LIMIT {0},{1}", offset, limitCount); string cmdString = "SELECT {0} FROM {1} {2} {3} {4}"; string cmdFieldString = string.Format("{0},{1},{2},{3}", FS2TableString.MailFieldSender, FS2TableString.MailFieldReceiver, FS2TableString.MailFieldPostTime, FS2TableString.MailFieldMailData); string cmdCountFieldString = "COUNT(*)"; SqlCommand cmd = new SqlCommand(string.Format(cmdString, cmdFieldString, FS2TableString.MailTableName, searchCondition.ToString(), orderByStatement, limitStatement), paramList.ToArray()); SqlResult result = WebUtil.QueryGameServerDb(CurrentUser.Id, server, cmd); if (result != null && result.Success) { Session[WebConfig.SessionQueryLogOffset] = offset; result.SetFieldType(new SqlDataType[] { SqlDataType.String, SqlDataType.String, SqlDataType.DateTime, SqlDataType.String }); object[] record = null; ArrayList infos = new ArrayList(); while ((record = result.ReadRecord()) != null) { MailInfo info = new MailInfo(); info.sender = record[0] as string; info.receiver = record[1] as string; info.postTime = (DateTime)record[2]; info.mailData = record[3] as string; infos.Add(info); } ButtonPreviousPage.Enabled = (offset > 0); ButtonFirstPage.Enabled = (offset > 0); ButtonNextPage.Enabled = (infos.Count >= limitCount); //单独查询总数,只有第一页显示 if (offset == 0) { SqlCommand cmdCount = new SqlCommand(string.Format(cmdString, cmdCountFieldString, FS2TableString.MailTableName, searchCondition.ToString(), string.Empty, string.Empty), paramList.ToArray()); if (!server.IsConnected) { LabelOpMsg.Text = StringDef.NoConnectionAlert; return; } SqlResult resultCount = WebUtil.QueryGameServerDb(CurrentUser.Id, server, cmdCount); if (resultCount.ResultState == SqlResult.State.Done && resultCount.Success) { resultCount.SetFieldType(new SqlDataType[] { SqlDataType.Int32 }); object[] count = resultCount.ReadRecord(); TableRow rowHead = new TableRow(); TableCell cellHead = new TableCell(); cellHead.Font.Bold = true; cellHead.ColumnSpan = 4; cellHead.Text = StringDef.Total + StringDef.Colon + (int)count[0]; rowHead.Cells.Add(cellHead); TableSearchMailList.Rows.Add(rowHead); } } bool success = CreateSearchResultList((MailInfo[])infos.ToArray(typeof(MailInfo))); PanelResult.Visible = success; if (!success) { LabelOpMsg.Text = StringDef.NoMatchingRecord; } else { LabelResult.Text = string.Format(StringDef.LabelStatisticResult, server.Group.Name, server.Name, string.Empty, StringDef.Mail); } } else { if (result == null) { LabelOpMsg.Text = StringDef.QueryTimeOut; } else { LabelOpMsg.Text = StringDef.OperationFail; } } } catch (Exception ex) { LabelOpMsg.Text = ex.Message; PanelResult.Visible = false; } }
public async Task<bool> Execute(GameServer server, Player plr, string[] args) { if (args.Length < 1) { plr.SendConsoleMessage(S4Color.Red + "Wrong Usage, possible usages:"); plr.SendConsoleMessage(S4Color.Red + "> level <nickname> <level>"); return true; } if (args.Length >= 2) { AccountDto account; using (var db = AuthDatabase.Open()) { account = (await DbUtil.FindAsync<AccountDto>(db, statement => statement .Include<BanDto>(join => join.LeftOuterJoin()) .Where($"{nameof(AccountDto.Nickname):C} = @Nickname") .WithParameters(new { Nickname = args[0] }))).FirstOrDefault(); if (account == null) { plr.SendConsoleMessage(S4Color.Red + "Unknown player"); return true; } var playerdto = (await DbUtil.FindAsync<PlayerDto>(db, statement => statement .Where($"{nameof(PlayerDto.Id):C} = @Id") .WithParameters(new { account.Id })) ).FirstOrDefault(); if (playerdto == null) { plr.SendConsoleMessage(S4Color.Red + "Unknown player"); return true; } if (byte.TryParse(args[1], out var level)) { var expTable = GameServer.Instance.ResourceCache.GetExperience(); if (expTable.TryGetValue(level, out var exp)) { plr.SendConsoleMessage($"Changed {account.Nickname}'s level to {args[1]}"); playerdto.Level = level; playerdto.TotalExperience = exp.TotalExperience; DbUtil.Update(db, playerdto); var player = GameServer.Instance.PlayerManager.Get((ulong)account.Id); if (player != null) { player.Level = level; player.TotalExperience = exp.TotalExperience; player.Session?.SendAsync(new ExpRefreshInfoAckMessage(player.TotalExperience)); player.Session?.SendAsync( new PlayerAccountInfoAckMessage(player.Map<Player, PlayerAccountInfoDto>())); player.NeedsToSave = true; } } else { plr.SendConsoleMessage(S4Color.Red + "Invalid Level"); } } else { plr.SendConsoleMessage(S4Color.Red + "Wrong Usage, possible usages:"); plr.SendConsoleMessage(S4Color.Red + "> level <nickname> <level>"); } } } return true; }
private void Draw(SpriteBatch spriteBatch, Item item, Vector2 position, Vector2 labelPos, Vector2 wirePosition, bool mouseIn, Wire equippedWire, float wireInterval) { //spriteBatch.DrawString(GUI.SmallFont, Name, new Vector2(labelPos.X, labelPos.Y-10), Color.White); GUI.DrawString(spriteBatch, labelPos, Name, IsPower ? Color.Red : Color.White, Color.Black, 0, GUI.SmallFont); GUI.DrawRectangle(spriteBatch, new Rectangle((int)position.X - 10, (int)position.Y - 10, 20, 20), Color.White); spriteBatch.Draw(panelTexture, position - new Vector2(16.0f, 16.0f), new Rectangle(64, 256, 32, 32), Color.White); for (int i = 0; i < MaxLinked; i++) { if (Wires[i] == null || Wires[i].Hidden || draggingConnected == Wires[i]) { continue; } Connection recipient = Wires[i].OtherConnection(this); DrawWire(spriteBatch, Wires[i], (recipient == null) ? Wires[i].Item : recipient.item, position, wirePosition, mouseIn, equippedWire); wirePosition.Y += wireInterval; } if (draggingConnected != null && Vector2.Distance(position, PlayerInput.MousePosition) < 13.0f) { spriteBatch.Draw(panelTexture, position - new Vector2(21.5f, 21.5f), new Rectangle(106, 250, 43, 43), Color.White); if (!PlayerInput.LeftButtonHeld()) { //find an empty cell for the new connection int index = FindWireIndex(null); if (index > -1 && !Wires.Contains(draggingConnected)) { bool alreadyConnected = draggingConnected.IsConnectedTo(item); draggingConnected.RemoveConnection(item); if (draggingConnected.Connect(this, !alreadyConnected, true)) { var otherConnection = draggingConnected.OtherConnection(this); if (otherConnection == null) { GameServer.Log(Character.Controlled.LogName + " connected a wire to " + Item.Name + " (" + Name + ")", ServerLog.MessageType.ItemInteraction); } else { GameServer.Log(Character.Controlled.LogName + " connected a wire from " + Item.Name + " (" + Name + ") to " + otherConnection.item.Name + " (" + otherConnection.Name + ")", ServerLog.MessageType.ItemInteraction); } AddLink(index, draggingConnected); } } } } int screwIndex = (position.Y % 60 < 30) ? 0 : 1; if (Wires.Any(w => w != null && w != draggingConnected)) { spriteBatch.Draw(panelTexture, position - new Vector2(16.0f, 16.0f), new Rectangle(screwIndex * 32, 256, 32, 32), Color.White); } }
public override void Update(float deltaTime, Camera cam) { if (!item.body.Enabled) { return; } if (midAir) { if (item.body.LinearVelocity.LengthSquared() < 0.01f) { item.body.CollidesWith = Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionPlatform; midAir = false; } return; } if (picker == null || picker.Removed || !picker.HasSelectedItem(item)) { IsActive = false; return; } if (picker.IsKeyDown(InputType.Aim) && picker.IsKeyHit(InputType.Shoot)) { throwing = true; } if (!picker.IsKeyDown(InputType.Aim) && !throwing) { throwPos = 0.0f; } bool aim = picker.IsKeyDown(InputType.Aim) && (picker.SelectedConstruction == null || picker.SelectedConstruction.GetComponent <Ladder>() != null); if (picker.IsUnconscious || picker.IsDead || !picker.AllowInput) { throwing = false; aim = false; } ApplyStatusEffects(ActionType.OnActive, deltaTime, picker); if (item.body.Dir != picker.AnimController.Dir) { Flip(); } AnimController ac = picker.AnimController; item.Submarine = picker.Submarine; if (!throwing) { if (aim) { throwPos = MathUtils.WrapAnglePi(System.Math.Min(throwPos + deltaTime * 5.0f, MathHelper.PiOver2)); ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos); } else { throwPos = 0; ac.HoldItem(deltaTime, item, handlePos, holdPos, Vector2.Zero, false, holdAngle); } } else { throwPos = MathUtils.WrapAnglePi(throwPos - deltaTime * 15.0f); ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos); if (throwPos < 0) { Vector2 throwVector = Vector2.Normalize(picker.CursorWorldPosition - picker.WorldPosition); //throw upwards if cursor is at the position of the character if (!MathUtils.IsValid(throwVector)) { throwVector = Vector2.UnitY; } #if SERVER GameServer.Log(picker.LogName + " threw " + item.Name, ServerLog.MessageType.ItemInteraction); #endif Character thrower = picker; item.Drop(thrower, createNetworkEvent: GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer); item.body.ApplyLinearImpulse(throwVector * throwForce * item.body.Mass * 3.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); //disable platform collisions until the item comes back to rest again item.body.CollidesWith = Physics.CollisionWall | Physics.CollisionLevel; midAir = true; ac.GetLimb(LimbType.Head).body.ApplyLinearImpulse(throwVector * 10.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); ac.GetLimb(LimbType.Torso).body.ApplyLinearImpulse(throwVector * 10.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); Limb rightHand = ac.GetLimb(LimbType.RightHand); item.body.AngularVelocity = rightHand.body.AngularVelocity; throwPos = 0; throwDone = true; if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer) { GameMain.NetworkMember.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnSecondaryUse, this, thrower.ID }); } if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer) { //Stun grenades, flares, etc. all have their throw-related things handled in "onSecondaryUse" ApplyStatusEffects(ActionType.OnSecondaryUse, deltaTime, thrower, user: thrower); } throwing = false; } } }
public override void OnResponse(GameServer server, GameClient client, ushort responseID, string args) { }
/// <summary> /// Handles the server action /// </summary> /// <param name="parameters"></param> public void OnAction(Hashtable parameters) { Console.WriteLine("This server DDTankII, edit and build by Trminhpc!"); Console.WriteLine("Starting GameServer ... please wait a moment!"); GameServer.CreateInstance(new GameServerConfig()); GameServer.Instance.Start(); GameServer.KeepRunning = true; Console.WriteLine("Server started!"); ConsoleClient client = new ConsoleClient(); while (GameServer.KeepRunning) { try { handler = ConsoleCtrHandler; SetConsoleCtrlHandler(handler, true); Console.Write("> "); string line = Console.ReadLine(); string[] para = line.Split(' '); switch (para[0]) { case "exit": GameServer.KeepRunning = false; break; case "cp": GameClient[] clients = GameServer.Instance.GetAllClients(); int clientCount = clients == null ? 0 : clients.Length; GamePlayer[] players = WorldMgr.GetAllPlayers(); int playerCount = players == null ? 0 : players.Length; List <BaseRoom> rooms = RoomMgr.GetAllUsingRoom(); int roomCount = 0; int gameCount = 0; foreach (BaseRoom r in rooms) { if (!r.IsEmpty) { roomCount++; if (r.IsPlaying) { gameCount++; } } } double memoryCount = GC.GetTotalMemory(false); Console.WriteLine(string.Format("Total Clients/Players:{0}/{1}", clientCount, playerCount)); Console.WriteLine(string.Format("Total Rooms/Games:{0}/{1}", roomCount, gameCount)); Console.WriteLine(string.Format("Total Momey Used:{0} MB", memoryCount / 1024 / 1024)); break; case "shutdown": _count = 6; //_timer = new Timer(new TimerCallback(GameServer.Instance.ShutDownCallBack), null, 0, 60 * 1000); _timer = new Timer(new TimerCallback(ShutDownCallBack), null, 0, 60 * 1000); break; case "savemap": //TODO: break; case "clear": Console.Clear(); break; case "ball&reload": if (BallMgr.ReLoad()) { Console.WriteLine("Ball info is Reload!"); } else { Console.WriteLine("Ball info is Error!"); } break; case "map&reload": if (MapMgr.ReLoadMap()) { Console.WriteLine("Map info is Reload!"); } else { Console.WriteLine("Map info is Error!"); } break; case "mapserver&reload": if (MapMgr.ReLoadMapServer()) { Console.WriteLine("mapserver info is Reload!"); } else { Console.WriteLine("mapserver info is Error!"); } break; case "prop&reload": if (PropItemMgr.Reload()) { Console.WriteLine("prop info is Reload!"); } else { Console.WriteLine("prop info is Error!"); } break; case "item&reload": if (ItemMgr.ReLoad()) { Console.WriteLine("item info is Reload!"); } else { Console.WriteLine("item info is Error!"); } break; case "shop&reload": if (ShopMgr.ReLoad()) { Console.WriteLine("shop info is Reload!"); } else { Console.WriteLine("shop info is Error!"); } break; case "quest&reload": if (QuestMgr.ReLoad()) { Console.WriteLine("quest info is Reload!"); } else { Console.WriteLine("quest info is Error!"); } break; case "fusion&reload": if (FusionMgr.ReLoad()) { Console.WriteLine("fusion info is Reload!"); } else { Console.WriteLine("fusion info is Error!"); } break; case "consortia&reload": if (ConsortiaMgr.ReLoad()) { Console.WriteLine("consortiaMgr info is Reload!"); } else { Console.WriteLine("consortiaMgr info is Error!"); } break; case "rate&reload": if (RateMgr.ReLoad()) { Console.WriteLine("Rate Rate is Reload!"); } else { Console.WriteLine("Rate Rate is Error!"); } break; case "fight&reload": if (FightRateMgr.ReLoad()) { Console.WriteLine("FightRateMgr is Reload!"); } else { Console.WriteLine("FightRateMgr is Error!"); } break; case "dailyaward&reload": if (AwardMgr.ReLoad()) { Console.WriteLine("dailyaward is Reload!"); } else { Console.WriteLine("dailyaward is Error!"); } break; case "language&reload": if (LanguageMgr.Reload("")) { Console.WriteLine("language is Reload!"); } else { Console.WriteLine("language is Error!"); } break; case "nickname": Console.WriteLine("Please enter the nickname"); string nickname = Console.ReadLine(); string state = WorldMgr.GetPlayerStringByPlayerNickName(nickname); Console.WriteLine(state); break; default: if (line.Length <= 0) { break; } if (line[0] == '/') { line = line.Remove(0, 1); line = line.Insert(0, "&"); } try { bool res = CommandMgr.HandleCommandNoPlvl(client, line); if (!res) { Console.WriteLine("Unknown command: " + line); } } catch (Exception e) { Console.WriteLine(e.ToString()); } break; } } catch (Exception ex) { Console.WriteLine(ex); } } if (GameServer.Instance != null) { GameServer.Instance.Stop(); } LogManager.Shutdown(); }
public async Task<bool> Execute(GameServer server, Player plr, string[] args) { return true; }
public virtual void Initialize(GameServer server) { _server = server; }
public ArenaMaster(GameServer server, Mundane mundane) : base(server, mundane) { }
public override void OnGossip(GameServer server, GameClient client, string message) { }
public ClientAnimationStateUpdate(SceneTree Tree, GameServer Server) : base(Tree, Server) { }
public TowerDefenseHandler(GameServer server, Mundane mundane) : base(server, mundane) { }
public CommandManager(GameServer server) { Server = server; }
public GrandMaster01(GameServer server, Mundane mundane) : base(server, mundane) { }
public override void OnGossip(GameServer server, GameClient client, string message) { if (message == "benson called you a pussy") { var benson = GetObject <Mundane>(client.Aisling.Map, i => i.Template.Name == "Benson"); Mundane.Target = benson ?? client.Aisling as Sprite; Mundane.Template.EnableAttacking = true; Mundane.Template.EnableTurning = true; Mundane.Template.EnableWalking = true; if (Mundane.Template.EnableAttacking) { Mundane.Template.AttackTimer = new GameServerTimer(TimeSpan.FromMilliseconds(750)); } if (Mundane.Template.EnableWalking) { Mundane.Template.EnableTurning = false; Mundane.Template.WalkTimer = new GameServerTimer(TimeSpan.FromSeconds(500)); } if (Mundane.Template.EnableTurning) { Mundane.Template.TurnTimer = new GameServerTimer(TimeSpan.FromSeconds(1)); } new TaskFactory().StartNew(() => { Thread.Sleep(3000); Mundane.Show(Scope.NearbyAislings, new ServerFormat0D { Text = "what u say c**t!!", Type = 0x00, Serial = Mundane.Serial }); Thread.Sleep(2000); Mundane.Show(Scope.NearbyAislings, new ServerFormat0D { Text = "you got a problem? there a problem!?", Type = 0x00, Serial = Mundane.Serial }); }); new TaskFactory().StartNew(() => { Thread.Sleep(12000); if (benson != null) { var quest = client.Aisling.Quests.Find(i => i.Name == "Benson_quest" && !i.Completed); quest.OnCompleted(client.Aisling); } Mundane.Show(Scope.NearbyAislings, new ServerFormat0D { Text = "fuckn weak as piss.", Type = 0x00, Serial = Mundane.Serial }); Mundane.CurrentHp = 0; Mundane.Template.TurnTimer = null; Mundane.Template.AttackTimer = null; Mundane.Template.WalkTimer = null; Mundane.Template.EnableAttacking = false; Mundane.Template.EnableWalking = false; Mundane.Template.EnableTurning = false; }); } }
private void OnEnable() { m_CallbackSteamServersConnected = Callback <SteamServersConnected_t> .CreateGameServer(OnSteamServersConnected); m_CallbackSteamServersConnectFailure = Callback <SteamServerConnectFailure_t> .CreateGameServer(OnSteamServersConnectFailure); m_CallbackSteamServersDisconnected = Callback <SteamServersDisconnected_t> .CreateGameServer(OnSteamServersDisconnected); m_CallbackPolicyResponse = Callback <GSPolicyResponse_t> .CreateGameServer(OnPolicyResponse); m_CallbackGSAuthTicketResponse = Callback <ValidateAuthTicketResponse_t> .CreateGameServer(OnValidateAuthTicketResponse); m_CallbackP2PSessionRequest = Callback <P2PSessionRequest_t> .CreateGameServer(OnP2PSessionRequest); m_CallbackP2PSessionConnectFail = Callback <P2PSessionConnectFail_t> .CreateGameServer(OnP2PSessionConnectFail); m_bInitialized = false; m_bConnectedToSteam = false; #if USE_GS_AUTH_API EServerMode eMode = EServerMode.eServerModeAuthenticationAndSecure; #else // Don't let Steam do authentication EServerMode eMode = EServerMode.eServerModeNoAuthentication; #endif // Initialize the SteamGameServer interface, we tell it some info about us, and we request support // for both Authentication (making sure users own games) and secure mode, VAC running in our game // and kicking users who are VAC banned m_bInitialized = GameServer.Init(0, SPACEWAR_AUTHENTICATION_PORT, SPACEWAR_SERVER_PORT, SPACEWAR_MASTER_SERVER_UPDATER_PORT, eMode, SPACEWAR_SERVER_VERSION); if (!m_bInitialized) { Debug.Log("SteamGameServer_Init call failed"); return; } // Set the "game dir". // This is currently required for all games. However, soon we will be // using the AppID for most purposes, and this string will only be needed // for mods. it may not be changed after the server has logged on SteamGameServer.SetModDir("spacewar"); // These fields are currently required, but will go away soon. // See their documentation for more info SteamGameServer.SetProduct("SteamworksExample"); SteamGameServer.SetGameDescription("Steamworks Example"); /* * // We don't support specators in our game. * // .... but if we did: * //SteamGameServer.SetSpectatorPort( ... ); * //SteamGameServer.SetSpectatorServerName( ... ); * * //SteamGameServer.SetDedicatedServer(true); * SteamGameServer.SetPasswordProtected(false); * SteamGameServer.SetMaxPlayerCount(4); * SteamGameServer.SetServerName("Test Server"); * SteamGameServer.SetMapName("Test Map");*/ // Initiate Anonymous logon. // Coming soon: Logging into authenticated, persistent game server account SteamGameServer.LogOnAnonymous(); // We want to actively update the master server with our presence so players can // find us via the steam matchmaking/server browser interfaces #if USE_GS_AUTH_API SteamGameServer.EnableHeartbeats(true); #endif Debug.Log("Started."); }
public override void OnResponse(GameServer server, GameClient client, ushort responseID, string args) { var quest = client.Aisling.Quests.FirstOrDefault(i => i.Name == Mundane.Template.QuestKey); if (client.DlgSession != null && client.DlgSession.Serial == SequenceMenu.Serial) { switch (responseID) { case 0: SequenceMenu.SequenceIndex = 0; client.DlgSession = null; break; case 1: if (SequenceMenu.CanMoveNext) { SequenceMenu.MoveNext(client); SequenceMenu.Invoke(client); } ; break; case 0x0010: client.SendOptionsDialog(Mundane, "sweet, Bring me some rat shit. (10)"); if (quest != null) { quest.Started = true; quest.TimeStarted = DateTime.UtcNow; } break; case 0x0011: client.SendOptionsDialog(Mundane, "I'll hook you up with something good!", new OptionsDataItem(0x0010, "Sure, Ok then!"), new OptionsDataItem(0x0012, "Don't need anything mate.") ); break; case 0x0012: client.SendOptionsDialog(Mundane, "well f**k you then."); break; case ushort.MaxValue: if (SequenceMenu.CanMoveBack) { var idx = (ushort)(SequenceMenu.SequenceIndex - 1); SequenceMenu.SequenceIndex = idx; client.DlgSession.Sequence = idx; client.Send(new ServerFormat30(client, SequenceMenu)); } break; case 0x0015: if (quest != null && !quest.Rewarded && !quest.Completed) { quest.OnCompleted(client.Aisling); } break; case 0x0016: if (quest != null && !quest.Rewarded && !quest.Completed) { quest.OnCompleted(client.Aisling); } break; case 0x0017: if (quest != null && !quest.Rewarded && !quest.Completed) { quest.OnCompleted(client.Aisling); client.SendOptionsDialog(Mundane, "Thank you."); } break; } } }
public OldMan(GameServer server, Mundane mundane) : base(server, mundane) { }
/// <summary> /// 冒险契约充值接口 /// </summary> /// <param name="OrderNo">订单号</param> /// <returns>返回充值结果</returns> public string Pay(string OrderNo) { order = os.GetOrder(OrderNo); //获取用户的充值订单 gu = gus.GetGameUser(order.UserName); //获取充值用户 gs = gss.GetGameServer(order.ServerId); //获取用户要充值的服务器 string PayGold = (order.PayMoney * game.GameMoneyScale).ToString(); //计算支付的游戏币 if (gus.IsGameUser(gu.UserName)) //判断用户是否属于平台 { tstamp = Utils.GetTimeSpan(); //获取时间戳 Sign = DESEncrypt.Md5(gu.UserName + gc.AgentId + OrderNo + order.PayMoney + gc.PayTicket + tstamp + gs.ServerNo + "mxqy", 32); string PayUrl = "http://" + gc.PayCom + "?game=mxqy&agent=" + gc.AgentId + "&user="******"&order=" + OrderNo + "&money=" + order.PayMoney + "&server=" + gs.ServerNo + "&time=" + tstamp + "&sign=" + Sign; GameUserInfo gui = Sel(gu.Id, gs.Id); //获取玩家查询信息 if (gui.Message == "Success") //判断玩家是否存在 { if (order.State == 1) //判断订单状态是否为支付状态 { string PayResult = Utils.GetWebPageContent(PayUrl); //获取充值结果 switch (PayResult) { case "1": if (os.UpdateOrder(order.OrderNo)) //更新订单状态为已完成 { gus.UpdateGameMoney(gu.UserName, order.PayMoney); //跟新玩家游戏消费情况 return("充值成功!"); } else { return("充值失败!错误原因:更新订单状态失败!"); } case "0": return("充值失败!错误原因:参数不全!"); case "2": return("充值失败!错误原因:不存在的合作方!"); case "3": return("充值失败!错误原因:金额错误!"); case "4": return("充值失败!错误原因:服务器不存在!"); case "5": return("充值失败!错误原因:验证失败!"); case "6": return("充值失败!错误原因:游戏不存在!"); case "7": return("充值失败!错误原因:角色不存在!"); case "-7": return("充值失败!错误原因:无法提交重复订单!"); case "-1": return("充值失败!错误原因:非法访问的IP!"); case "-4": return("充值失败!错误原因:未知错误!"); case "-102": return("充值失败!错误原因:游戏无响应!"); default: return("充值失败!未知错误!"); } } else { return("充值失败!错误原因:无法提交未支付订单!"); } } else { return(gui.Message); } } else { return("充值失败!错误原因:用户不存在"); } }
public override void OnResponse(GameServer server, GameClient client, ushort responseID, string args) { if (responseID == 0x0006) { client.SendOptionsDialog(Mundane, "Are you sure you want to leave?", new OptionsDataItem(0x0060, "Leave"), new OptionsDataItem(0x0070, "Continue Fighting")); } if (responseID == 0x0060) { client.Revive(); client.SendStats(StatusFlags.All); client.Refresh(); client.Aisling.PortalSession = new PortalSession { IsMapOpen = false }; client.Aisling.PortalSession.TransitionToMap(client); client.CloseDialog(); } if (responseID == 0x0001) { if (client.Aisling.CurrentMapId == 508) { client.TransitionToMap(509, new Position(4, 4)); } else { client.WarpTo(new Position(4, 4)); client.CloseDialog(); } } if (responseID == 0x0002) { if (client.Aisling.CurrentMapId == 508) { client.TransitionToMap(509, new Position(51, 4)); } else { client.WarpTo(new Position(51, 4)); client.CloseDialog(); } } if (responseID == 0x0003) { if (client.Aisling.CurrentMapId == 508) { client.TransitionToMap(509, new Position(51, 51)); } else { client.WarpTo(new Position(51, 51)); client.CloseDialog(); } } if (responseID == 0x0004) { if (client.Aisling.CurrentMapId == 508) { client.TransitionToMap(509, new Position(4, 51)); } else { client.WarpTo(new Position(4, 51)); client.CloseDialog(); } } if (responseID == 0x0005) { if (client.Aisling.CurrentMapId == 508) { client.TransitionToMap(509, new Position(35, 35)); } else { client.WarpTo(new Position(35, 35)); client.CloseDialog(); } } }
public override void Update(float deltaTime, Camera cam) { #if SERVER if (GameMain.Server != null && nextServerLogWriteTime != null) { if (Timing.TotalTime >= (float)nextServerLogWriteTime) { GameServer.Log(lastUser.LogName + " adjusted reactor settings: " + "Temperature: " + (int)(temperature * 100.0f) + ", Fission rate: " + (int)targetFissionRate + ", Turbine output: " + (int)targetTurbineOutput + (autoTemp ? ", Autotemp ON" : ", Autotemp OFF"), ServerLog.MessageType.ItemInteraction); nextServerLogWriteTime = null; lastServerLogWriteTime = (float)Timing.TotalTime; } } #endif //if an AI character was using the item on the previous frame but not anymore, turn autotemp on // (= bots turn autotemp back on when leaving the reactor) if (lastAIUser != null) { if (lastAIUser.SelectedConstruction != item && lastAIUser.CanInteractWith(item)) { AutoTemp = true; unsentChanges = true; lastAIUser = null; } } prevAvailableFuel = AvailableFuel; ApplyStatusEffects(ActionType.OnActive, deltaTime, null); //use a smoothed "correct output" instead of the actual correct output based on the load //so the player doesn't have to keep adjusting the rate impossibly fast when the load fluctuates heavily correctTurbineOutput += MathHelper.Clamp((load / MaxPowerOutput * 100.0f) - correctTurbineOutput, -10.0f, 10.0f) * deltaTime; //calculate tolerances of the meters based on the skills of the user //more skilled characters have larger "sweet spots", making it easier to keep the power output at a suitable level float tolerance = MathHelper.Lerp(2.5f, 10.0f, degreeOfSuccess); optimalTurbineOutput = new Vector2(correctTurbineOutput - tolerance, correctTurbineOutput + tolerance); tolerance = MathHelper.Lerp(5.0f, 20.0f, degreeOfSuccess); allowedTurbineOutput = new Vector2(correctTurbineOutput - tolerance, correctTurbineOutput + tolerance); optimalTemperature = Vector2.Lerp(new Vector2(40.0f, 60.0f), new Vector2(30.0f, 70.0f), degreeOfSuccess); allowedTemperature = Vector2.Lerp(new Vector2(30.0f, 70.0f), new Vector2(10.0f, 90.0f), degreeOfSuccess); optimalFissionRate = Vector2.Lerp(new Vector2(30, AvailableFuel - 20), new Vector2(20, AvailableFuel - 10), degreeOfSuccess); optimalFissionRate.X = Math.Min(optimalFissionRate.X, optimalFissionRate.Y - 10); allowedFissionRate = Vector2.Lerp(new Vector2(20, AvailableFuel), new Vector2(10, AvailableFuel), degreeOfSuccess); allowedFissionRate.X = Math.Min(allowedFissionRate.X, allowedFissionRate.Y - 10); float heatAmount = GetGeneratedHeat(fissionRate); float temperatureDiff = (heatAmount - turbineOutput) - Temperature; Temperature += MathHelper.Clamp(Math.Sign(temperatureDiff) * 10.0f * deltaTime, -Math.Abs(temperatureDiff), Math.Abs(temperatureDiff)); //if (item.InWater && AvailableFuel < 100.0f) Temperature -= 12.0f * deltaTime; FissionRate = MathHelper.Lerp(fissionRate, Math.Min(targetFissionRate, AvailableFuel), deltaTime); TurbineOutput = MathHelper.Lerp(turbineOutput, targetTurbineOutput, deltaTime); float temperatureFactor = Math.Min(temperature / 50.0f, 1.0f); currPowerConsumption = -MaxPowerOutput *Math.Min(turbineOutput / 100.0f, temperatureFactor); //if the turbine output and coolant flow are the optimal range, //make the generated power slightly adjust according to the load // (-> the reactor can automatically handle small changes in load as long as the values are roughly correct) if (turbineOutput > optimalTurbineOutput.X && turbineOutput < optimalTurbineOutput.Y && temperature > optimalTemperature.X && temperature < optimalTemperature.Y) { float maxAutoAdjust = maxPowerOutput * 0.1f; autoAdjustAmount = MathHelper.Lerp( autoAdjustAmount, MathHelper.Clamp(-load - currPowerConsumption, -maxAutoAdjust, maxAutoAdjust), deltaTime * 10.0f); } else { autoAdjustAmount = MathHelper.Lerp(autoAdjustAmount, 0.0f, deltaTime * 10.0f); } currPowerConsumption += autoAdjustAmount; if (shutDown) { targetFissionRate = 0.0f; targetTurbineOutput = 0.0f; } else if (autoTemp) { UpdateAutoTemp(2.0f, deltaTime); } float currentLoad = 0.0f; List <Connection> connections = item.Connections; if (connections != null && connections.Count > 0) { foreach (Connection connection in connections) { if (!connection.IsPower) { continue; } foreach (Connection recipient in connection.Recipients) { if (!(recipient.Item is Item it)) { continue; } PowerTransfer pt = it.GetComponent <PowerTransfer>(); if (pt == null) { continue; } //calculate how much external power there is in the grid //(power coming from somewhere else than this reactor, e.g. batteries) float externalPower = Math.Max(CurrPowerConsumption - pt.CurrPowerConsumption, 0) * 0.95f; //reduce the external power from the load to prevent overloading the grid currentLoad = Math.Max(currentLoad, pt.PowerLoad - externalPower); } } } loadQueue.Enqueue(currentLoad); while (loadQueue.Count() > 60.0f) { load = loadQueue.Average(); loadQueue.Dequeue(); } if (fissionRate > 0.0f) { foreach (Item item in item.ContainedItems) { if (!item.HasTag("reactorfuel")) { continue; } item.Condition -= fissionRate / 100.0f * fuelConsumptionRate * deltaTime; } if (item.CurrentHull != null) { var aiTarget = item.CurrentHull.AiTarget; float range = Math.Abs(currPowerConsumption) / MaxPowerOutput; float noise = MathHelper.Lerp(aiTarget.MinSoundRange, aiTarget.MaxSoundRange, range); aiTarget.SoundRange = Math.Max(aiTarget.SoundRange, noise); } if (item.AiTarget != null) { var aiTarget = item.AiTarget; float range = Math.Abs(currPowerConsumption) / MaxPowerOutput; aiTarget.SoundRange = MathHelper.Lerp(aiTarget.MinSoundRange, aiTarget.MaxSoundRange, range); } } item.SendSignal(0, ((int)(temperature * 100.0f)).ToString(), "temperature_out", null); UpdateFailures(deltaTime); #if CLIENT UpdateGraph(deltaTime); #endif AvailableFuel = 0.0f; sendUpdateTimer = Math.Max(sendUpdateTimer - deltaTime, 0.0f); if (unsentChanges && sendUpdateTimer <= 0.0f) { #if SERVER if (GameMain.Server != null) { item.CreateServerEvent(this); } #endif #if CLIENT if (GameMain.Client != null) { item.CreateClientEvent(this); } #endif sendUpdateTimer = NetworkUpdateInterval; unsentChanges = false; } }
public override void OnResponse(GameServer server, GameClient client, ushort responseID, string args) { var spells = ServerContext.GlobalSpellTemplateCache.Select(i => i.Value) .Where(i => i.NpcKey != null && i.NpcKey.Equals(Mundane.Template.Name)).ToArray(); var availableSpellTemplates = new List <SpellTemplate>(); foreach (var skill in spells) { if (skill.Prerequisites != null) { if (skill.Prerequisites.Class_Required == client.Aisling.Path) { availableSpellTemplates.Add(skill); } } if (skill.LearningRequirements != null && skill.LearningRequirements.TrueForAll(i => i.Class_Required == client.Aisling.Path)) { availableSpellTemplates.Add(skill); } } switch (responseID) { case 0x0001: var learnedSpells = client.Aisling.SpellBook.Spells.Where(i => i.Value != null) .Select(i => i.Value.Template).ToList(); var newSpells = availableSpellTemplates.Except(learnedSpells).ToList(); if (newSpells.Count > 0) { client.SendSpellLearnDialog(Mundane, "Only the dedicated can unlock the power of magic.", 0x0003, newSpells.Where(i => i.Prerequisites.Class_Required == client.Aisling.Path)); } else { client.CloseDialog(); client.SendMessage(0x02, "I have nothing to teach for now."); } break; case 0x0002: { client.SendSpellForgetDialog(Mundane, "What must you vanish from your mind?\nMake sure you understand, This cannot be un-done.", 0x9000); } break; case 0x9000: { var idx = -1; int.TryParse(args, out idx); if (idx < 0 || idx > byte.MaxValue) { client.SendMessage(0x02, "Go away."); client.CloseDialog(); } client.Aisling.SpellBook.Remove((byte)idx); client.Send(new ServerFormat18((byte)idx)); client.SendSpellForgetDialog(Mundane, "It is gone, Shall we cleanse more?\nRemember, This cannot be un-done.", 0x9000); } break; case 0x0003: client.SendOptionsDialog(Mundane, "Are you sure you want to learn " + args + "?\nDo you wish to expand your mind? Let me check if you're ready.", args, new OptionsDataItem(0x0006, $"What does {args} do?"), new OptionsDataItem(0x0004, "Yes"), new OptionsDataItem(0x0001, "No")); break; case 0x0004: { var subject = ServerContext.GlobalSpellTemplateCache[args]; if (subject == null) { return; } if (subject.Prerequisites == null) { client.CloseDialog(); client.SendMessage(0x02, ServerContext.Config.CantDoThat); } else { var conditions = subject.Prerequisites.IsMet(client.Aisling, (msg, result) => { if (!result) { client.SendOptionsDialog(Mundane, msg, subject.Name); } else { client.SendOptionsDialog(Mundane, "You have satisfied my requirements, Ready for such magic?", subject.Name, new OptionsDataItem(0x0005, "Yes, I'm Ready."), new OptionsDataItem(0x0001, "No, I'm not ready.")); } }); } } break; case 0x0006: { var subject = ServerContext.GlobalSpellTemplateCache[args]; if (subject == null) { return; } client.SendOptionsDialog(Mundane, $"{args} - {(string.IsNullOrEmpty(subject.Description) ? "No more information is available." : subject.Description)}" + "\n" + subject.Prerequisites, subject.Name, new OptionsDataItem(0x0006, $"What does {subject.Name} do?"), new OptionsDataItem(0x0004, "Yes"), new OptionsDataItem(0x0001, "No")); } break; case 0x0005: { var subject = ServerContext.GlobalSpellTemplateCache[args]; if (subject == null) { return; } client.SendAnimation(109, client.Aisling, Mundane); client.LearnSpell(Mundane, subject, "Go Spark, Aisling."); } break; } }
/// <summary> /// Crée une nouvelle instance de EntityTower. /// </summary> public EntityShop() : base() { Type = EntityType.Shop; Shop = new Equip.Shop(GameServer.GetScene().ShopDB, this, GameServer.GetScene().Constants.Structures.Shops.DefaultBuyRange); }
public static void Main(string[] args) { // Force Globalization to en-US because we use periods instead of commas for decimals CultureInfo.CurrentCulture = new CultureInfo("en-US"); // Load .env file string dotenv = Path.Combine(Paths.SOLUTION_DIR, ".env"); if (!File.Exists(dotenv)) { throw new ArgumentException(".env file not found!"); } DotEnv.Load(dotenv); InitDatabase(); // No DI here because MapleServer is static Logger logger = LogManager.GetCurrentClassLogger(); logger.Info($"MapleServer started with {args.Length} args: {string.Join(", ", args)}"); IContainer loginContainer = LoginContainerConfig.Configure(); using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope(); LoginServer loginServer = loginScope.Resolve <LoginServer>(); loginServer.Start(); IContainer gameContainer = GameContainerConfig.Configure(); using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope(); gameServer = gameScope.Resolve <GameServer>(); gameServer.Start(); // Input commands to the server while (true) { string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2); switch (input[0]) { case "exit": case "quit": gameServer.Stop(); loginServer.Stop(); return; case "send": string packet = input[1]; PacketWriter pWriter = new PacketWriter(); pWriter.Write(packet.ToByteArray()); logger.Info(pWriter); foreach (Session session in GetSessions(loginServer, gameServer)) { logger.Info($"Sending packet to {session}: {pWriter}"); session.Send(pWriter); } break; case "resolve": PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]); GameSession first = gameServer.GetSessions().Single(); resolver.Start(first); break; default: logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}"); break; } } }
public void PlaceBid(int bidAmount) { if (BidUser.HorseInventory.HorseList.Length >= BidUser.MaxHorses) { byte[] tooManyHorses = PacketBuilder.CreateChat(Messages.AuctionYouHaveTooManyHorses, PacketBuilder.CHAT_BOTTOM_RIGHT); BidUser.LoggedinClient.SendPacket(tooManyHorses); return; } string yourBidRaisedTo = Messages.FormatAuctionBidRaised(BidAmount, BidAmount + bidAmount); if (BidAmount >= MAX_BID) { byte[] maxBidReached = PacketBuilder.CreateChat(Messages.AuctionBidMax, PacketBuilder.CHAT_BOTTOM_RIGHT); BidUser.LoggedinClient.SendPacket(maxBidReached); return; } if (BidAmount + bidAmount > BidUser.Money && (AuctionItem.OwnerId != BidUser.Id)) { byte[] cantAffordBid = PacketBuilder.CreateChat(Messages.AuctionCantAffordBid, PacketBuilder.CHAT_BOTTOM_RIGHT); BidUser.LoggedinClient.SendPacket(cantAffordBid); return; } BidAmount += bidAmount; if (BidAmount > MAX_BID) // no u { yourBidRaisedTo = Messages.FormatAuctionBidRaised(BidAmount, MAX_BID); BidAmount = MAX_BID; } if (BidAmount > AuctionItem.HighestBid) { foreach (Auction room in AuctionRooms) { foreach (Auction.AuctionEntry entry in room.AuctionEntries) { if (entry.RandomId != AuctionItem.RandomId && entry.HighestBidder == BidUser.Id) { byte[] cantWinTooMuch = PacketBuilder.CreateChat(Messages.AuctionOnlyOneWinningBidAllowed, PacketBuilder.CHAT_BOTTOM_RIGHT); BidUser.LoggedinClient.SendPacket(cantWinTooMuch); return; } } } int oldBid = AuctionItem.HighestBid; AuctionItem.HighestBid = BidAmount; if (AuctionItem.HighestBidder != BidUser.Id && oldBid > 0) { if (GameServer.IsUserOnline(AuctionItem.HighestBidder)) { User oldBidder = GameServer.GetUserById(AuctionItem.HighestBidder); byte[] outbidMessage = PacketBuilder.CreateChat(Messages.FormatAuctionYourOutbidBy(BidUser.Username, AuctionItem.HighestBid), PacketBuilder.CHAT_BOTTOM_RIGHT); oldBidder.LoggedinClient.SendPacket(outbidMessage); } } AuctionItem.HighestBidder = BidUser.Id; yourBidRaisedTo += Messages.AuctionTopBid; } else { yourBidRaisedTo += Messages.AuctionExistingBidHigher; } byte[] bidPlacedMsg = PacketBuilder.CreateChat(yourBidRaisedTo, PacketBuilder.CHAT_BOTTOM_RIGHT); BidUser.LoggedinClient.SendPacket(bidPlacedMsg); }
private void NewServer(out GameServer <ServerPlayer> server, out ServerListener listener) { this.NewServer(out server, out listener, out _); }