Send() public method

public Send ( char opcode ) : bool
opcode char
return bool
        private void RefreshMoveOptions()
        {
            int pieceID = -1;

            switch (selEvent.CurrentType)
            {
            case PlayerSelectionEvent.SelectionType.Piece:
                pieceID = selEvent.PieceID;
                break;

            case PlayerSelectionEvent.SelectionType.Square:
                pieceID = board.PieceOnSpace(selEvent.SquarePos);
                break;
            }
            if (pieceID >= 0 && pieceID != chosenPiece.Value)
            {
                Piece       piece             = board.Pieces[pieceID];
                TurnOptions calculatedOptions = moveOptionCalculator.Send(new TurnOptionCalculatorArgs()
                {
                    pieceIndex = pieceID,
                    luaState   = LuaTranslator.GetMoveCalcState(pieceID, board, db),
                });

                displayMessage.Send(compiler.Send(new ActionIndicatorPatternCompileArgs()
                {
                    options          = calculatedOptions,
                    highlightedIndex = -1,
                    mouseOverMode    = true,
                }));
            }
            else
            {
                displayMessage.Send(null);
            }
        }
Beispiel #2
0
        private void OnReceivedAction(TurnAction action)
        {
            bool validAction = false;

            if (action.components.Count == 1 && action.components[0].type == TurnActionComponentType.Forfeit)
            {
                validAction = true;
            }
            else
            {
                int pieceIndex = board.PieceOnSpace(action.searchPiece);
                if (pieceIndex >= 0)
                {
                    TurnOptions currentOptions = turnOptionCalculator.Send(new TurnOptionCalculatorArgs()
                    {
                        pieceIndex = pieceIndex,
                        luaState   = LuaTranslator.GetMoveCalcState(pieceIndex, board, db),
                    });
                    foreach (var possible in currentOptions.options)
                    {
                        if (possible.IsEquivalent(action))
                        {
                            validAction = true;
                            break;
                        }
                    }
                }
            }
            if (!validAction)
            {
                UnityEngine.Debug.LogError("Cheating detected! Or at least a mod mismatch!");
            }
            choiceMadeEvent.Send(action);
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="eventServerInfoChanged">Invocato se il download dei dati ha causato una modifica ai dati</param>
        /// <returns></returns>
        public Task ReadData(EventHandler <EventArgs> eventServerInfoChanged = null)
        {
            return(Task.Factory.StartNew(() =>
            {
                var query = new Query(Server.Ip, Server.Port);
                query.Send('i');

                var count = query.Receive();
                var info = query.Store(count);

                if (info.Length == 0)
                {
                    /* qualcosa è andato storto? */
                    return;
                }

                Locked = int.Parse(info[0]) == 1;
                Players = new List <Player>(int.Parse(info[2]));
                Server.HostName = info[3];
                Gamemode = info[4];
                MapName = info[5];

                if (updated && eventServerInfoChanged != null)
                {
                    eventServerInfoChanged(Server, null);
                }

                updated = false;
            }));
        }
        private bool Calculate(CheckCalcArgs args)
        {
            Piece king = board.Pieces[args.kingIndex];

            for (int p = 0; p < board.Pieces.Count; p++)
            {
                Piece enemy = board.Pieces[p];
                if (enemy.OwnerPlayer != king.OwnerPlayer)
                {
                    TurnOptions moveOptions = moveOptionQuery.Send(new TurnOptionCalculatorArgs()
                    {
                        pieceIndex = p,
                        luaState   = LuaTranslator.GetMoveCalcState(p, board, db),
                    });
                    foreach (var option in moveOptions.options)
                    {
                        if (option.components[0].target == args.testPosition)
                        {
                            BalugaDebug.Log(string.Format("King {0} in check from {1} at {2}", args.kingIndex, p, enemy.BoardPosition));
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        private void SearchLocalFileMods()
        {
            localMods = modSearcher.Send(ModStrings.GetModFolder());
            Dictionary <string, int> nameMap = new Dictionary <string, int>();

            for (int i = localMods.Count - 1; i >= 0; i--)
            {
                int prevIndex;
                if (nameMap.TryGetValue(localMods[i].modName, out prevIndex))
                {
                    int prevVesion = localMods[prevIndex].numericVersion;
                    int iVersion   = localMods[i].numericVersion;
                    if (iVersion > prevVesion)
                    {
                        nameMap[localMods[i].modName] = i;
                        localMods.RemoveAt(prevIndex);
                    }
                    else
                    {
                        localMods.RemoveAt(i);
                    }
                }
            }

            Unity.GameLink.LocalMods = localMods;
        }
Beispiel #6
0
 private void OnModTranslated()
 {
     if (phase.State == (int)Phase.ModLoading)
     {
         phase.State = (int)Phase.StartCondition;
         NetworkGameState gameState = null;
         switch (lobbyChoices.MatchState)
         {
         case LobbyMatchState.FreshLobby:
         case LobbyMatchState.RepeatGame:
             if (connHelper.CurrentMode == ConnectionHelper.Mode.Host)
             {
                 try {
                     gameState = startGenerator.Send();
                 } catch (BoardSetupException ex) {
                     loadingError.Send(ex.Message);
                 }
             }
             break;
         }
         if (phase.State == (int)Phase.StartCondition)
         {
             sendGameState.Send(gameState);
         }
     }
 }
 public bool HasAnyOptions()
 {
     if (disposed)
     {
         return(false);
     }
     else
     {
         return(qHasOptions.Send(this));
     }
 }
Beispiel #8
0
        private EoTScriptState CheckGameOver()
        {
            EoTScriptState type = EoTScriptState.Undecided;

            NextTurnInfo nextTurn = nextTurnInfo.Send();

            lastCalcState.TurnInfo = LuaTranslator.GetTurnInfo(nextTurn);
            lastCalcState.Board    = LuaTranslator.GetBoard(board, db);

            luaHelper.Ready = true;
            scripts.AddGlobal("winCheckHelper", luaHelperValue);
            DynValue ret = scripts.CallFunction(db.WinLossCheck, lastCalcState.Board);

            scripts.RemoveGlobal("winCheckHelper");
            luaHelper.Ready = false;

            foreach (var options in optionCache.Values)
            {
                options.Dispose();
            }
            optionCache.Clear();

            if (ret.Type != DataType.String)
            {
                type = EoTScriptState.Error;
            }
            else
            {
                switch (ret.String.ToUpperInvariant())
                {
                case Mods.Lua.LuaConstants.GameOverFirstWins:
                    type = EoTScriptState.FirstPlayerWins;
                    break;

                case Mods.Lua.LuaConstants.GameOverSecondWins:
                    type = EoTScriptState.SecondPlayerWins;
                    break;

                case Mods.Lua.LuaConstants.GameOverTie:
                    type = EoTScriptState.Tie;
                    break;

                case Mods.Lua.LuaConstants.GameOverUndecided:
                    type = EoTScriptState.Undecided;
                    break;

                default:
                    type = EoTScriptState.Error;
                    break;
                }
            }

            return(type);
        }
 public bool CanPromote(int x, int y)
 {
     if (disposed)
     {
         return(false);
     }
     else
     {
         return(qCanPromote.Send(this, new IntVector2(x, y)));
     }
 }
 public PieceTurnOptions GetPieceTurnOptions(Piece piece)
 {
     if (ready)
     {
         return(qGetTurnOptions.Send(piece));
     }
     else
     {
         return(null);
     }
 }
 public bool DoesPlayerHaveAnyPieces(string player)
 {
     if (ready)
     {
         return(qPlayerHasPieces.Send(player));
     }
     else
     {
         return(false);
     }
 }
 public bool CanPlayerMove(string player)
 {
     if (ready)
     {
         return(qPlayerCanMove.Send(player));
     }
     else
     {
         return(false);
     }
 }
 private void OnAllReadyReceived(LobbyExitState exitState)
 {
     if (state.State == (int)LobbySetupExitState.Ready)
     {
         state.State         = (int)LobbySetupExitState.Exiting;
         screen.State        = (int)LobbyScreen.Disposing;
         choices.OrderChoice = exitState.turnOrderChoice;
         choices.ModFolder   = getModFolder.Send(exitState.modName);
         game.Controller     = new ModLoadingScene(game);
     }
 }
 public bool StartHost(int port, string password, bool wantsInProgressGames)
 {
     UnityEngine.Debug.LogError(string.Format("{0}: Start host {1} \"{2}\" {3}", UnityEngine.Time.frameCount, port, password, wantsInProgressGames));
     mode = Mode.Host;
     return(startHostCommand.Send(new StartHostCommand()
     {
         port = port,
         password = password,
         wantsInProgressGame = wantsInProgressGames,
     }));
 }
 public bool StartClient(string address, int port, string password, bool isGameInProgress)
 {
     UnityEngine.Debug.LogError(string.Format("{0}: Start client {1} {2} \"{3}\" {4}", UnityEngine.Time.frameCount, address, port, password, isGameInProgress));
     mode = Mode.Client;
     return(startClientCommand.Send(new StartClientCommand()
     {
         address = address,
         port = port,
         password = password,
         gameInProgress = isGameInProgress,
     }));
 }
Beispiel #16
0
 private void OnHighlightChange(TurnChooserHighlight hl)
 {
     if (hl.options != null)
     {
         selectedPattern.Send(compiler.Send(new ActionIndicatorPatternCompileArgs()
         {
             options          = hl.options,
             showOnly         = hl.indexesOnSpace,
             highlightedIndex = hl.highlightedIndex,
             mouseOverMode    = false,
         }));
     }
     else
     {
         selectedPattern.Send(null);
     }
 }
Beispiel #17
0
        private void Form1_Load(object sender, EventArgs e)
        {
            metroButton13.Enabled = true;
            metroButton14.Enabled = false;
            metroButton15.Enabled = true;
            metroButton16.Enabled = false;
            string output = "";

            // Server info query example
            using (Query q = new Query(metroTextBox2.Text, 7777))
            {
                q.Send('i');

                foreach (string str in q.Store(q.Recieve()))
                {
                    output += str + '\n';
                }
            }
        }
Beispiel #18
0
        public List <LocalModInfo> SearchForMods(string parentFolder)
        {
            if (tocLoader == null)
            {
                tocLoader = scene.Game.Components.Get <Query <TOCLoadResult, string> >((int)ComponentKeys.TableOfContentsLoadRequest);
            }

            List <LocalModInfo> mods = new List <LocalModInfo>();

            if (Directory.Exists(parentFolder))
            {
                foreach (var folder in Directory.GetDirectories(parentFolder))
                {
                    string        filePath  = Path.Combine(parentFolder, folder);
                    TOCLoadResult tocResult = tocLoader.Send(filePath);
                    if (tocResult.error == TOCLoadError.None)
                    {
                        TableOfContents toc  = tocResult.toc;
                        LocalModInfo    info = new LocalModInfo()
                        {
                            filePath       = filePath,
                            modName        = toc.name,
                            displayName    = toc.displayName,
                            displayVersion = toc.displayVersion,
                            numericVersion = toc.version,
                            author         = toc.author,
                        };
                        mods.Add(info);
                    }
                    else
                    {
                        UnityEngine.Debug.Log(string.Format("Unable to load mod TOC at {0}: {1}", folder, tocResult.error));
                    }
                }
            }
            else
            {
                UnityEngine.Debug.Log("Mod folder does not exist");
            }

            return(mods);
        }
Beispiel #19
0
 private void OnReconnectionReplyReceived(NetworkGameState gameState)
 {
     if (state.State == (int)ReconnectionState.WaitingForServerReply)
     {
         state.State = (int)ReconnectionState.SignaledReady;
         if (gameState == null)
         {
             BalugaDebug.Log("Server replied no game state");
             ExitToLobby();
         }
         else
         {
             Board board = createBoard.Send(gameState);
             scene.Game.Components.Remove((int)ComponentKeys.GameBoard);
             scene.Game.Components.Register((int)ComponentKeys.GameBoard, board);
             newBoardMessage.Send(board);
             sendReady.Send(true);
         }
     }
 }
Beispiel #20
0
        private PieceTurnOptions CacheTurnOptions(int logicPieceIndex)
        {
            PieceTurnOptions luaOptions;

            if (!optionCache.TryGetValue(logicPieceIndex, out luaOptions))
            {
                luaOptions = new PieceTurnOptions();
                optionCache[logicPieceIndex] = luaOptions;
                luaOptions.Piece             = lastCalcState.Board.Pieces[logicPieceIndex];
                luaOptions.QHasOptions       = turnOptionsHasOptions;
                luaOptions.QCanMove          = turnOptionsCanMove;
                luaOptions.QCanCapture       = turnOptionsCanCapture;
                luaOptions.QCanPromote       = turnOptionsCanPromote;

                lastCalcState.MovingPiece = luaOptions.Piece.Index;
                luaOptions.Options        = actionCalculator.Send(new TurnOptionCalculatorArgs()
                {
                    luaState   = lastCalcState,
                    pieceIndex = logicPieceIndex,
                });
            }
            return(luaOptions);
        }
Beispiel #21
0
 private void OnEnterState(int state)
 {
     if (chooserState.State == (int)TurnChooser.State.ChooseAction)
     {
         chosenAction.Value = null;
         inputOffsets.Clear();
         currentOptions = turnOptionCalculator.Send(new TurnOptionCalculatorArgs()
         {
             pieceIndex = chosenPiece.Value,
             luaState   = LuaTranslator.GetMoveCalcState(chosenPiece.Value, board, db),
         });
         RefreshHighlightedValue();
     }
     else
     {
         highlightMessage.Send(new TurnChooserHighlight()
         {
             options          = null,
             indexesOnSpace   = null,
             highlightedIndex = -1,
         });
         currentOptions = null;
     }
 }
Beispiel #22
0
        public static void checkGame(int gameId, string gamePath)
        {
            try {

                // If we didn't start SA-MP, return.
                if(gameId != 4039) return;

                // Initiatre our ProcessMemory objects for address checking
                ProcessMemory Mem = new ProcessMemory("gta_sa");
                ProcessMemory Mem2 = new ProcessMemory("samp");

                // if GTASA and sa-mp browser are started then
                if(Mem != null && Mem2 != null) {

                   	do {

                   		if(!Mem2.CheckProcess()) {
                   			// SA-MP browser is closed, end our checking.
                   			whenGameStopped(4039);
                   			return;

                   		}
                   		Thread.Sleep(5000);
                   		// Wait for GTA SA to be launched. (only sa-mp server browser is open at this time.)
                    } while(!Mem.CheckProcess());
                }

                #if !debug
                try {
                    if(File.Exists(g_szLogFilePath) && !File.Exists(g_szLogFilePath + "123")) {
                        if(Cryptology.DecryptFile(g_szLogFilePath, g_szLogFilePath + "123", "password removed for public src release")) {
                            if(File.Exists(g_szLogFilePath)) {
                                File.Delete(g_szLogFilePath);
                            }
                        }
                    }
                } catch(Exception) { }
                #endif

                string file = "";

                // Remove samp.exe from our path, so we can get the GTA directory, might cause problems if for some reason players have "samp.exe" in the path
                file = gamePath.Replace("samp.exe", "");

                g_szWireGamePath = file;

                string path = "";
                // check what the registry says about the GTA Directory.
                var path2 = Registry.GetValue("HKEY_CURRENT_USER\\Software\\SAMP", "gta_sa_exe", "");

                // NOTE: if path2 is null, then there are 3 things that could be true, either sa-mp isn't installed, the Registry is disabled, or a firewall blocked it
                if(path2 != null) {
                    path = path2.ToString();
                    // check if the path is valid.
                    if(path.Length > 3) {
                        // Remove "gta_sa.exe" from our file path.
                        if(path.LastIndexOf("\\") > 0) {
                            int index = path.LastIndexOf("\\");
                            path = path.Substring(0, index + 1);
                        }
                        // the sa-mp.exe launch path doesn't match the one found in registry, the one in registry is the one actually used by the SA-MP browser, so ignore ESL Wire path.
                        if(!path.Equals(file)) {
                            file = path;
                            Log.WriteLog("    -> Warning: game path from ESL Wire doesn't match SA-MP GTA Path from registry, checking registry path and ignoring ESL Wire path");
                            Log.WriteLog(" ESL Wire Path: " + gamePath);
                            Log.WriteLog(" Path in registry: " + file);
                            Log.WriteLog(" ");
                        }
                    }
                }

                int bAddr = -1;
                do {

                    Process[] p = Process.GetProcessesByName("gta_sa");
                    int idx = 0;

                    // hopefully there is only 1 gta_sa.exe started!
                    foreach(Process proc in p) {
                   		idx++;
                        if(proc != null) {
                   			// weird restart loop incase getting process filename fails below.
                   			// if it fails it will usually work the 2nd time, and if not the 2nd time, the 3rd.
                   			// if not the 3rd, then the 4th, if not the 4th, then etc..

                            bool restart = false;
                            do {
                                restart = false;
                                try {
                                    string s = Misc.getProcessPath(proc);
                                    if(File.Exists(s)) {

                                        path = s;
                                    }
                                } catch(Exception e) {
                                    Log.WriteLog(e.ToString());
                                    try {
                                        if(File.Exists(proc.MainModule.FileName)) {
                                            path = proc.MainModule.FileName;
                                        }
                                    } catch(Exception ee) {
                                        // really now?
                                        Log.WriteLog(ee.ToString());
                                        restart = true;
                                        Thread.Sleep(500);
                                    }
                                }
                            } while(restart);

                            // Get the directory path, remove gta_sa.exe.
                            if(path.Length > 3) {
                               	if(path.LastIndexOf("\\") > 0) {
                               		int index = path.LastIndexOf("\\");
                               		path = path.Substring(0, index + 1);
                               	}
                            }

                            g_bGTASAStarted = true;
                            Log.WriteLog("gta_sa.exe launched from: " + path2);
                            Log.WriteLog(" ");

                            g_szGTASaPath = path;

                            do {
                                restart = false;
                                try {
                                    // get base address for samp.dll
                                    bAddr = Modules.GetModuleBaseAddress(proc, "samp.dll");
                                } catch(Exception e) {
                                    restart = true;
                                    Log.WriteLog("Getting samp.dll offset error:");
                                    Log.WriteLog(e.ToString());
                                    Thread.Sleep(500);
                                }
                            }
                            while(restart);
                        }
                   		// it's ok, we've prepared for more than 1 gta.
                   		if(idx > 1) {
                   			proc.Kill();
                   			g_bGTASAStarted = false;
                        }
                     }
                    Thread.Sleep(500);
                } while(!g_bGTASAStarted);

               		g_bGTASAStarted = true;

                g_iCleanGame = 0;

                // samp.dll +
                /*
                 * 0x20D77D - ip
                 * 0x20D87E - port
                 * 0x20D97F - name
                 *
                 * (it'd be better to just read command line, and would be compatable with all sa-mp versions then, these are 0.3e addresses.)
                 * */
                if(Mem.StartProcess()) {

                    // get connected server IP and player name.
                    string ip = Mem.ReadStringAscii(bAddr + 0x020D77D, 30);
                    string port = Mem.ReadStringAscii(bAddr + 0x020D87E, 10);
                    string name = Mem.ReadStringAscii(bAddr + 0x020D97F, 24);

                    Log.WriteLog("Connected Server: " + ip + ":" + port + " as " + name);
                    Log.WriteLog("Attempting to Query server...");

                    // get time stamp to calculate our ping.
                    DateTime p = DateTime.Now;
                    bool restart = false;
                    do {
                        restart = false;
                        try {

                            // use sa-mp server query mechanism
                            Query sQuery = new Query(ip, int.Parse(port));

                            sQuery.Send('i');

                            int count = sQuery.Recieve();

                            string[] info = sQuery.Store(count);

                            DateTime pp = DateTime.Now;

                            TimeSpan ts = pp - p;

                            Log.WriteLog("Successfully contacted server. (ping: " + ts.Milliseconds + ")");

                            Log.WriteLog("Hostname: " + info[3]);
                            Log.WriteLog("Gamemode: " + info[4]);
                            Log.WriteLog("Players: " + info[1]);

                            Log.WriteLog(" ");

                            sQuery.Send('d');

                            count = sQuery.Recieve();

                            info = sQuery.Store(count);

                            int i = 0;

                            for(int j = 0; j < info.Length-2; ++j) {
                                // still don't understand how this works, but it does!
                                if(i == 0) {
                                    Log.WriteLog("PlayerID: " + info[j] + " || PlayerName: " + info[j+1]);
                                }
                                i++;
                                if(i == 4) i = 0;
                            }

                            Log.WriteLog(" ");

                        } catch(System.IndexOutOfRangeException) {
                            Log.WriteLog("** Failed to get player list.");
                        } catch(System.FormatException) {
                            Log.WriteLog("Failed to contact SA-MP server");
                            Log.WriteLog("** Game not initialized, retrying...");
                            restart = true;
                            Thread.Sleep(1000);
                        } catch(Exception e) {
                            Log.WriteLog("Failed to contact SA-MP server - " + ip + ":" + port + " as " + name);
                            Log.WriteLog(e.ToString());
                        }
                    } while(restart);
                }

                // Check game integrity
               		checkGameFiles( g_szGTASaPath );
               		// check some memory addresses to make sure the file path for the data files hasn't been changed.
             	Memory.VerifySomeMemoryStuff();

                // Show results.
                Log.WriteLog("Strange files in GTA SA Path: ");
                Log.WriteLog(" ");

                // paste all files in GTA SA path that aren't part of the original game.
                gtadir(g_szGTASaPath);

                Log.WriteLog(" ");

             	if(g_iCleanGame == 0) {
               		Log.WriteLog("VERDICT: Game is clean!");
               	} else {
                 	if(g_iCleanGame > 1) {
               			Log.WriteLog("VERDICT: Detected " + g_iCleanGame + " inconsistencies");
                 	} else {
                 		Log.WriteLog("VERDICT: Detected " + g_iCleanGame + " inconsistency");
                 	}
               	}
                 Log.WriteLog(" ");

                // check again in 15 minutes

                aTimer.Enabled = true;

                //#if !debug
                // encrypt our log file and delete the original .txt we where writing plain text too.
                if(File.Exists(g_szLogFilePath + "123") && !File.Exists(g_szLogFilePath)) {

                    g_szLogFileMD5 = MD5file(g_szLogFilePath + "123");
                    if(Cryptology.EncryptFile(g_szLogFilePath + "123", g_szLogFilePath, "password removed for public src release")) {
                        if(File.Exists(g_szLogFilePath + "123")) {
                            File.Delete(g_szLogFilePath + "123");
                        }
                    }
                }
                //#endif

                return;
            } catch(Exception e) { Log.WriteLog(e.ToString()); }
        }
Beispiel #23
0
        private void SendEndOfTurnState()
        {
            EoTScriptState overType;

            switch (lastActionResult)
            {
            case TurnActionExecutionResult.Success:
                overType = checkGameOver.Send();
                break;

            case TurnActionExecutionResult.Forfeit:
                overType = EoTScriptState.Forfeit;
                break;

            default:
                overType = EoTScriptState.Error;
                break;
            }

            BalugaDebug.Log("Game over type: " + overType);

            // Send win/loss/not-decided/error to server, and wait for reply
            EndOfTurnState eotState = EndOfTurnState.Error;

            switch (overType)
            {
            case EoTScriptState.FirstPlayerWins:
                if (board.LocalPlayerOrder == PlayerTurnOrder.First)
                {
                    eotState = EndOfTurnState.Win;
                }
                else
                {
                    eotState = EndOfTurnState.Loss;
                }
                break;

            case EoTScriptState.SecondPlayerWins:
                if (board.LocalPlayerOrder == PlayerTurnOrder.First)
                {
                    eotState = EndOfTurnState.Loss;
                }
                else
                {
                    eotState = EndOfTurnState.Win;
                }
                break;

            case EoTScriptState.Tie:
                eotState = EndOfTurnState.Tie;
                break;

            case EoTScriptState.Undecided:
                eotState = EndOfTurnState.Undecided;
                break;

            case EoTScriptState.Forfeit:
                eotState = EndOfTurnState.Forfeit;
                break;

            default:
                eotState = EndOfTurnState.Error;
                break;
            }

            BalugaDebug.Log("End of turn state: " + eotState);
            sendEoTState.Send(eotState);
        }
Beispiel #24
0
        private void SendGameState()
        {
            NetworkGameState state = compileGameState.Send();

            sendGameState.Send(state);
        }