public ClientProcessor(GameState gameState, int id, TcpClient client)
        {
            this.gameState = gameState;
            this._id = id;
            this.tcpClient = client;

            //Pegar o canal de cominicação
            NetworkStream stream = client.GetStream();
            reader = new StreamReader(stream);
            writer = new StreamWriter(stream);
        }
        static void Main(string[] args)
        {
            TcpListener tcpListener = null;
            int port = 9999;
            bool working = true;
            GameState gameState = new GameState();

            try
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                tcpListener = new TcpListener(ip, port);
                tcpListener.Start();

                while (working)
                {
                    //Se ainda nao se tem 02 jogadores, ficar aguardando.
                    if (!gameState.IsReady())
                    {
                        Console.WriteLine("Aguardando Conexões...");

                        //Trava até um cliente chegar
                        TcpClient tcpClient = tcpListener.AcceptTcpClient();

                        gameState.AddPlayer(tcpClient);
                    }
                    else
                    {
                        gameState.Play();
                    }
                }
            }

            catch (SocketException e) { Console.WriteLine("Erro: {0}", e); }

            finally { tcpListener.Stop(); }
        }
 protected abstract GameState CalculateState(GameState state);
        internal void GameStart()   // start communication with client services to send game state
        {
            GameState state = null;

            if (_isReplica)
            {
                // Get primary information and state
                lock (PrimaryServer) {
                    NUM_PLAYERS    = PrimaryServer.GetNumberOfPlayers();
                    MSEC_PER_ROUND = PrimaryServer.GetMsecPerRound();
                    _replicas      = PrimaryServer.GetReplicaDictionary();
                    _replicas.Remove(Id); // removes himself from the replicas list
                    _clientList = PrimaryServer.GetPlayerList();
                    foreach (var client in _clientList.Values)
                    {
                        _isDelayed[client.GetPid()] = false;
                    }
                    Inputs  = PrimaryServer.GetInputList();
                    _states = PrimaryServer.GetStateList();

                    // update replica UI
                    UpdateStatus(Status.ReplicaStandby);
                    foreach (string client in _clientList.Keys)
                    {
                        _form.Invoke(new AddPlayerDelegate(_form.AddPlayer), client);
                    }
                    _imAliveThread.Start();
                    Monitor.Wait(PrimaryServer);
                }
            }
            else
            {
                _imAliveThread.Start();
                UpdateStatus(Status.WaitingPlayers);
                lock (_clientList) {
                    while (_clientList.Count < NUM_PLAYERS)
                    {
                        Monitor.Wait(_clientList);
                        if (!_running)
                        {
                            return;            // Someone might terminate the server while waiting for players
                        }
                    }
                }
            }

            UpdateStatus(Status.GameStarted);
            if (RoundTimestamp >= 0)   // initial state has RoundTimestamp = -1, this is in case the primary server crashes and a replica takes place
            {
                lock (_states) {
                    state = _states[RoundTimestamp];
                }
            }
            else
            {
                state = CalculateInitialState(); // Initial state
                state.RoundTimestamp = RoundTimestamp;
                UpdateRoundTimestamp();
                UpdateReplicasState(state);
                UpdateClients(state);
            }
            _acceptingInput = true;

            while (_running && !state.GameOver())
            {
                Thread.Sleep(MSEC_PER_ROUND);
                state = CalculateState(state);
                state.RoundTimestamp = RoundTimestamp;
                UpdateRoundTimestamp();
                UpdateReplicasState(state);
                UpdateClients(state);
                lock (_states) {
                    _states.Add(state.Copy());
                }
            }
            _acceptingInput = false;
            NotifyGameOver();
            UpdateStatus(Status.GameEnd);
        }
        static void Main(string[] args)
        {
            _rand = new Random(Environment.TickCount);

            SslConfig sslConfig;
            TcpConfig tcpConfig = new TcpConfig(true, 5000, 20000);

            Console.WriteLine("Setting up secure server");
            sslConfig  = new SslConfig(true, "cert.pfx", "", SslProtocols.Tls12);
            _webServer = new SimpleWebServer(10000, tcpConfig, 16 * 1024, 3000, sslConfig);
            _webServer.Start(Constants.GAME_PORT);
            Console.WriteLine("Server started");

            _webServer.onConnect    += WebServerOnConnect;
            _webServer.onData       += WebServerOnData;
            _webServer.onDisconnect += WebServerOnDisconnect;

            Timer stateUpdateTimer = new Timer(1f / Constants.SERVER_TICKRATE * 1000);

            stateUpdateTimer.Elapsed  += StateUpdateTimerOnElapsed;
            stateUpdateTimer.AutoReset = true;
            stateUpdateTimer.Enabled   = true;

            while (!Console.KeyAvailable)
            {
                _webServer.ProcessMessageQueue();

                // GUARD, DONT DO STATE STUFF IF WE ARE WAITING
                if (_waitingOnStateTimer)
                {
                    continue;
                }
                switch (_currentState)
                {
                case GameState.Waiting:
                {
                    if (_connectedIds.Count >= 2)
                    {
                        _currentState = GameState.Begin;
                        SendStateUpdate(_currentState);
                    }

                    break;
                }

                case GameState.Begin:
                {
                    // Set timer to go to builder state
                    beginTimer           = new Timer(SECONDS_WAITING_IN_BEGIN * 1000);
                    beginTimer.AutoReset = false;
                    beginTimer.Start();
                    _waitingOnStateTimer = true;

                    beginTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        _movedObjects = new Dictionary <ushort, Tuple <ushort, ushort> >;
                        _currentState = GameState.Builder;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Builder:
                {
                    // Set timer to go to builder state
                    buildTimer           = new Timer(SECONDS_WAITING_IN_BUILD * 1000);
                    buildTimer.AutoReset = false;
                    buildTimer.Start();
                    _waitingOnStateTimer = true;

                    buildTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        // Reset everyones guesses
                        foreach (PlayerData playerData in _playerDatas.Values)
                        {
                            playerData.guesses.Clear();
                        }
                        _currentState = GameState.Search;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Search:
                {
                    // Set timer to go to scoring state
                    searchTimer           = new Timer(SECONDS_WAITING_IN_SEARCH * 1000);
                    searchTimer.AutoReset = false;
                    searchTimer.Start();
                    _waitingOnStateTimer = true;

                    searchTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        _currentState = GameState.Scoring;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Scoring:
                {
                    // Set timer to wait for points to come in from clients
                    scoringTimer           = new Timer(SECONDS_WAITING_IN_SCORING * 1000);
                    scoringTimer.AutoReset = false;
                    scoringTimer.Start();
                    _waitingOnStateTimer = true;

                    scoringTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        // Tell everyone everyones scores
                        _bitBuffer.Clear();
                        _bitBuffer.AddByte(7);
                        _bitBuffer.AddUShort((ushort)_playerDatas.Count);

                        foreach (PlayerData data in _playerDatas.Values)
                        {
                            _bitBuffer.AddUShort(data.id);
                            _bitBuffer.AddShort(data.points);
                        }

                        _bitBuffer.ToArray(_buffer);
                        _webServer.SendAll(_connectedIds, new ArraySegment <byte>(_buffer, 0, 3 + 4 * _playerDatas.Count));

                        if (_connectedIds.Count >= 2)
                        {
                            _currentState = GameState.Begin;
                        }
                        else
                        {
                            _currentState = GameState.Waiting;
                        }
                        SendStateUpdate(_currentState);
                    };

                    break;
                }
                }
            }

            Console.WriteLine("Closing server");
            _webServer.Stop();
        }
Exemple #6
0
        static void Main(string[] args)
        {
            _rand = new Random(Environment.TickCount);

            SslConfig sslConfig;
            TcpConfig tcpConfig = new TcpConfig(true, 5000, 20000);

            Console.WriteLine("Setting up secure server");
            sslConfig  = new SslConfig(true, "cert.pfx", "", SslProtocols.Tls12);
            _webServer = new SimpleWebServer(10000, tcpConfig, 16 * 1024, 3000, sslConfig);
            _webServer.Start(Constants.GAME_PORT);
            Console.WriteLine("Server started");

            _webServer.onConnect    += WebServerOnConnect;
            _webServer.onData       += WebServerOnData;
            _webServer.onDisconnect += WebServerOnDisconnect;

            Timer stateUpdateTimer = new Timer(1f / Constants.SERVER_TICKRATE * 1000);

            stateUpdateTimer.Elapsed  += StateUpdateTimerOnElapsed;
            stateUpdateTimer.AutoReset = true;
            stateUpdateTimer.Enabled   = true;

            while (!Console.KeyAvailable)
            {
                _webServer.ProcessMessageQueue();

                // GUARD, DONT DO STATE STUFF IF WE ARE WAITING
                if (_waitingOnStateTimer)
                {
                    continue;
                }
                switch (_currentState)
                {
                case GameState.Waiting:
                {
                    if (_connectedIds.Count >= 2)
                    {
                        _currentState = GameState.Begin;
                        SendStateUpdate(_currentState);
                    }

                    break;
                }

                case GameState.Begin:
                {
                    // Set timer to go to builder state
                    beginTimer           = new Timer(SECONDS_WAITING_IN_BEGIN * 1000);
                    beginTimer.AutoReset = false;
                    beginTimer.Start();
                    _waitingOnStateTimer = true;

                    beginTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        _movedObjects = new List <ushort>();
                        _currentState = GameState.Builder;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Builder:
                {
                    // Set timer to go to builder state
                    buildTimer           = new Timer(SECONDS_WAITING_IN_BUILD * 1000);
                    buildTimer.AutoReset = false;
                    buildTimer.Start();
                    _waitingOnStateTimer = true;

                    buildTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        // Reset everyones guesses
                        foreach (PlayerData playerData in _playerDatas.Values)
                        {
                            playerData.guesses.Clear();
                        }
                        _currentState = GameState.Search;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Search:
                {
                    // Set timer to go to scoring state
                    searchTimer           = new Timer(SECONDS_WAITING_IN_SEARCH * 1000);
                    searchTimer.AutoReset = false;
                    searchTimer.Start();
                    _waitingOnStateTimer = true;

                    searchTimer.Elapsed += delegate(Object source, ElapsedEventArgs e) {
                        _waitingOnStateTimer = false;

                        _currentState = GameState.Scoring;
                        SendStateUpdate(_currentState);
                    };
                    break;
                }

                case GameState.Scoring:
                {
                    short builderPoints = 0;

                    _bitBuffer.Clear();
                    _bitBuffer.AddByte(7);
                    _bitBuffer.AddUShort((ushort)_playerDatas.Count);


                    foreach (var playerData in _playerDatas.Values)
                    {
                        // GUARD, DON'T SCORE THE BUILDER THIS WAY
                        if (playerData.id == _builderId)
                        {
                            continue;
                        }

                        // Free points for objects builder couldnt move
                        // A point for a correct guess, minus point for a wrong guess
                        int numCorrect = _movedObjects.Distinct().Intersect(playerData.guesses).Count();
                        int newPoints  = (numCorrect * 2) - playerData.guesses.Count + (NUMBER_OF_MOVEABLE_OBJECTS - _movedObjects.Count);
                        playerData.points += (short)newPoints;

                        // Builder gets a point for each player who couldnt find any differences
                        if (numCorrect == 0)
                        {
                            builderPoints += 1;
                        }

                        _bitBuffer.AddUShort(playerData.id);
                        _bitBuffer.AddShort(playerData.points);
                    }

                    _playerDatas[_builderId].points += builderPoints;
                    _bitBuffer.AddUShort((ushort)_builderId);
                    _bitBuffer.AddShort(_playerDatas[_builderId].points);

                    _bitBuffer.ToArray(_buffer);
                    _webServer.SendAll(_connectedIds, new ArraySegment <byte>(_buffer, 0, 3 + 2 * _playerDatas.Count));

                    if (_connectedIds.Count >= 2)
                    {
                        _currentState = GameState.Begin;
                    }
                    else
                    {
                        _currentState = GameState.Waiting;
                    }
                    SendStateUpdate(_currentState);

                    break;
                }
                }
            }

            Console.WriteLine("Closing server");
            _webServer.Stop();
        }