Esempio n. 1
0
        /// <summary>
        /// Attempts to connect to the given hostname using the given nickname.
        /// </summary>
        /// <param name="hostname">The server address, excluding the port.</param>
        /// <param name="nickname">The nickname to use for the player connecting.</param>
        private void Connect(string hostname, string nickname)
        {
            // Connect to the server.
            ClientNetworking.ConnectToServer(
                hostname,
                11000,
                state =>
            {
                _socketState = state;

                // Listen for when data is received on the socket.
                _socketState.DataReceived += DataReceived;

                // Listen for when the socket disconnects.
                _socketState.Disconnected += () => { Disconnected?.Invoke(); };

                // Send the nickname of the user.
                AbstractNetworking.Send(state, nickname + '\n');

                // Wait for data.
                AbstractNetworking.GetData(state);
            },
                reason => _connectionFailedCallback(reason)
                );
        }
Esempio n. 2
0
    //Set Random Colors for Symbols
    public void setSymbols()
    {
        //Get Client
        ClientNetworking client   = ClientNetworking.getLocalClientNetworking();
        ClientNetworking opponent = ClientNetworking.getOpponentClientNetworking();

        if (client.playerNumber == Player.Player1)
        {
            player1Granny.sprite = getGrannyColor(client.playerColor);
            player2Granny.sprite = getGrannyColor(opponent.playerColor);
            player1Symbol.color  = client.playerColor;
            player2Symbol.color  = opponent.playerColor;
            player1Symbol.sprite = getSpriteBySymbol(client.playerSymbol);
            player2Symbol.sprite = getSpriteBySymbol(opponent.playerSymbol);
            player1Text.text     = "You";
            player2Text.text     = "Opponent";
        }
        else
        {
            player2Granny.sprite = getGrannyColor(client.playerColor);
            player1Granny.sprite = getGrannyColor(opponent.playerColor);
            player2Symbol.color  = client.playerColor;
            player1Symbol.color  = opponent.playerColor;
            player2Symbol.sprite = getSpriteBySymbol(client.playerSymbol);
            player1Symbol.sprite = getSpriteBySymbol(opponent.playerSymbol);
            player1Text.text     = "Opponent";
            player2Text.text     = "You";
        }
    }
Esempio n. 3
0
        /// <summary>
        /// This attempts to connect to the server at the ip provided.
        /// </summary>
        /// <param name="server">String ip of the server.</param>
        /// <param name="name">Name to send.</param>
        public void ConnectToServer(String server, String name = "Tarun")
        {
            // This is where we connect to the server for the first time. After the setup is done we
            // want our callback to be FirstContact.
            ClientNetworking.ConnectToServer(server,
                                             state =>
            {
                SuccessfulConnection?.Invoke("Connected to host: " + server);

                _socketState = state;

                // Listen for when data is received on the socket.
                _socketState.DataReceived += DataReceived;

                // Listen for when the socket disconnects.
                _socketState.Disconnected += () => { Disconnected?.Invoke(); };

                // Send the register message with the server.
                Debug.WriteLine(REGISTER, "sending register message");
                AbstractNetworking.Send(state, REGISTER);

                // Wait for data.
                AbstractNetworking.GetData(state);
            },
                                             reason => ErrorCallback?.Invoke(reason));
        }
Esempio n. 4
0
        public void Startup(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _logger = serviceProvider.GetRequiredService <ILogger>();

            _engine = serviceProvider.GetRequiredService <IClientEngine>();

            _networking = serviceProvider.GetRequiredService <ClientNetworking>();

            _entities = serviceProvider.GetRequiredService <ClientEntities>();

            _clientUI = new ImGuiInterface(_logger, _engine, this);

            _renderer = new Renderer.Renderer(
                _engine.GameWindow,
                _logger,
                _engine.FileSystem,
                _engine.CommandContext,
                _engine.UserInterface.WindowManager.InputSystem,
                _engine.Time,
                this,
                Framework.Path.EnvironmentMaps,
                Framework.Path.Shaders);

            _engine.GameWindow.Resized += _renderer.WindowResized;

            _entities.Startup(_renderer);
        }
Esempio n. 5
0
    // Use this for initialization
    void Awake()
    {
        // We are a singleton
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        else
        {
            Instance = this;
        }

        if (applicationId == -1)
        {
            applicationId = Network.Utils.GetIPBasedApplicationId();
        }

        Client            = new ClientNetworking(socketSettings, applicationId);
        Client.OnConnect += OnConnect;
        onPlayerFullPacketListenerHandle = Client.AddListener <PlayerFullPacket>(OnPlayerFullPacket);

        worldEntityManager = new WorldEntityManager(Client);
        npcManager         = new ClientNPCManager(Client, worldEntityManager);
        // don't set proxy manager up yet, as we want to wait for first player packet
        // as that is for *us* rather than proxy players

        Client.Connect();
    }
    // Use this for initialization
    void Start()
    {
        RPCHandler handler = new RPCHandler();
        RPCParser  parser  = new RPCParser(handler);

        _client = new ClientNetworking(parser, "localhost", 7777);
        _client.connect();

        handler.addResponseListener("numberResult", handleResult, handleError);
    }
Esempio n. 7
0
 public override void Connect()
 {
     Networking               = new ClientNetworking(hostname, hostPort);
     Networking.Connected    += (o, e) => SendClientInfo();
     Networking.Disconnected += (o, e) =>
     {
         Console.WriteLine("Lost connection to the server for some reason. Full? Kicked? Timed out?");
         GameClient.Instance.Disconnect();
     };
 }
Esempio n. 8
0
        public override void Connect()
        {
            Networking = new ClientNetworking(); // we need this so as to create Outgoing messages :\
            server     = ServerBase.CreateReflection();

            Config config = Config.ReadFile(settingsFilename);

            if (config == null)
            {
                config = server.CreateDefaultConfig();
                config.SaveToFile(settingsFilename);
            }

            server.Start(false, config);
            SendClientInfo();
        }
Esempio n. 9
0
    public void RpcRelayPlay(int cellNumber, Symbol symbol)
    {
        //Update States
        int row    = cellNumber / 3;
        int column = cellNumber % 3;

        GameState.Instance.updateCell(row, column, symbol);
        GameView.Instance.destroyGhost(cellNumber); //If Any

        if (symbol == playerSymbol)
        {
            GameView.Instance.updateCell(cellNumber, symbol, playerColor);
        }
        else
        {
            GameView.Instance.updateCell(cellNumber, symbol, ClientNetworking.getOpponentClientNetworking().playerColor);
        }
    }
 public ClientLogic(ILogger logger = null)
 {
     this.logger   = logger;
     clientNetwork = new ClientNetworking(logger: logger);
     LANNetwork    = new LANNetworking(logger: logger);
 }
Esempio n. 11
0
        private void btnStartHost_Click(object sender, EventArgs e)
        {
            // Prevent Changes
            tabsType.Enabled = false;

            if (string.IsNullOrEmpty(txtPlayerNameHost.Text))
            {
                MessageBox.Show("NoName");
                tabsType.Enabled = true;
                return;
            }

            if (txtPlayerNameHost.Text.ToLower().StartsWith("[bot]"))
            {
                MessageBox.Show("Bot");
                tabsType.Enabled = true;
                return;
            }

            // Save Settings
            StringCollection cardPacks = new StringCollection();

            foreach (string set in chkCardSetsHost.CheckedItems)
            {
                cardPacks.Add(set.Replace(Environment.NewLine, "_"));
            }
            Properties.Settings.Default.CardSets   = cardPacks;
            Properties.Settings.Default.Rounds     = (int)numRoundsHost.Value;
            Properties.Settings.Default.Cards      = (int)numCardsHost.Value;
            Properties.Settings.Default.NeverHaveI = chkNeverHaveIHost.Checked;
            Properties.Settings.Default.Rebooting  = chkRebootingTheUniverseHost.Checked;
            Properties.Settings.Default.Save();

            List <string> players = new List <string>();

            players.Add(txtPlayerNameHost.Text);
            int i = 0;

            while (i < (int)numPlayersHost.Value)
            {
                players.Add("FREESLOT");
                i++;
            }
            i = 0;
            while (i < (int)numBotsHost.Value)
            {
                players.Add("[Bot] " + (i + 1));
                i++;
            }
            Program.CurrentGame = new Game('H', players);
            if (Program.CurrentGame.Playable)
            {
                ClientNetworking playerNetwork = new ClientNetworking(Program.CurrentGame.Players[0], "127.0.0.1", Program.CurrentGame.HostNetwork.Port);
                playerNetwork.NextCommand = "JOIN " + txtPlayerNameHost.Text.Replace(' ', '_') + " " + Program.SessionKey;
                playerNetwork.NewCommand  = true;
                while (!playerNetwork.NewResponse)
                {
                    Application.DoEvents();
                }
                if (playerNetwork.LastResponse == "SUCCESS")
                {
                    playerNetwork.NewResponse = false;
                    Program.CurrentGame.LocalPlayers.Add(playerNetwork);

                    string IPs = "";
                    foreach (string ConnectionString in Program.CurrentGame.HostNetwork.ConnectionStrings)
                    {
                        IPs = IPs + ConnectionString + Environment.NewLine;
                    }
                    MessageBox.Show("Game Started, connect using:" + Environment.NewLine + Environment.NewLine + IPs, "Game Started", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    tabsType.Enabled = true;
                }
            }
            else
            {
                tabsType.Enabled = true;
            }
        }
Esempio n. 12
0
 public void RpcRelayWinner(VictoryType victoryType, Symbol winnerSymbol)
 {
     ServerNetworking.Instance.currentTurn = Player.None;
     GameView.Instance.displayWinner(victoryType, winnerSymbol == ClientNetworking.getLocalClientNetworking().playerSymbol);
 }
Esempio n. 13
0
 //Get Game Logic
 void Start()
 {
     client = ClientNetworking.getLocalClientNetworking();
 }
Esempio n. 14
0
        /// <summary>
        /// Join a Remote Game.
        /// </summary>
        /// <param name="address">Hostname, IPv4 or IPv6 Address of game.</param>
        /// <param name="port">TCP Port of Game.</param>
        /// <returns>If Game was joined.</returns>
        public bool Join(string address, int port)
        {
StartJoin:
            LocalPlayers = new List <ClientNetworking>();
            ClientNetworking playerNetwork;

            playerNetwork = new ClientNetworking(Players[0], address, port);
            LocalPlayers.Add(playerNetwork);
            playerNetwork.NextCommand = "HELLO";
            playerNetwork.NewCommand  = true;
            while (!playerNetwork.NewResponse)
            {
                Application.DoEvents();
            }
            string ServerHello = playerNetwork.LastResponse;

            playerNetwork.NewResponse = false;
            string[] ServerDetails = ServerHello.Split(' ');

            if (ServerDetails[3] != "0")
            {
                playerNetwork.NextCommand = "JOIN " + Players[0].Name.Replace(' ', '_') + " " + Program.SessionKey;
                playerNetwork.NewCommand  = true;
                while (!playerNetwork.NewResponse)
                {
                    Application.DoEvents();
                }
                string ServerResponse = playerNetwork.LastResponse;
                playerNetwork.NewResponse = false;
                if (ServerResponse == "SUCCESS")
                {
                    Program.CurrentPlayer = LocalPlayers[0];
                    goto SetupGame;
                }
                else
                {
                    string reason = "Unknown Error";
                    if (ServerResponse.StartsWith("FAILED "))
                    {
                        switch (ServerResponse.Split(' ')[1])
                        {
                        case "NoSpace":
                            if (MessageBox.Show("Failed  to Join Game: No space in game.", "Join Failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                            {
                                goto StartJoin;
                            }
                            else
                            {
                                playerNetwork.NextCommand = "EXIT";
                                playerNetwork.NewCommand  = true;
                                while (!playerNetwork.NewResponse)
                                {
                                    Application.DoEvents();
                                }
                                return(false);
                            }

                        case "BadPass":
                            reason = "Name in use or Password incorrect";
                            break;
                        }
                    }
                    MessageBox.Show("Failed to Join Game: " + reason, "Failed to Join", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    playerNetwork.NextCommand = "EXIT";
                    playerNetwork.NewCommand  = true;
                    while (!playerNetwork.NewResponse)
                    {
                        Application.DoEvents();
                    }
                    return(false);
                }
SetupGame:
                Program.CurrentPlayer.NextCommand = "GETRULES";
                Program.CurrentPlayer.NewCommand  = true;
                while (!Program.CurrentPlayer.NewResponse)
                {
                    Application.DoEvents();
                }
                string[] responses = Program.CurrentPlayer.LastResponse.Split(' ');
                Program.CurrentPlayer.NewResponse = false;
                foreach (string setting in responses)
                {
                    string[] settingPair = setting.Split(':');
                    switch (settingPair[0])
                    {
                    case "CardsPerPlayer":
                        CardsPerUser = Convert.ToInt32(settingPair[1]);
                        break;

                    case "Rounds":
                        Rounds = Convert.ToInt32(settingPair[1]);
                        break;

                    case "NeverHaveI":
                        NeverHaveI = Convert.ToBoolean(settingPair[1]);
                        break;

                    case "RebootingTheUniverse":
                        RebootingTheUniverse = Convert.ToBoolean(settingPair[1]);
                        break;

                    case "Cheats":
                        Cheats = Convert.ToBoolean(settingPair[1]);
                        break;
                    }
                }

                Program.CurrentPlayer.NextCommand = "GETCARDS";
                Program.CurrentPlayer.NewCommand  = true;
                while (!Program.CurrentPlayer.NewResponse)
                {
                    Application.DoEvents();
                }
                string response = Program.CurrentPlayer.LastResponse;
                Program.CurrentPlayer.NewResponse = false;
                BinaryFormatter formatter = new BinaryFormatter();
                using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(response)))
                {
                    stream.Position = 0;
                    GameSet         = (CardSet)formatter.Deserialize(stream);
                }
                Playable = true;
                return(true);
            }
            else
            {
                if (MessageBox.Show("Failed to Join Game: No space in game.", "Join Failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                {
                    goto StartJoin;
                }
                else
                {
                    playerNetwork.NextCommand = "EXIT";
                    playerNetwork.NewCommand  = true;
                    while (!playerNetwork.NewResponse)
                    {
                        Application.DoEvents();
                    }
                    return(false);
                }
            }
        }
Esempio n. 15
0
 private void ClientMainWindow_Closed(object sender, EventArgs e)
 {
     ClientNetworking.Disconnect();
     Application.Current.Shutdown();
 }
Esempio n. 16
0
 public ClientForm()
 {
     InitializeComponent();
     networkApi = new ClientNetworking();
 }
Esempio n. 17
0
 private void Page_Loaded(object sender, RoutedEventArgs e)
 {
     LoginMenuPlayer(true, null);
     Task.Run(() => ClientNetworking.Connect());
     Task.Run(() => MainClientWorker.CheckSoundEffects());
 }
Esempio n. 18
0
        /// <summary>
        /// Start a local game.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartLocal_Click(object sender, EventArgs e)
        {
            if (lstPlayersLocal.Items.Count > 0)
            {
                // Prevent Changes
                tabsType.Enabled = false;
                // Save Settings
                StringCollection cardPacks = new StringCollection();
                foreach (string set in chkCardSetsLocal.CheckedItems)
                {
                    cardPacks.Add(set.Replace(Environment.NewLine, "_"));
                }
                Properties.Settings.Default.CardSets   = cardPacks;
                Properties.Settings.Default.Rounds     = (int)numRoundsLocal.Value;
                Properties.Settings.Default.Cards      = (int)numCardsLocal.Value;
                Properties.Settings.Default.NeverHaveI = chkNeverHaveILocal.Checked;
                Properties.Settings.Default.Rebooting  = chkRebootingTheUniverseLocal.Checked;
                Properties.Settings.Default.Save();

                List <string> players = new List <string>();
                foreach (string player in lstPlayersLocal.Items)
                {
                    players.Add(player);
                }
                Program.CurrentGame = new Game('L', players);
                if (Program.CurrentGame.Playable)
                {
                    RNGCryptoServiceProvider PassGen = new RNGCryptoServiceProvider();
                    byte[] PassBytes = new byte[32];
                    PassGen.GetBytes(PassBytes);
                    Program.SessionKey = Convert.ToBase64String(PassBytes);
                    foreach (Player player in Program.CurrentGame.Players)
                    {
                        if (!player.Name.ToLower().StartsWith("[bot]"))
                        {
                            ClientNetworking playerNetwork = new ClientNetworking(player, "127.0.0.1", Program.CurrentGame.HostNetwork.Port);
                            playerNetwork.NextCommand = "JOIN " + player.Name.Replace(' ', '_') + " " + Program.SessionKey;
                            playerNetwork.NewCommand  = true;
                            while (!playerNetwork.NewResponse)
                            {
                                Application.DoEvents();
                            }
                            if (playerNetwork.LastResponse == "SUCCESS")
                            {
                                playerNetwork.NewResponse = false;
                                Program.CurrentGame.LocalPlayers.Add(playerNetwork);
                            }
                        }
                    }
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    tabsType.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("Add some players.", "No Players", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }