示例#1
0
        /// <summary>
        /// Atira em uma posição do tabuleiro e retorna o resultado do tiro
        /// </summary>
        /// <param name="x">Coordenada X do tabuleiro onde deve-se dar o tiro</param>
        /// <param name="y">Coordenada Y do tabuleiro onde deve-se dar o tiro</param>
        /// <returns>Um ResultadoDeTiro para o tiro dado</returns>
        /// <exception cref="Exception">Caso o tabuleiro não esteja completo</exception>
        /// <exception cref="IndexOutOfRangeException">Caso alguma das coordenadas esteja fora do mapa</exception>
        public ResultadoDeTiro Atirar(int x, int y)
        {
            if (!EstaCompleto())
            {
                throw new Exception("O tabuleiro não está completo");
            }

            Celula celula = this[y, x];

            // Se não tem nada naquela posição, errou
            if (celula == null)
            {
                return(ResultadoDeTiro.Errou);
            }

            // Se não errou, acertou
            celula.FoiAcertada = true;
            ResultadoDeTiro r = ResultadoDeTiro.Acertou;

            // Verifica se afundou o navio
            Celula atual = celula.PrimeiraDoNavio;
            bool   afundou;

            for (afundou = true; atual != null && afundou; atual = atual.ProximaDoNavio)
            {
                afundou = atual.FoiAcertada;
            }

            if (afundou)
            {
                r |= ResultadoDeTiro.Afundou;
            }

            return(r);
        }
示例#2
0
        /// <summary>
        /// Executa o jogo se comunicando com o par remoto
        /// </summary>
        private void Jogar()
        {
            StreamWriter writer = new StreamWriter(cliente.GetStream());

            writer.AutoFlush = true;

            TirosDados     = new ListaDeTiros();
            TirosRecebidos = new ListaDeTiros();

            StreamReader reader = new StreamReader(cliente.GetStream());

            try
            {
                while (Conectado)
                {
                    // Envia um tiro
                    Tiro tiroDado = EsperarTiro();
                    writer.writeLine("Tiro " + tiroDado.X + "," + tiroDado.Y);

                    // Recebe um tiro do cliente remoto
                    string r;
                    string line;
                    line = reader.ReadLine();

                    int x = Convert.ToInt32(line.Substring(5, line.IndexOf(',') - 5));
                    int y = Convert.ToInt32(line.Substring(line.IndexOf(',') + 1));

                    Tiro recebido = new Tiro(x, y);

                    // Avisa que recebeu o tiro para o cliente local
                    TirosRecebidos.Add(recebido, recebido.Aplicar(Tabuleiro));
                    OnTiroRecebido(recebido);


                    // Envia o resultado do tiro recebido
                    writer.WriteLine(((uint)recebido.Aplicar(Tabuleiro)).ToString());

                    // Recebe o resultado do seu tiro
                    line = reader.ReadLine();

                    // Avisa o cliente do resultado do tiro
                    ResultadoDeTiro resultado = ResultadoDeTiro.Errou;
                    resultado = (ResultadoDeTiro)Convert.ToUInt32(line);
                    TirosDados.Add(tiroDado, resultado);
                    OnResultadoDeTiro(tiroDado, resultado);

                    waitHandle.Reset();
                }
            }
            catch (Exception e)
            {
                Debugger.Log(0, "error", e.Message + Environment.NewLine);
                OnClienteDesconectado((cliente.Client.RemoteEndPoint as IPEndPoint).Address);
            }
        }
示例#3
0
        private void Cliente_OnResultadoDeTiro(Tiro t, ResultadoDeTiro resultado)
        {
            if (resultado == ResultadoDeTiro.Ganhou)
            {
                MessageBox.Show(this, "Você ganhou!", "UHUL :)", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cliente = null;
                PosicionarNavios();
            }

            tInimigo.ResultadoTiro(t, resultado);
        }
        public void ResultadoTiro(Tiro t, ResultadoDeTiro r)
        {
            StatusCelula s = StatusCelula.Agua;

            if (r == ResultadoDeTiro.Acertou || r == ResultadoDeTiro.Afundou)
            {
                s = StatusCelula.Navio;
            }

            celulas[t.X, t.Y] = s;
        }
示例#5
0
 private void Cliente_OnResultadoDeTiro(Tiro t, ResultadoDeTiro resultado)
 {
     Invoke(new Action(() =>
     {
         Console.WriteLine("Atirô");
         tirosDados.Add(new Tiro(tiroX, tiroY), resultado);
         tiroX = tiroY = -1;
         pictureBox1.Invalidate();
         pictureBox2.Invalidate();
         podeAtirar = false;
     }));
 }
示例#6
0
        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            larguraF = (sender as PictureBox).Width / 10F;
            alturaF  = (sender as PictureBox).Height / 10F;

            foreach (KeyValuePair <Tiro, ResultadoDeTiro> tiroDado in tirosDados)
            {
                ResultadoDeTiro tiroRes = tiroDado.Value;
                Image           tiro    = tiroPreto;
                Console.WriteLine("Tirores" + tiroRes);
                switch (tiroRes)
                {
                case ResultadoDeTiro.Errou:
                    tiro = tiroVerde;
                    break;

                case ResultadoDeTiro.Acertou:
                    tiro = tiroVermelho;
                    break;

                case ResultadoDeTiro.Afundou:
                    tiro = tiroPreto;
                    break;

                case ResultadoDeTiro.Ganhou:
                    MessageBox.Show("Ganhou Miserávi");
                    break;

                default:
                    Console.WriteLine(tiroRes + "");
                    break;
                }
                e.Graphics.DrawImage(tiro, tiroDado.Key.X * larguraF, tiroDado.Key.Y * alturaF, larguraF, alturaF);
            }

            for (int i = 1; i < 10; i++)
            {
                e.Graphics.DrawLine(new Pen(Color.Black, 2F), larguraF * i, 0, larguraF * i, (sender as PictureBox).Height - 1);
                e.Graphics.DrawLine(new Pen(Color.Black, 2F), 0, alturaF * i, (sender as PictureBox).Width - 1, alturaF * i);
            }

            if (tiroX != -1)
            {
                e.Graphics.DrawRectangle(new Pen(Color.Aquamarine, 2f), tiroX * larguraF, tiroY * alturaF, larguraF, alturaF);
            }

            if (x2 != -1)
            {
                e.Graphics.DrawImage(miraVermelha, x2 * larguraF, y2 * alturaF, larguraF, alturaF);
            }
        }
示例#7
0
 /// <summary>
 /// Adiciona um elemento na lista
 /// </summary>
 /// <param name="t">Tiro</param>
 /// <param name="r">Resultado do tiro</param>
 internal void Add(Tiro t, ResultadoDeTiro r)
 {
     _tiros.Add(t, r);
 }
示例#8
0
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            larguraF = (sender as PictureBox).Width / 10F;
            alturaF  = (sender as PictureBox).Height / 10F;

            if (navio != default(TipoDeNavio))
            {
                Image img = Image.FromFile(navio.ToString() + ".png");

                if (frmNavios.Direcao == 0)
                {
                    if (10 - navio.Tamanho() < y1)
                    {
                        y1 = 10 - navio.Tamanho();
                    }

                    e.Graphics.DrawImage(img, new RectangleF(larguraF * x1, alturaF * y1, larguraF, alturaF * navio.Tamanho()));
                }
                else
                {
                    if (10 - navio.Tamanho() < x1)
                    {
                        x1 = 10 - navio.Tamanho();
                    }

                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    e.Graphics.DrawImage(img, new RectangleF(larguraF * x1, alturaF * y1, larguraF * navio.Tamanho(), alturaF));
                }
            }

            foreach (KeyValuePair <int[], TipoDeNavio> barco in tabuleiro.Navios)
            {
                if (barco.Key[2] == 0)
                {
                    e.Graphics.DrawImage(Image.FromFile(barco.Value.ToString() + ".png"), new RectangleF(larguraF * barco.Key[0], alturaF * barco.Key[1], larguraF, alturaF * barco.Value.Tamanho()));
                }
                else
                {
                    Image img = Image.FromFile(barco.Value.ToString() + ".png");
                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    e.Graphics.DrawImage(img, new RectangleF(larguraF * barco.Key[0], alturaF * barco.Key[1], larguraF * barco.Value.Tamanho(), alturaF));
                }
            }

            foreach (Tiro tiroRecebido in tirosRecebidos)
            {
                ResultadoDeTiro tiroRes = tabuleiro.Atirar(tiroRecebido.X, tiroRecebido.Y);
                Image           tiro    = tiroPreto;
                switch (tiroRes)
                {
                case ResultadoDeTiro.Errou:
                    tiro = tiroVerde;
                    break;

                case ResultadoDeTiro.Acertou:
                    tiro = tiroVermelho;
                    break;

                case ResultadoDeTiro.Afundou:
                    tiro = tiroPreto;
                    break;
                }
                e.Graphics.DrawImage(tiro, tiroRecebido.X * larguraF, tiroRecebido.Y * alturaF, larguraF, alturaF);
            }

            for (int i = 1; i < 10; i++)
            {
                e.Graphics.DrawLine(new Pen(Color.Black, 2F), larguraF * i, 0, larguraF * i, (sender as PictureBox).Height - 1);
                e.Graphics.DrawLine(new Pen(Color.Black, 2F), 0, alturaF * i, (sender as PictureBox).Width - 1, alturaF * i);
            }

            if (x1 != -1)
            {
                e.Graphics.DrawImage(miraVerde, x1 * larguraF, y1 * alturaF, larguraF, alturaF);
            }
        }
示例#9
0
        /// <summary>
        /// Executa o jogo se comunicando com o par remoto
        /// </summary>
        private void Jogar()
        {
            StreamWriter writer = new StreamWriter(cliente.GetStream());

            writer.AutoFlush = true;

            StreamReader reader = new StreamReader(cliente.GetStream());

            try
            {
                while (Conectado)
                {
                    Debugger.Log(0, "msg", "Sua vez" + Environment.NewLine);
                    OnDarTiro();
                    waitHandle.WaitOne(TIMEOUT_TIRO);

                    if (_tiro == null)
                    {
                        _tiro = new Tiro(rnd.Next(Tabuleiro.NumeroDeColunas), rnd.Next(Tabuleiro.NumeroDeLinhas));
                    }

                    writer.WriteLine("Tiro " + _tiro.X + "," + _tiro.Y);
                    Debugger.Log(0, "msg", "Tiro " + _tiro.X + "," + _tiro.Y + Environment.NewLine);

                    string r        = reader.ReadLine();
                    Tiro   recebido = null;

                    if (r.StartsWith("Tiro "))
                    {
                        int x = Convert.ToInt32(r.Substring(5, r.IndexOf(',') - 5));
                        int y = Convert.ToInt32(r.Substring(r.IndexOf(',') + 1));

                        Debugger.Log(0, "msg", "I '" + r + "'" + Environment.NewLine);
                        recebido = new Tiro(x, y);

                        ResultadoDeTiro resultado = recebido.Aplicar(Tabuleiro);
                        TirosRecebidos.Add(recebido, resultado);
                        Task.Run(() => OnTiroRecebido(recebido));

                        lock (writer)
                            writer.WriteLine(((uint)resultado).ToString());
                    }

                    while (!char.IsNumber(r[0]))
                    {
                        r = reader.ReadLine();
                    }

                    ResultadoDeTiro result = (ResultadoDeTiro)Convert.ToUInt32(r);
                    TirosDados.Add(_tiro, result);
                    Task.Run(() => OnResultadoDeTiro(_tiro, result));

                    _tiro = null;

                    if (recebido == null)
                    {
                        string line;

                        line = reader.ReadLine();
                        Debugger.Log(0, "msg", "I '" + line + "'" + Environment.NewLine);
                        if (line.StartsWith("Tiro "))
                        {
                            int x = Convert.ToInt32(line.Substring(5, line.IndexOf(',') - 5));
                            int y = Convert.ToInt32(line.Substring(line.IndexOf(',') + 1));

                            recebido = new Tiro(x, y);
                            ResultadoDeTiro resultado = recebido.Aplicar(Tabuleiro);
                            TirosRecebidos.Add(recebido, resultado);
                            Task.Run(() => OnTiroRecebido(recebido));

                            lock (writer)
                                writer.WriteLine(((uint)resultado).ToString());
                        }
                    }

                    waitHandle.Reset();
                }
            }
            catch (Exception e)
            {
                Debugger.Log(0, "error", e.Message + Environment.NewLine);
                OnClienteDesconectado((cliente.Client.RemoteEndPoint as IPEndPoint).Address);
            }
        }
 /// <summary>
 /// Obtém o tipo de navio acertado por um tiro
 /// </summary>
 public static TipoDeNavio TipoDeNavio(this ResultadoDeTiro r)
 {
     return((TipoDeNavio)((int)r & 0xffff));
 }