Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
0
Indexable
Never
using System.Net.Sockets;
using System.Net;
using TicTacToe;

public class GameServer
{
    private TcpListener listener;
    private List<NetworkPlayer> players = new List<NetworkPlayer>();
    private int port; // Nastav port podle potřeby
    private bool isRunning = false;

    public GameServer(int port)
    {
        this.port = port;
        listener = new TcpListener(IPAddress.Any, port);
    }

    public void Start()
    {
        isRunning = true;
        listener.Start();
        Console.WriteLine("Server started, listening on port " + port);

        Thread clientAcceptThread = new Thread(AcceptClients);
        clientAcceptThread.Start();
    }

    private void AcceptClients()
    {
        while (isRunning)
        {
            if (!listener.Pending())
            {
                Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
                continue; // skip to next iteration of loop
            }
            TcpClient client = listener.AcceptTcpClient();
            NetworkPlayer player = new NetworkPlayer(client);
            players.Add(player);

            if (players.Count >= 2)
            {
                StartGame(players[0], players[1]);
                players.Clear();
            }
        }
    }

    private void StartGame(NetworkPlayer player1, NetworkPlayer player2)
    {
        // Send a message to each player to start the game
        player1.SendMessage("START");
        player2.SendMessage("START");

        // Create a new game
        Game game = new Game();

        // Wait for each player to send their moves
        while (true)
        {
            string move1 = player1.ReceiveMessage();
            string move2 = player2.ReceiveMessage();

            // Process the moves
            game.MakeMove(move1, Game.SquareState.X);
            game.MakeMove(move2, Game.SquareState.O);

            // Check the game state
            if (game.IsGameOver())
            {
                // If the game is over, break the loop
                break;
            }
        }
    }


    public void Stop()
    {
        isRunning = false;
        foreach (var player in players)
        {
            player.Disconnect();
        }
        listener.Stop();
        Console.WriteLine("Server stopped");
    }
}