Mine game : Game « Page Components « JavaScript DHTML

JavaScript DHTML
1. Ajax Layer
2. Data Type
3. Date Time
4. Development
5. Document
6. Event
7. Event onMethod
8. Form Control
9. GUI Components
10. HTML
11. Javascript Collections
12. Javascript Objects
13. Language Basics
14. Node Operation
15. Object Oriented
16. Page Components
17. Security
18. Style Layout
19. Table
20. Utilities
21. Window Browser
Microsoft Office Word 2007 Tutorial
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
JavaScript DHTML » Page Components » Game 
Mine game


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Buscayasminas &copy; (by Joan Alba Maldonado)</title>
        <!-- (cBuscayasminas - Programa realizado por Joan Alba Maldonado (granvino@granvino.com). Prohibido publicar, reproducir o modificar sin citar expresamente al autor original. -->
        <script language="JavaScript1.2" type="text/javascript">
            <!--
                //(c) Buscayasminas - Programa realizado por Joan Alba Maldonado (granvino@granvino.com). Prohibido publicar, reproducir o modificar sin citar expresamente al autor original.

                
                //Ancho del mapa:
                var mapa_width = 9;
                var mapa_width_maximo = 30//Ancho maximo del mapa que puede ponerse.
                //Alto del mapa:
                var mapa_height = 9;
                var mapa_height_maximo = 30//Alto maximo del mapa que puede ponerse.

                //Ancho y alto de las celdas:
                var celda_width = 20;
                var celda_height = 20;

                //Numero de minas:
                var numero_minas = 10;
                //Numero de banderas:
                var numero_banderas = numero_minas;
                
                //Matriz con las minas:
                var matriz_minas = new Array(mapa_width*mapa_height);
                //Matriz con los numeros:
                var matriz_numeros = new Array(mapa_width*mapa_height);
                //Matriz del usuario (para saber que casillas ha descubierto, que banderas ha puesto, etc):
                var matriz_usuario = new Array(mapa_width*mapa_height);

                //Variable que determina la opcion seleccionada:
                var opcion_seleccionada = false;
                
                //Variable para saber si se tiene que arrastrar el menu opciones o no:
                var arrastrar_opciones = false;                
                //Variables que calcularan la diferencia entre las coordenadas del mouse y las del div de opciones:
                var diferencia_posicion_horizontal = false;
                var diferencia_posicion_vertical = false;
                //Variable para saber si se esta arrastrando en un campo seleccionable, y asi no dejar arrastrar:
                var campo_seleccionable = false;

                //Variable para saber si el juego ha finalizado (ya por haber ganado o por haber perdido):
                var se_ha_acabado_juego = false;
                
                //Variable para saber si se han cambiado las banderas despues de haber apretado la tecla alt, control o shift:
                var se_ha_modificado_bandera = false;
                
                //Variable para saber si una tecla se ha levantado o no:
                var tecla_levantada = true;
                
                //Matriz que define de que color saldra cada numero (del 0, que no se usa, al 8):
                var color_numeros = new Array("#ff0000""#00ff00""#00aaff""#ffff00""#aaffcc""#aabbff""#ffffff""#ddaaff""#ffddbb");

                //Variable que guarda el contenido del div de la cara de la yasmina, para hacer el if de no cambiarlo si esta como al principio:
                var div_cara_yasmina_inicial = false;

                //Variable para saber si se ha iniciado el contador de tiempo:
                var iniciado_temporizador = false;
                //Variable donde se guardara el setInterval del tiempo:
                var tiempo = false;
                //Variables que guardan los segundos y los minutos, respectivamente, del temporizador:
                var segundos = 0;

                //Variable que define si hay tiempo limite:
                var hay_tiempo_limite = true;
                //Variable que define cuanto tiempo limite hay:
                var tiempo_limite = 9999;
                
                
                //Funcion que muestra un mensaje en pantalla:
                function mostrar_mensaje(mensaje)
                 {
                    //Se pone el mensaje en el div:
                    document.getElementById("mensaje").innerHTML = mensaje;

                    //Si se ha enviado un mensaje:
                    if (mensaje != "")
                     {
                        //Se muestra el div:
                        document.getElementById("mensaje").style.visibility = "visible";
                     }
                    //...y si no:
                    else
                     {
                        //Se oculta el div:
                        document.getElementById("mensaje").style.visibility = "hidden";                        
                     }
                 }
                
                
                //Funcion que muestra u oculta el menu de opciones:
                function mostrar_ocultar_opciones()
                 {
                    //Se ponen las opciones pertinentes:
                    document.getElementById("numero_minas").value = numero_minas;
                    document.getElementById("mapa_width").value = mapa_width;
                    document.getElementById("mapa_height").value = mapa_height;
                    document.getElementById("tiempo_limite_input").value = tiempo_limite;
                    if (hay_tiempo_limite)
                     {
                        //Se chequea el checkbox conforme hay tiempo limite:
                        document.getElementById("hay_tiempo_limite_input").checked = true;
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = false;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#333333";
                        document.getElementById("tiempo_limite_input").style.background = "#99bbff";
                     }
                    else
                     {
                        //Se deschequea el checkbox conforme no hay tiempo limite:
                        document.getElementById("hay_tiempo_limite_input").checked = false;
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = true;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#3333dd";
                        document.getElementById("tiempo_limite_input").style.background = "#999999";
                     }
                    
                    //Si esta oculto, lo muestra:
                    if (document.getElementById("menu_opciones").style.visibility == "hidden") { document.getElementById("menu_opciones").style.visibility = "visible"; document.getElementById("opcion_opciones").title = "Close options"}
                    //...y si no, lo oculta:
                    else document.getElementById("menu_opciones").style.visibility = "hidden"; document.getElementById("opcion_opciones").title = "Edit options"}
                 }

                
                //Funcion que activa o desactiva el tiempo limite:
                function activar_desactivar_tiempo_limite()
                 {
                    //Si el tiempo limite esta desactivado, se activa:
                    if (document.getElementById("hay_tiempo_limite_input").checked == true)
                     {
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = false;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#333333";
                        document.getElementById("tiempo_limite_input").style.background = "#99bbff";
                     }
                    //...pero si ya esta activado, se desactiva:
                    else
                     {
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = true;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#3333dd";
                        document.getElementById("tiempo_limite_input").style.background = "#999999";
                     }
                 }


                //Funcion que aplica las opciones elegidas:
                function aplicar_opciones()
                 {
                    //Se guarda en variables las opciones enviadas:
                    var numero_minas_enviado = parseInt(document.getElementById("numero_minas").value);
                    var mapa_width_enviado = parseInt(document.getElementById("mapa_width").value);
                    var mapa_height_enviado = parseInt(document.getElementById("mapa_height").value);
                    var numero_minas_maximo_enviado = (mapa_width_enviado*mapa_height_enviado1;
                    var tiempo_limite_enviado = parseInt(document.getElementById("tiempo_limite_input").value);
                    
                    //Si las opciones siguen siendo iguales a las que hay actualmente, sale de la funcion:
                    if (numero_minas_enviado == numero_minas && mapa_width_enviado == mapa_width && mapa_height_enviado == mapa_height)
                     {
                        //Si se ha seteado conforme hay limite de tiempo, pero se ha enviado el mismo que ya habia, sale de la funcion:
                        if (hay_tiempo_limite && document.getElementById("hay_tiempo_limite_input").checked == true && tiempo_limite_enviado == tiempo_limite) { return}
                        //...o si no se ha enviado conforme hay limite de tiempo, tambien sale:
                        else if (!hay_tiempo_limite && document.getElementById("hay_tiempo_limite_input").checked == false) { return}
                     }
                    
                    
                    //Variable que guarda los errores, si se generan:
                    var errores = "";
                    //Variable para saber que hay que restaurar, en caso de ser erroneo:
                    var restaurar_numero_minas = false;
                    var restaurar_mapa_width = false;
                    var restaurar_mapa_height = false;
                    var restaurar_tiempo_limite = false;
                    //Calcular errores cometidos (opciones invalidas):
                    if (mapa_width_enviado == && mapa_height_enviado == 1) { errores += "\n* Map must be more than one cell (it can't be 1x1)."; restaurar_mapa_width = true; restaurar_mapa_height = true}
                    if (mapa_width_enviado > mapa_width_maximo || mapa_width_enviado < || isNaN(mapa_width_enviado)) { errores += "\n* Map width must be a number between 1 and "+mapa_width_maximo+"."; restaurar_mapa_width = true}
                    if (mapa_height_enviado > mapa_height_maximo || mapa_height_enviado < || isNaN(mapa_height_enviado)) { errores += "\n* Map height must be a number between 1 and "+mapa_height_maximo+"."; restaurar_mapa_height = true}
                    if (numero_minas_enviado > numero_minas_maximo_enviado || numero_minas_enviado < || isNaN(numero_minas_enviado)) { errores += "\n* Number of mines must be a number between 1 and result of operation: map height x map width - 1."; restaurar_numero_minas = true}
                    if (document.getElementById("hay_tiempo_limite_input").checked == true && tiempo_limite_enviado > 9999 || tiempo_limite_enviado < 10 || isNaN(tiempo_limite_enviado)) { errores += "\n* Time limit must be between 10 and 9999 seconds."; restaurar_tiempo_limite = true}
                    //Si se ha cometido algun error de opcion no valida:
                    if (errores != "")
                     {
                        //Alerta sobre el error:
                        alert("Options are wrong.\nProblems:"+errores);
                        //Vuelve a poner todo como estaba antes (siempre que se haya determinado por ser erroneo):
                        if (restaurar_numero_minas) { document.getElementById("numero_minas").value = numero_minas; }
                        if (restaurar_mapa_width) { document.getElementById("mapa_width").value = mapa_width; }
                        if (restaurar_mapa_height) { document.getElementById("mapa_height").value = mapa_height; }
                        if (restaurar_tiempo_limite) { document.getElementById("tiempo_limite_input").value = tiempo_limite; }
                        //Sale de la funcion:
                        return;
                     }
                    //...pero si no ha habido ningun error, se aplican las opciones (con confirmacion):
                    else
                     {
                        //Pide confirmacion, y si se cancela restaura los valores y sale de la funcion:
                        if (!confirm("Press ok to apply options. Actual game will be lost."))
                         {
                            //Restaura los valores anteriores:
                            document.getElementById("numero_minas").value = numero_minas;
                            document.getElementById("mapa_width").value = mapa_width;
                            document.getElementById("mapa_height").value = mapa_height;
                            //Sale de la funcion:
                            return;
                         }
                        //...y si no, aplica las opciones:
                        else
                         {
                            //Aplica las opciones:
                            numero_minas = parseInt(document.getElementById("numero_minas").value);
                            mapa_width = parseInt(document.getElementById("mapa_width").value);
                            mapa_height = parseInt(document.getElementById("mapa_height").value);
                            tiempo_limite = parseInt(document.getElementById("tiempo_limite_input").value);
                            if (document.getElementById("hay_tiempo_limite_input").checked == true) { hay_tiempo_limite = true; iniciado_temporizador = false}
                            else hay_tiempo_limite = false}

                            //Se pone el mensaje de espera:
                            mostrar_mensaje("Loading...");
                            
                            //Inicia el juego con las nuevas opciones y se quita el mensaje de espera, despues de unos milisegundos:
                            setTimeout("iniciar_juego(); mostrar_mensaje('');"10);
                         }
                     }
                    
                 }


                //Funcion que selecciona una opcion (poner bandera, etc):
                function seleccionar_opcion(opcion, nombre_div)
                 {
                    //Se pone como opcion seleccionada la enviada:
                    opcion_seleccionada = opcion;
                    //Quita el borde solido a todos los div de opciones:
                    document.getElementById("bandera").style.border = ""//Se borran primero para que el Opera 7.54 no de errores de redraw (y quiza otras versiones).
                    document.getElementById("bandera_no").style.border = ""//Se borran primero para que el Opera 7.54 no de errores de redraw (y quiza otras versiones).
                    document.getElementById("bandera").style.border = "2px #bbbbbb dotted";
                    document.getElementById("bandera_no").style.border = "2px #bbbbbb dotted";
                    //Pone un borde al div de la opcion seleccionada:
                    document.getElementById(nombre_div).style.border = "2px #ffff00 solid";
                    //Se setea conforme se han modificado las opciones de bandera:
                    se_ha_modificado_bandera = true;
                    //Se setea conforme la tecla se ha levantado:
                    tecla_levantada = true;
                 }


                //Funcion que reinicia el juego:
                function reiniciar_juego()
                 {
                    //Se pone el mensaje de espera:
                    mostrar_mensaje("Loading...");
                            
                    //Inicia el juego con las nuevas opciones y se quita el mensaje de espera, despues de unos milisegundos:
                    setTimeout("iniciar_juego(); mostrar_mensaje('');"10);
                 }

                
                //Funcion que inicia el juego por primera vez:
                function iniciar_juego_primera_vez()
                 {
                    //Muestra el mensaje de cargando:
                    mostrar_mensaje("Loading...");
                    //Pone en el input text del tiempo limite, el tiempo limite:
                    document.getElementById("tiempo_limite_input").value = tiempo_limite;
                    //Si no hay tiempo limite, desactiva la opcion de tiempo limite:
                    if (!hay_tiempo_limite)
                     {
                        //Se deschequea el checkbox de tiempo limite:
                        document.getElementById("hay_tiempo_limite_input").checked = false;
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = true;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#3333dd";
                        document.getElementById("tiempo_limite_input").style.background = "#999999";
                     }
                    //...pero si hay tiempo limite, activa la opcion de tiempo limite:
                    else
                     {
                        //Se chequea el checkbox de tiempo limite:
                        document.getElementById("hay_tiempo_limite_input").checked = true;
                        //Se desbloquea el input text con el limite de tiempo:
                        document.getElementById("tiempo_limite_input").disabled = false;
                        //Se vuelve a poner un color de fondo y de texto normal:
                        document.getElementById("tiempo_limite_input").style.color = "#333333";
                        document.getElementById("tiempo_limite_input").style.background = "#99bbff";
                     
                    //Se pone la opcion de mostrar/ocultar el menu de opciones:
                    document.getElementById("menu").innerHTML += '<div id="opcion_opciones" style="left:130px; top:26px; width:60px; height:11px; position:absolute; border:0px; padding:0px; background:transparent; color:#ffffff; text-align:center; line-height:11px; text-decoration:underline; font-family:arial; font-size:11px; cursor: pointer; cursor: hand; z-index:3;" title="Edit options" onClick="javascript:mostrar_ocultar_opciones();" onMouseOver="javascript:document.getElementById(\'opcion_opciones\').style.color=\'#ffff00\';" onMouseOut="javascript:document.getElementById(\'opcion_opciones\').style.color=\'#ffffff\';">opciones</div>';
                    //Inicia el juego despues de unos milisegundos, y luego quita el mensaje de cargando:
                    setTimeout("iniciar_juego(); mostrar_mensaje('');"10);                 
                 }
                                 
                 
                //Funcion que inicia el juego:
                function iniciar_juego()
                 {
                    //Se pone conforme el juego aun no se ha cabado:
                    se_ha_acabado_juego = false;

                    //Pone como valores del input text del formulario de opciones las opciones definidas:
                    document.getElementById("numero_minas").value = numero_minas;
                    document.getElementById("mapa_width").value = mapa_width;
                    document.getElementById("mapa_height").value = mapa_height;

                    //Se ponen tantas banderas como numero de minas:
                    numero_banderas = numero_minas;
                    //Se representan en el contador:
                    document.getElementById("contador_banderas").innerHTML = numero_banderas;

                    //Se pone el contador de tiempo a cero:
                    iniciar_temporizador(false);
                    document.getElementById("tiempo").innerHTML = 0;
                    
                    //Se vuelve a poner la cara normal a la yasmina:
                    document.getElementById("yasmina").innerHTML = '<img src="img/yasmina.gif" alt="New game" title="New game" height="30" width="30" hspace="0" vspace="0" align="center">';

                    //Se guarda el contenido del div de la cara de la yasmina, siempre que no se haya hecho antes:
                    if (!div_cara_yasmina_inicial) { div_cara_yasmina_inicial = document.getElementById("yasmina").innerHTML; }

                    //Prepara el mapa:
                    preparar_mapa();
                    
                    //Representa el mapa:
                    dibujar_mapa();
                 }

                
                //Funcion que prepara el mapa:
                function preparar_mapa()
                 {
                    //Se crean o vuelven a resizear la matriz de minas con el ancho correspondiente y vaciandola:
                    matriz_minas = new Array(mapa_width*mapa_height);
                    for (x=0; x<matriz_minas.length; x++) { matriz_minas[x0}
                                        
                    //Se ponen aleatoriamente las minas en la matriz de minas (tantas como sean necesarias):
                    var minas_puestas = 0;
                    var posicion_aleatoria = 0;
                    while (minas_puestas != numero_minas)
                     {
                        //Se calcula una posicion aleatoria para la mina:
                        posicion_aleatoria = parseInt(Math.random() (mapa_width * mapa_height));
                        //Si la posicion esta desocupada, se pone la mina:
                        if (matriz_minas[posicion_aleatoria== 0) { matriz_minas[posicion_aleatoria1; minas_puestas++; }
                     }

                    //Adecua la matriz de numeros segun la matriz de minas:
                    crear_matriz_numeros();
                    
                    //Se crea la matriz del usuario:
                    matriz_usuario = new Array(mapa_width*mapa_height);
                    for (x=0; x<matriz_usuario.length; x++) { matriz_usuario[x0}
                 }
                

                //Funcion que crea la matriz de numeros:
                function crear_matriz_numeros()
                 {
                    //Se crean o vuelven a resizear la matriz de minas con el ancho correspondiente y vaciandola:
                    matriz_numeros = new Array(mapa_width*mapa_height);
                    for (x=0; x<matriz_numeros.length; x++) { matriz_numeros[x0}
                    
                    //Se adecua segun sea la matriz de minas (si hay mina = X, si no hay alrededor = 0):
                    var contador_minas = 0//Contador de minas circundantes a cada celda.
                    var numero_columna = 1//Contador de la columna en la que se esta.
                    for (x=0; x<matriz_numeros.length; x++)
                     {
                        //Si el contador de columnas es mayor a las columnas del mapa, lo vuelve a 1:
                        if (numero_columna > mapa_width) { numero_columna = 1}
                        
                        //Si hay una mina, se setea como X:
                        if (matriz_minas[x== 1) { matriz_numeros[x"X"