Exemplo n.º 1
0
 public static void setJugador2(Jugador player)
 {
     j2 = player;
 }
Exemplo n.º 2
0
 public static void setJugador1(Jugador player)
 {
     j1 = player;
 }
Exemplo n.º 3
0
        private void ManejarCliente(TcpClient cli)
        {
            string data;

            NetworkStream ns = cli.GetStream();
            StreamReader  sr = new StreamReader(ns);
            StreamWriter  sw = new StreamWriter(ns);
            string        ip = cli.Client.RemoteEndPoint.ToString().Split(':')[0];

            //confirmacion de conexion
            sw.WriteLine("OK");
            sw.Flush();


            while (true)
            {
                try
                {
                    //Manejo del cliente
                    //instrucciones del juego AQUI

                    data = sr.ReadLine();
                    Console.WriteLine("data: " + data); //para depurar en el server
                    String[] subdatos = data.Split('#');

                    #region comINSCRIBIR
                    if (subdatos[1] == "INSCRIBIR")
                    {
                        if (!p.PartidaIniciada)
                        {
                            if (Jugadores.Count < jugadoresMax)
                            {
                                if (!Jugadores.Any(c => c.Nick.Equals(subdatos[2])))
                                {
                                    puertoEscucha++;
                                    sw.WriteLine("#OK#" + puertoEscucha + "#");
                                    sw.Flush();
                                    EnviarInstruccion(8, subdatos[2] + " ENTRÓ EN LA SALA" + "#"); //Aviso a todos los jugadores que el cliente entró en la sala
                                    Jugadores.Add(new Jugador(cli, subdatos[2], cli.Client.RemoteEndPoint.ToString().Split(':')[0], puertoEscucha));
                                    del = new DelegadoEscribirLista(escribirListaClientes);
                                    del.Invoke();
                                }
                                else
                                {
                                    sw.WriteLine("#NOK#el nick ya existe, elige otro");
                                    sw.Flush();
                                }
                            }
                            else
                            {
                                sw.WriteLine("#NOK#Límite máximo de " + jugadoresMax + " jugadores alcanzado#");
                                sw.Flush();
                            }
                        }
                        else
                        {
                            sw.WriteLine("#NOK#Ya hay una partida en curso#");
                            sw.Flush();
                        }
                    }
                    #endregion

                    #region com LISTOPARAJUGAR
                    if (subdatos[1] == "LISTOPARAJUGAR")
                    {
                        lock (key)
                        {
                            try
                            {
                                Jugador j = Jugadores.Find(c => c.Cliente.Equals(cli));
                                Console.WriteLine(subdatos[1]);
                                //El jugador esta listo para jugar la partida
                                j.Listoparajugar = true;
                                sw.WriteLine("#OK#" + numericUpDown_tiempoRonda.Value + "#");
                                sw.Flush();

                                EnviarInstruccion(8, j.Nick.ToUpper() + " ESTÁ LISTO!" + "#");


                                // SI TODOS LOS JUGADORES ESTÁN LISTOS INICIA NUEVA PARTIDA
                                if (Jugadores.All(c => c.Listoparajugar) == true)
                                {
                                    Console.WriteLine("Todos los jugadores estan listos para jugar");
                                    p.PartidaIniciada = true;
                                    p.MaxPuntos       = Convert.ToInt32(numericUpDown_maxPuntos.Value);
                                    p.MaxRondas       = Convert.ToInt32(numericUpDown_maxRondas.Value);

                                    //Envia instruccion de nueva partida con la primera imagen de la pila
                                    EnviarInstruccion(3);
                                }
                            }

                            catch (Exception error)
                            {
                                sw.WriteLine("#NOK#" + error);
                                sw.Flush();
                            }
                        }
                    }
                    #endregion

                    #region com JUGADA
                    if (subdatos[1] == "JUGADA")
                    {
                        lock (key)
                        {
                            if (p.Respuesta == subdatos[2]) //respuesta acertada
                            {
                                j = Jugadores.Find(c => c.Cliente == cli);
                                j.RespuestaAdivinada = true;
                                sw.WriteLine("#OK#correcto");
                                sw.Flush();
                                EnviarInstruccion(8, j.Nick.ToUpper() + " ACERTÓ!");
                            }
                            else
                            {
                                sw.WriteLine("#OK#incorrecto");
                                sw.Flush();
                            }
                        }
                    }
                    #endregion

                    #region com PUNTUACION
                    if (subdatos[1] == "PUNTUACION")
                    {
                        try
                        {
                            j             = Jugadores.Find(c => c.Cliente == cli);
                            j.Puntuacion += Convert.ToInt32(subdatos[2]);
                            sw.WriteLine("#OK#");
                            sw.Flush();
                        }
                        catch (Exception er)
                        {
                            sw.WriteLine("#NOK#" + er);
                            sw.Flush();
                        }
                    }
                    #endregion

                    #region com FIN DE RONDA
                    if (subdatos[1] == "FINDERONDA")
                    {
                        lock (key)
                        {
                            j = Jugadores.Find(c => c.Cliente == cli);
                            j.PartidaFinalizada = true;
                            sw.WriteLine("#OK#faltan " + Jugadores.Where(c => c.PartidaFinalizada == false).ToList().Count + " jugadores#");
                            sw.Flush();
                            EnviarInstruccion(7);
                        }
                    }
                    #endregion

                    #region com CHAT
                    if (subdatos[1] == "MSGCHAT")
                    {
                        EnviarInstruccion(8, subdatos[2]);
                    }
                    #endregion

                    #region comDESCONEXION

                    if (subdatos[1] == "DESCONEXION")
                    {
                        lock (key)
                        {
                            j = Jugadores.Find(c => c.Cliente.Equals(cli));
                            Jugadores.Remove(j);
                            del = new DelegadoEscribirLista(escribirListaClientes);
                            EnviarInstruccion(8, j.Nick.ToUpper() + " SE DESCONECTÓ");
                            del.Invoke();
                            cli.Close();
                        }
                    }
                    #endregion
                }
                catch (Exception error)
                {
                    Console.WriteLine("Errro: {0}", error.ToString());
                    break;
                }
            }
        }
Exemplo n.º 4
0
 public void salirCola(Jugador jugador)
 {
     cola.RemoveAll(x => x.id == jugador.id);
 }
Exemplo n.º 5
0
        private void doChat()
        {
            try
            {
                string dataFromClient = null;

                Byte[] sendBytes      = null;
                string serverResponse = null;

                while (true)
                {
                    // Recibi mensaje
                    byte[]        bytesFrom     = new byte[4];
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    int buffersize = BitConverter.ToInt32(bytesFrom, 0);
                    bytesFrom = new byte[buffersize];
                    networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

                    //Verifico si es un usuario
                    if (dataFromClient.Contains("usuario"))
                    {
                        Jugador jugador = JsonConvert.DeserializeObject <Jugador>(dataFromClient);
                        jugador.setConexion(clientSocket);
                        Partida.setTcpClients(clientSocket);

                        //Depende del mensaje que mande un usuario, el servidor realiza una acción distinta
                        switch (jugador.mensaje)
                        {
                        case 0:
                            System.Console.WriteLine("Jugador " + jugador.usuario + " ha ingresado al servidor");
                            System.Console.WriteLine("Id: " + jugador.id + "/ Nombre: " + jugador.usuario + "/ Puntaje: " + jugador.puntaje + "/ Victorias: " + jugador.calcularPorcentaje() + "%");
                            enviarMensaje("ok");
                            break;

                        case 1:
                            string rival = ListadoCola.getInstancia().entrarCola(jugador);
                            System.Console.WriteLine("Jugador " + jugador.usuario + " ha ingresado a la cola");
                            if (rival != "")
                            {
                                //Se envia al rival y se vuelve a setear la conexion para que no quede en null
                                enviarMensaje(rival);
                                jugador.setConexion(clientSocket);
                            }
                            break;

                        case 2:
                            ListadoCola.getInstancia().salirCola(jugador);
                            System.Console.WriteLine("Jugador " + jugador.usuario + " ha salido de la cola");
                            enviarMensaje("ok");
                            Partida.reiniciarChecks();
                            break;
                        }
                    }
                    else
                    {
                        Partida.interpretarMensaje(dataFromClient, clientSocket);
                        //Mensajes provenientes de la partida
                    }



                    void enviarMensaje(string mensaje)
                    {
                        serverResponse = mensaje;
                        sendBytes      = System.Text.Encoding.ASCII.GetBytes(serverResponse);
                        byte[] intBytes = BitConverter.GetBytes(sendBytes.Length);
                        networkStream.Write(intBytes, 0, intBytes.Length);
                        networkStream.Write(sendBytes, 0, sendBytes.Length);
                        networkStream.Flush();
                    }
                }
            }
            catch (System.IO.IOException)
            {
                Console.WriteLine("Un usuario se ha desconectado");
            }
        }