Jump to content
Fórum Script Brasil
  • 0

Duvida campo minado em javaScript


gr3g

Question

Ola galera, iniciando no forum.

Estou com uma duvida nas funções do campo minado em javaScript.

Eu criei uma matriz e uma função para sortear valores dentro dela. Onde -1 é a bomba.

Porem agora estou com dificuldades para criar as dicas, tipo, a casa que tiver uma bomba como vizinha, recebe o valor 1, com duas bombas vizinhas

recebe 2, e assim por diante.

E tambem, não sei como fazer para quando clicado num campo vazio, abrir os campos vazios ao redor daquele clicado.

Se alguém puder ajudar, fico grato.

<script type="text/javascript" language="javascript">
            var matCampoMinado = new Array (4);
            matCampoMinado[0] = [0,0,0,0]
            matCampoMinado[1] = [0,0,0,0]
            matCampoMinado[2] = [0,0,0,0]
            matCampoMinado[3] = [0,0,0,0]
            
            function inicializa()
            {
                resetCampo();
                desenhaTabela();
                
            }
            
            function resetCampo()
            {
                derrota=false;
                vitoria=false;
                campoLivre=100;
                campoCont=0;
                for(i=0;i<4;i++)
                {
                    for(j=0;j<4;j++)
                    {
                        matCampoMinado[i][j] = (Math.floor(Math.random() * 6))-1;//-1 == bomba
                    }
                }

                
            }
            
            function mostraMensagem(text) 
            {
                document.getElementById("status").innerHTML = text;
            }
            
            function desenhaTabela()
            {
                // Converte o array em uma tabela e a insere no DIV #board
                // Note o parametro onclick, que deixa cada celula "clicavel"
                var board = new Array();  

                board.push("<table><tr>");
                for (var i = 0; i < matCampoMinado.length; i++) {
                    if (i != 0) board.push("</tr><tr>");
                    for (var j = 0; j < matCampoMinado[i].length; j++) {
                        board.push(
                            '<td' +
                            '    onMouseOver="cellHover(this)"' +
                            '    onMouseOut="cellOut(this)"' +
                            '    onClick="cellClicked(this)">' +
                            matCampoMinado[i][j] + "</td>"
                        );
                    }
                }
                board.push("</tr></table>"); 
                document.getElementById("board").innerHTML = board.join("\n");
            }
            
            function cellClicked(thisCell) 
            {
                // Detecta se algo importante aconteceu
                if (derrota) 
                {
                    init();
                    setMessage("Tente de novo");
                    return;
                } 
                else if (vitoria) 
                {
                    init();
                    setMessage("Parabéns, você ganhou.");
                    return;
                }
                
                // Se esse quadrado já foi clicado, ignora
                if (thisCell.className == "clicked") return;

                // No CSS a classe "clicked" usa outras cores, revelando o numero
                thisCell.className = "clicked";

                switch (thisCell.innerHTML) {
                    // Pinta cada numero de uma cor
                    case "1": thisCell.style.color = "#070"; break;
                    case "2": thisCell.style.color = "#00b"; break;
                    case "3": thisCell.style.color = "#c00"; break;
                    // Bomba!
                    case "-1":
                        thisCell.innerHTML = '*';
                        derrota = true;
                        mostraMensagem("BOOOOOOM");
                        return;
                }
                campoCont++;

                if (campoCont == campoLivre) { // achou todos os quadrados livres
                    vitoria = true;
                    mostraMensagem("PARABENS, voce ganhou!!");
                } else {
                    mostraMensagem("Faltam: " + (safeMax-safeCount));
                }
            }
            // Podia ter usado :hover, mas a ideia é estressar o javascript
            // só faz o highlight nos quadrados virgens
            function cellHover(thisCell) 
            {
                if (!thisCell.className) {
                    thisCell.style.border = "2px solid yellow";
                }
            }
            
            function cellOut(thisCell) 
            {
                if (thisCell.className == "clicked") {
                    thisCell.style.border = "2px solid #ccc";
                } else {
                    thisCell.style.border = "2px outset gray";
                }
            }
        </script>

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Andei analisando, mudei meu código, consegui sortear as bombas de forma correta, porem não consigo checar quantas vizinhas elas tem.

O problema está na function checaVizinhas(). Se alguém puder me ajudar...

&lt;script type="text/javascript" language="javascript">
            var matCampoMinado = new Array ();
            matCampoMinado[0] = [0,0,0,0]
            matCampoMinado[1] = [0,0,0,0]
            matCampoMinado[2] = [0,0,0,0]
            matCampoMinado[3] = [0,0,0,0]
            
            function inicializa()
            {
                sortBomba();
                checaVizinhas();
                desenhaTabela();
                
            }
            
            function sortBomba()
            {
                derrota=false;
                vitoria=false;
                for(x=0;x<4;x++)
                {
                    i=Math.floor(Math.random()*4);
                    j=Math.floor(Math.random()*4);
                    if(matCampoMinado[i][j]==0)
                    {
                        matCampoMinado[i][j]=-1;
                    }
                    else
                    {
                        i=Math.floor(Math.random()*4);
                        j=Math.floor(Math.random()*4);
                    }
                }
            }
            
            function checaVizinhas()
            {
                var a=0;
                for(i=0;i<4;i++)
                {
                    for(j=0;j<4;j++)
                    {
                        if(matCampoMinado[i][j]!= -1)
                        {
                            if(matCampoMinado[i+1][j]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i+1][j+1]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i][j+1]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i-1][j+1]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i-1][j]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i-1][j-1]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i][j-1]==-1)
                            {
                                a++;
                            }
                            if(matCampoMinado[i+1][j-1]==-1)
                            {
                                a++;
                            }
                            matCampoMinado[i][j]=a;
                            a=0;
                        }
                    }
                }
            }
            
            function mostraMensagem(text) 
            {
                document.getElementById("status").innerHTML = text;
            }
            
            function desenhaTabela()
            {
                // Converte o array em uma tabela e a insere no DIV #board
                // Note o parametro onclick, que deixa cada celula "clicavel"
                var board = new Array();  

                board.push("<table><tr>");
                for (var i = 0; i < matCampoMinado.length; i++) {
                    if (i != 0) board.push("</tr><tr>");
                    for (var j = 0; j < matCampoMinado[i].length; j++) {
                        board.push(
                            '<td' +
                            '    onMouseOver="cellHover(this)"' +
                            '    onMouseOut="cellOut(this)"' +
                            '    onClick="cellClicked(this)">' +
                            matCampoMinado[i][j] + "</td>"
                        );
                    }
                }
                board.push("</tr></table>"); 
                document.getElementById("board").innerHTML = board.join("\n");
            }
            
            function cellClicked(thisCell) 
            {
                // Detecta se algo importante aconteceu
                if (derrota) 
                {
                    init();
                    setMessage("Tente de novo");
                    return;
                } 
                else if (vitoria) 
                {
                    init();
                    setMessage("Parabéns, você ganhou.");
                    return;
                }
                
                // Se esse quadrado já foi clicado, ignora
                if (thisCell.className == "clicked") return;

                // No CSS a classe "clicked" usa outras cores, revelando o numero
                thisCell.className = "clicked";

                switch (thisCell.innerHTML) {
                    // Pinta cada numero de uma cor
                    case "1": thisCell.style.color = "#070"; break;
                    case "2": thisCell.style.color = "#00b"; break;
                    case "3": thisCell.style.color = "#c00"; break;
                    // Bomba!
                    case "-1":
                        thisCell.innerHTML = '*';
                        derrota = true;
                        mostraMensagem("BOOOOOOM");
                        return;
                }
                campoCont++;

                if (campoCont == campoLivre) { // achou todos os quadrados livres
                    vitoria = true;
                    mostraMensagem("PARABENS, voce ganhou!!");
                } else {
                    mostraMensagem("Faltam: " + (safeMax-safeCount));
                }
            }
            // Podia ter usado :hover, mas a ideia é estressar o javascript
            // só faz o highlight nos quadrados virgens
            function cellHover(thisCell) 
            {
                if (!thisCell.className) {
                    thisCell.style.border = "2px solid yellow";
                }
            }
            
            function cellOut(thisCell) 
            {
                if (thisCell.className == "clicked") {
                    thisCell.style.border = "2px solid #ccc";
                } else {
                    thisCell.style.border = "2px outset gray";
                }
            }
        </script>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...