elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Mensajes
Páginas: [1]
1  Programación / Java / ayuda con recursividad juego de adivinar animales en: 1 Abril 2019, 18:30 pm
hola que tal estoy haciendo un juego de adivinar animales pero necesito hacerlo recursivo pero no tengo idea de como aplicar la recursion
aquí les comparto el código 

Código
  1. package evidencia;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;
  9. import java.io.Serializable;
  10.  
  11.  
  12. public class Juego implements Serializable {
  13.  
  14.  
  15.    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
  16.  
  17.        FileInputStream Fi = new FileInputStream("respuestas.txt");
  18.        ObjectInputStream in = new ObjectInputStream(Fi);
  19.        Memoria memory = (Memoria)in.readObject();
  20.        memory.iniciar("vaca");
  21.  
  22.        FileOutputStream out = new FileOutputStream("respuestas.txt");
  23.        ObjectOutputStream os = new ObjectOutputStream(out);
  24.        os.writeObject(memory);
  25.  
  26.  
  27.    }
  28.  
  29. }
  30.  

Código
  1. package evidencia;
  2.  
  3. import java.io.Serializable;
  4.  
  5.  
  6. public class Arbol<E> implements Serializable {
  7.    public Arbol izquierda;
  8.    public Arbol derecha;
  9.    public E carga;
  10.  
  11.    public Arbol() {
  12.    }
  13.  
  14.  
  15.    public Arbol(Arbol izquierda,Arbol derecha, E carga){
  16.        this.izquierda = izquierda;
  17.        this.derecha = derecha;
  18.        this.carga = carga;
  19.    }
  20.    public Arbol(E cargar){
  21.        this.izquierda = null;
  22.        this.derecha = null;
  23.        this.carga = cargar;
  24.    }
  25.    @Override
  26.    public String toString(){
  27.        return carga.toString();
  28.    }
  29. }
  30.  
  31.  

Código
  1. package evidencia;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.Serializable;
  7.  
  8.  
  9.  
  10. public class Memoria implements Serializable {
  11.    private Arbol raiz;
  12.    static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
  13.  
  14.    public boolean si(String pregunta) throws IOException{
  15.        System.out.println(pregunta);
  16.  
  17.        String respuesta = sc.readLine();
  18.  
  19.        return "si".equals(respuesta.toLowerCase());
  20.    }
  21.  
  22.    public void iniciar(String firstAnimal) throws IOException{
  23.        boolean bucle = true;
  24.        if(raiz == null){
  25.        raiz = new Arbol(firstAnimal);
  26.        }
  27.        while(bucle){
  28.            if (!si("¿Estas pensando en un Animal?")) {
  29.                break;
  30.            }
  31.            Arbol arbol = raiz;
  32.            while(arbol.izquierda !=null){
  33.                if (si(arbol.carga+"?")) {
  34.                    arbol = arbol.izquierda;
  35.                }else{
  36.                    arbol = arbol.derecha;
  37.                }
  38.            }
  39.            String animal = (String) arbol.carga;
  40.            if (si("Es un "+animal+"?")) {
  41.                System.out.println("Adivine!!");
  42.                continue;
  43.            }
  44.            if(arbol.derecha == null){
  45.            System.out.println("¿Que animal era?");
  46.            String nuevo = sc.readLine();
  47.            System.out.println("que diferencia a un(a) " +animal+ " de un "+nuevo+"?");
  48.            String info = sc.readLine();
  49.            String indicador = "Si el animal fuera un(a) "+animal+" cual seria la respuesta";
  50.            arbol.carga = info;
  51.  
  52.            if (si(indicador)) {
  53.                arbol.izquierda = new Arbol(animal);
  54.                arbol.derecha = new Arbol(nuevo);
  55.            }else{
  56.                arbol.derecha = new Arbol(animal);
  57.                arbol.izquierda = new Arbol(nuevo);
  58.            }
  59.            }else{
  60.                System.out.println(arbol.derecha);
  61.            }
  62.        }
  63.    }
  64. }
  65.  
2  Programación / PHP / ordenar tabla en: 2 Marzo 2019, 02:08 am
hola que tal tengo una pequeña duda tengo una base de datos y en el programa hago que se muestre la tabla pero me gustaria añadirle un boton para ordenarlo segun id, genero y usuario pero la verdad no se como hacerlo llevo buscando soluciones y no se me ocurre nada :c aqui les adjunto el codigo
Código
  1.  
  2. <?php
  3.  
  4. $conexion=mysqli_connect('localhost','root','','actividad 7');
  5.  
  6. ?>
  7.  
  8.  
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>mostrar datos</title>
  13. </head>
  14. <body>
  15.  
  16. <br>
  17.  
  18. <table border="1" >
  19. <tr>
  20. <td>id</td>
  21. <td>genero</td>
  22. <td>nombre</td>
  23. <td>color</td>
  24. <td>comida</td>
  25. </tr>
  26.  
  27. <?php
  28. $sql="SELECT * from personas";
  29. $result=mysqli_query($conexion,$sql);
  30.  
  31. while($mostrar=mysqli_fetch_array($result)){
  32. ?>
  33.  
  34. <tr>
  35. <td><?php echo $mostrar['id'] ?></td>
  36. <td><?php echo $mostrar['genero'] ?></td>
  37. <td><?php echo $mostrar['nombre'] ?></td>
  38. <td><?php echo $mostrar['color'] ?></td>
  39. <td><?php echo $mostrar['comida'] ?></td>
  40. </tr>
  41. <?php
  42. }
  43. ?>
  44.                <?php
  45.  
  46.  
  47.                ?>
  48. </table>
  49.  
  50. </body>
  51. </html>
  52.  
3  Programación / Java / Re: invertir cola en: 13 Febrero 2019, 19:35 pm
amigo probe lo que me dices cree una clase llamada stack con sus metodos pero me sigue saliendo los mismos datos iguales

aqui esta el codigo
Código
  1. package clientqueue;
  2. import java.util.logging.Level;  
  3. import java.util.logging.Logger;
  4.  
  5.  
  6.  
  7. public class ClientQueue {
  8.    public static void main(String[] args) {
  9.        Queue<String> myQueue = new Queue();
  10.        myQueue.push("Jesus");
  11.        myQueue.push("Alberto");
  12.        myQueue.push("Enrique");
  13.        myQueue.push("Isma");
  14.        myQueue.push("Alexis");
  15.        System.out.println(myQueue);
  16.  
  17.        try {
  18.            myQueue.pop();
  19.        } catch (Exception ex) {
  20.            Logger.getLogger(ClientQueue.class.getName()).log(Level.SEVERE, null, ex);
  21.        }        
  22.        System.out.println(myQueue);    
  23.  
  24.        System.out.println("cola invertida: ");
  25.        myQueue.invert();
  26.        System.out.println(myQueue);
  27.  
  28.  
  29.    }    
  30.  
  31.  
  32. }

Código
  1. package clientqueue;
  2.  
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5.  
  6.  
  7. public class Queue<E> {
  8.      public static final int CAPACITY  =100000;
  9.      private E[] data;
  10.      private int size=0;
  11.  
  12.      public Queue() {
  13.         this.data  = (E[])new Object[this.CAPACITY];
  14.      }
  15.  
  16.      public boolean isEmpty(){        
  17.         return (this.size==0);
  18.      }
  19.  
  20.      public int size(){
  21.  
  22.         return (this.size);
  23.    }
  24.  
  25.      public void push(E value){
  26.        this.data[this.size] = value;
  27.        this.size++;
  28.    }
  29.  
  30.      public E pop() throws Exception{
  31.        E result=null;
  32.        if (this.isEmpty()){
  33.            throw new Exception("La cola está vacía");
  34.    }
  35.        result = this.data[0];
  36.  
  37.      for (int i=0;i<this.size-1;i++){
  38.            data[i]=data[i+1];            
  39.        }
  40.        this.data[this.size]= null;
  41.        this.size--;        
  42.        return result;
  43.  
  44.      }
  45.      public E peek() throws Exception{
  46.  
  47.        E result=null;
  48.        if (this.isEmpty()){
  49.            throw new Exception("La Cola está vacía");
  50.        }
  51.        result = this.data[0];
  52.        return result;
  53.    }
  54.     public E peekLast() throws Exception{
  55.  
  56.        E result=null;
  57.        if (this.isEmpty()){
  58.            throw new Exception("La Cola está vacía");
  59.        }
  60.        result = this.data[size-1];
  61.        return result;
  62.    }
  63.  
  64.     @Override
  65.    public String toString()
  66.    {
  67.        String result = " ";
  68.  
  69.        for (int i= size-1; i >= 0; i--)
  70.        {
  71.            result += this.data[i] + " " ;
  72.        }
  73.  
  74.        return result;
  75.    }
  76.    public  void invert(){
  77.        Stack aux = new Stack();
  78.        Queue result = new Queue();
  79.        while(!result.isEmpty()){
  80.            try {
  81.                aux.push(result.peek());
  82.                result.pop();
  83.            } catch (Exception ex) {
  84.                Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
  85.            }
  86.        }
  87.        while(!aux.isEmpty()){
  88.            try {
  89.                result.push(aux.peek());
  90.                aux.pop();
  91.            } catch (Exception ex) {
  92.                Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
  93.            }
  94.        }
  95.  
  96.  
  97.    }
  98. }

Código
  1. package clientqueue;
  2.  
  3.  
  4. public class Stack<E> {
  5.    public static final int CAPACITY  =100000;
  6.      private E[] data;
  7.      private int size=0;
  8.      public Stack() {
  9.         this.data  = (E[])new Object[this.CAPACITY];
  10.    }
  11.  
  12.       public boolean isEmpty(){        
  13.         return  (this.size==0);
  14.      }
  15.  
  16.       public int size(){
  17.         return  (this.size);
  18.      }
  19.       public void push(E value){
  20.      this.data[this.size] = value;
  21.      this.size++;
  22.      }
  23.        public E  pop() throws Exception{
  24.        E  result = null;
  25.        if (this.isEmpty()){
  26.          throw  new Exception("La  Pila está vacía");
  27.        }
  28.        this.size--;
  29.        result = this.data[this.size];
  30.        this.data[this.size]= null;
  31.        return result;
  32.    }
  33.       public E  peek() throws Exception{
  34.        E  result = null;
  35.        if (this.isEmpty()){
  36.            throw  new Exception("La  Pila está vacía");
  37.        }
  38.        result = this.data[this.size];
  39.        return result;
  40.    }
  41.  
  42.  
  43.  
  44.  
  45. }
  46.  
4  Programación / Java / invertir cola en: 13 Febrero 2019, 17:23 pm
hola que tal cree una cola con los métodos básicos de agregar eliminar y mostrar los elementos de la cola pero me gustaría saber como podría invertir los datos de este

eh buscado en varios post acerca de como invertir una cola pero no eh podido solucionar mi problema me gustaría saber si me pueden ayudar

aquí les adjunto el código  
Código
  1. package clientqueue;
  2.  
  3.  
  4. public class Queue<E> {
  5.      public static final int CAPACITY  =100000;
  6.      private E[] data;
  7.      private int size=0;
  8.  
  9.      public Queue() {
  10.         this.data  = (E[])new Object[this.CAPACITY];
  11.      }
  12.  
  13.      public boolean isEmpty(){        
  14.         return (this.size==0);
  15.      }
  16.  
  17.      public int size(){
  18.  
  19.         return (this.size);
  20.    }
  21.  
  22.      public void push(E value){
  23.        this.data[this.size] = value;
  24.        this.size++;
  25.    }
  26.  
  27.      public E pop() throws Exception{
  28.        E result=null;
  29.        if (this.isEmpty()){
  30.            throw new Exception("La cola está vacía");
  31.    }
  32.        result = this.data[0];
  33.  
  34.      for (int i=0;i<this.size-1;i++){
  35.            data[i]=data[i+1];            
  36.        }
  37.        this.data[this.size]= null;
  38.        this.size--;        
  39.        return result;
  40.  
  41.      }
  42.      public E peek() throws Exception{
  43.  
  44.        E result=null;
  45.        if (this.isEmpty()){
  46.            throw new Exception("La Cola está vacía");
  47.        }
  48.        result = this.data[0];
  49.        return result;
  50.    }
  51.     public E peekLast() throws Exception{
  52.  
  53.        E result=null;
  54.        if (this.isEmpty()){
  55.            throw new Exception("La Cola está vacía");
  56.        }
  57.        result = this.data[size-1];
  58.        return result;
  59.    }
  60.  
  61.     @Override
  62.    public String toString()
  63.    {
  64.        String result = " ";
  65.  
  66.        for (int i= size-1; i >= 0; i--)
  67.        {
  68.            result += this.data[i] + " " ;
  69.        }
  70.  
  71.        return result;
  72.    }
  73.  
  74.  
  75.  
  76. }

Código
  1. package clientqueue;
  2. import java.util.logging.Level;  
  3. import java.util.logging.Logger;
  4.  
  5.  
  6.  
  7. public class ClientQueue {
  8.    public static void main(String[] args) {
  9.        Queue<String> myQueue = new Queue();
  10.        myQueue.push("Jesus");
  11.        myQueue.push("Alberto");
  12.        myQueue.push("Enrique");
  13.        myQueue.push("Isma");
  14.        myQueue.push("Alexis");
  15.        System.out.println(myQueue);
  16.  
  17.        try {
  18.            myQueue.pop();
  19.        } catch (Exception ex) {
  20.            Logger.getLogger(ClientQueue.class.getName()).log(Level.SEVERE, null, ex);
  21.        }        
  22.        System.out.println(myQueue);        
  23.  
  24.  
  25.    }    
  26.  
  27.  
  28. }
5  Programación / Java / Re: ayuda hacer que aparezca casilla visible sin que el jugador se mueva en: 15 Noviembre 2018, 15:51 pm
Es que borre técnicamente el método ver() porque era lo mismo que mover() solo que te quitaba 1 de vida  :-\  pero sigo viendo cómo hacerle para que solo se descubra la casilla y que el personaje no avance xd por eso lo borre   :-[ gracias  por enseñarme lo de Geshi si es muy útil
6  Programación / Java / Re: ayuda hacer que aparezca casilla visible sin que el jugador se mueva en: 15 Noviembre 2018, 06:07 am
es que si lo que hice en el metodo ver porque lo que queria hacer era preguntarle al usuario si queria moverse a la casilla que tiene por delante o si queria solo ver que habia pero intente replicar el metodo de mover pero la verdad no tengo idea xd ando un poco perdido pero igual gracias por la ayuda  ;D
7  Programación / Java / ayuda hacer que aparezca casilla visible sin que el jugador se mueva en: 14 Noviembre 2018, 17:47 pm
estoy haciendo un pequeño juego en consola que se trata de una búsqueda del tesoro en un cuadricula pero lo que quiero hacer es que el usuario escoja dos opciones moverse o ver lo que hay en la casilla de adelante pero solo tango la opción de mover

Código
  1. package RetoFinal;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class BuscarTesoro {
  6.    public static void main(String[] args) {
  7.        System.out.println("Dame dificultad: ");
  8.        Scanner lector = new Scanner(System.in);
  9.        int dificultad = lector.nextInt();
  10.        Juego partida = new Juego(dificultad);
  11.  
  12.        do{
  13.            partida.imprimir();
  14.            System.out.println("Vida: " + partida.vida);
  15.            System.out.println("Tesoros: " + partida.tesEncontrados);
  16.  
  17.            partida.mover();
  18.  
  19.       }while(partida.vida>=0&&partida.tesEncontrados<partida.numTesoros);
  20.        if(partida.vida<0){
  21.            partida.imprimir();
  22.            System.out.println("GAME OVER");
  23.            System.out.println("Tesoros Encontrados: "+partida.tesEncontrados);
  24.        }else{
  25.            partida.imprimir();
  26.            System.out.println("GANASTE");
  27.        }
  28.    }
  29. }
  30.  
  31.  
  32.  

Código
  1. package RetoFinal;
  2.  
  3. class Comida extends Item{
  4.  
  5.    Comida(int posX, int posY) {
  6.        this.posX=posX;
  7.        this.posY=posY;
  8.        this.afecta=3;
  9.    }
  10.  
  11. }
  12.  
  13.  

Código
  1. package RetoFinal;
  2.  
  3. public class Elemento {
  4.    int posX;
  5.    int posY;
  6. }
  7.  
Código
  1. package RetoFinal;
  2.  
  3. class Enemigo extends Item{
  4.  
  5.    Enemigo(int posX, int posY) {
  6.        this.posX=posX;
  7.        this.posY=posY;
  8.        this.afecta=-5;
  9.    }
  10.  
  11. }
  12.  
Código
  1. package RetoFinal;
  2.  
  3. class Item extends Elemento{
  4.    int afecta;
  5. }
  6.  
Código
  1. package RetoFinal;
  2.  
  3. import java.util.Random;
  4. import java.util.Scanner;
  5.  
  6. public class Juego {
  7.    boolean continuar=true;
  8.    int tesEncontrados = 0;
  9.    private boolean hallazgo;
  10.    private boolean ver;
  11.    int numTesoros;
  12.    private int numEnemigos;
  13.    private int numComida;
  14.    int vida;
  15.    private int mapDimension;
  16.    private Jugador player1;
  17.    private Mapa map;
  18.    private Enemigo[] enemies;
  19.    private Comida[] food;
  20.    private Tesoro[] chest;
  21.  
  22.    public Juego(int dificultad) {
  23.  
  24.        switch(dificultad){
  25.            case 1:
  26.                this.mapDimension=5;
  27.                this.vida = 50;
  28.                this.numTesoros=1;
  29.                this.numEnemigos=2;
  30.                this.numComida=8;
  31.                break;
  32.            case 2:
  33.                this.mapDimension=8;
  34.                this.numTesoros=2;
  35.                this.vida = 40;
  36.                this.numEnemigos=4;
  37.                this.numComida=6;
  38.                break;
  39.            case 3:
  40.                this.numTesoros=4;
  41.                this.numEnemigos=8;
  42.                this.numComida=4;
  43.                this.vida = 30;
  44.                this.mapDimension=12;
  45.                break;
  46.            default:
  47.                break;
  48.        }
  49.        map = new Mapa(this.mapDimension);
  50.        this.generarJugador();
  51.        this.generarEnemigos();
  52.        this.generarComida();
  53.        this.generarTesoro();
  54.    }
  55.  
  56.    private void generarJugador() {
  57.        Random generadorAleatorios = new Random();
  58.        int posX = 0+generadorAleatorios.nextInt(this.mapDimension);
  59.        int posY = 0+generadorAleatorios.nextInt(this.mapDimension);
  60.        player1 = new Jugador(posX,posY);
  61.    }
  62.  
  63.    private void generarEnemigos() {
  64.        this.enemies = new Enemigo[this.numEnemigos];
  65.        for(int i=0;i<this.numEnemigos;i++){
  66.            Random generadorAleatorios = new Random();
  67.            int posX = 0+generadorAleatorios.nextInt(this.mapDimension);
  68.            int posY = 0+generadorAleatorios.nextInt(this.mapDimension);
  69.            int numeroAleatorio = 1+generadorAleatorios.nextInt(5);
  70.            this.enemies[i] = new Enemigo(posX, posY);
  71.        }
  72.    }
  73.  
  74.    private void generarComida() {
  75.        this.food = new Comida[this.numComida];
  76.        for(int i=0;i<this.numComida;i++){
  77.            Random generadorAleatorios = new Random();
  78.            int posX = 0+generadorAleatorios.nextInt(this.mapDimension);
  79.            int posY = 0+generadorAleatorios.nextInt(this.mapDimension);
  80.            int numeroAleatorio = 1+generadorAleatorios.nextInt(5);
  81.            food[i] = new Comida(posX, posY);
  82.        }
  83.    }
  84.  
  85.    private void generarTesoro() {
  86.        this.chest = new Tesoro[this.numTesoros];
  87.        for(int i=0;i<this.numTesoros;i++){
  88.            Random generadorAleatorios = new Random();
  89.            int posX = 0+generadorAleatorios.nextInt(this.mapDimension);
  90.            int posY = 0+generadorAleatorios.nextInt(this.mapDimension);
  91.            int numeroAleatorio = 1+generadorAleatorios.nextInt(5);
  92.            chest[i] = new Tesoro(posX, posY);
  93.        }
  94.    }
  95.  
  96.    public void imprimir() {
  97.        map.matriz[player1.posX][player1.posY] = '@';
  98.        map.imprimir();
  99.        this.generarItem();
  100.    }
  101.  
  102.    public void mover() {
  103.        if(!this.hallazgo){
  104.            map.matriz[player1.posX][player1.posY] = ' ';
  105.        }
  106.        if(ver){
  107.            map.matriz[player1.posX][player1.posY] = '?';
  108.        }
  109.        System.out.println("controles:");
  110.        System.out.println("oeste  norte  sur  este");
  111.        System.out.println("a      w      s    d");
  112.  
  113.        Scanner lector = new Scanner(System.in);
  114.        char opcion = lector.next().charAt(0);
  115.        switch(opcion){
  116.            case 'a':
  117.                player1.moverX(-1);
  118.                break;
  119.            case 'w':
  120.                player1.moverY(-1);
  121.                break;
  122.            case 's':
  123.                player1.moverY(1);
  124.                break;
  125.            case 'd':
  126.                player1.moverX(1);
  127.                break;
  128.  
  129.        }
  130.        this.encontrarItem();
  131.        this.vida-=2;
  132.    }
  133.  
  134.  
  135.    private void generarItem() {
  136.        int i;
  137.        this.hallazgo=false;
  138.        for(i=0;i<this.numTesoros;i++){
  139.            if(player1.posX==chest[i].posX&&player1.posY==chest[i].posY){
  140.                System.out.println("Encontraste Un Tesoro! Felicidades!");
  141.                map.matriz[player1.posX][player1.posY] = '$';
  142.                this.hallazgo=true;
  143.            }
  144.        }
  145.        for(i=0;i<this.numComida;i++){
  146.            if(player1.posX==food[i].posX&&player1.posY==food[i].posY){
  147.                System.out.println("Encontraste Comida! Salud+3");
  148.                map.matriz[player1.posX][player1.posY] = '+';
  149.                this.hallazgo=true;
  150.            }
  151.        }
  152.        for(i=0;i<this.numEnemigos;i++){
  153.            if(player1.posX==enemies[i].posX&&player1.posY==enemies[i].posY){
  154.                System.out.println("Encontraste Un Enemigo! Salud-5");
  155.                map.matriz[player1.posX][player1.posY] = '!';
  156.                this.hallazgo=true;
  157.            }
  158.        }
  159.    }
  160.  
  161.    private void encontrarItem() {
  162.        int i;
  163.        for(i=0;i<this.numTesoros;i++){
  164.            if(player1.posX==chest[i].posX&&player1.posY==chest[i].posY){
  165.                this.tesEncontrados++;
  166.            }
  167.        }
  168.        for(i=0;i<this.numComida;i++){
  169.            if(player1.posX==food[i].posX&&player1.posY==food[i].posY){
  170.                this.vida+=3;
  171.            }
  172.        }
  173.        for(i=0;i<this.numEnemigos;i++){
  174.            if(player1.posX==enemies[i].posX&&player1.posY==enemies[i].posY){              
  175.                this.vida-=5;
  176.            }
  177.        }
  178.    }
  179.  
  180. }
  181.  
  182.  
Código
  1. package RetoFinal;
  2.  
  3. class Jugador extends Elemento{
  4.    int vida;
  5.  
  6.    Jugador(int posX, int posY) {
  7.        this.posX=posX;
  8.        this.posY=posY;
  9.    }
  10.    public void moverX(int i){
  11.        this.posY += i;
  12.    }
  13.    public void moverY(int j){
  14.        this.posX += j;
  15.    }
  16. }
  17.  
Código
  1. package RetoFinal;
  2.  
  3. class Mapa {
  4.  
  5.    char[][] matriz;
  6.    private int dimension;
  7.  
  8.    public Mapa(int d) {
  9.        this.dimension = d;
  10.        this.matriz = new char[d][d];
  11.        for(int i=0;i<this.dimension;i++){
  12.            for(int j=0;j<this.dimension;j++){
  13.                this.matriz[i][j]='?';
  14.            }
  15.        }
  16.    }
  17.  
  18.    void imprimir() {
  19.        for(int i=0;i<this.dimension;i++){
  20.            for(int j=0;j<this.dimension;j++){
  21.                System.out.print(this.matriz[i][j]+" ");
  22.            }
  23.            System.out.println();
  24.        }
  25.    }
  26.  
  27. }
  28.  
Código
  1. package RetoFinal;
  2.  
  3.  
  4. class Tesoro extends Elemento{
  5.  
  6.    Tesoro(int posX, int posY) {
  7.        this.posX=posX;
  8.        this.posY=posY;
  9.    }
  10.  
  11. }
  12.  

lo que tengo duda es que al momento de que el jugador haga un movimiento pregunte si se quiere mover o quiere solo ver la casilla si se mueve perderia 2 de vida y si solo ve lo que hay en la casilla perderia 1 vida
8  Programación / Java / Re: crear 5 objetos con caracteristicas ya definidas aleatoriamente en: 29 Octubre 2018, 02:04 am
muchas gracias amigo me haz ayudado bastante
9  Programación / Java / crear 5 objetos con caracteristicas ya definidas aleatoriamente en: 29 Octubre 2018, 00:12 am
ayuda quiero generar un programa que me genere 5 personajes (objetos) que tengas diferentes atributos aleatoriamente

en si este es el ejercicio
Realiza un programa que incluya constructores, que genere cinco ayudantes, donde cada ayudante tiene características como: números de ojos (uno o dos), color de piel (amarilla o morada), altura (mediano o alto), un cierto nivel para crear objetos (1 al 5), un cierto nivel para arreglar cosas (1 al 5), un cierto nivel destructivo (1 al 5).

La cantidad de ayudantes necesarios ya ha sido definida, pero las características de cada uno deben ser establecidas al azar.

Al finalizar el programa, imprime la lista de los cinco ayudantes con sus características.

si alguien me puede ayudar estaria muy agradecido

por el momento llevo esto

public class Ayudantes {
    public int numOjos[] = {1,2};
    public String colorPiel[] = {"morado","amarillo"};
    public String altura[] = {"mediano","alto"};
    public int nivelCrearObjetos[] = {1,2,3,4,5};
    public int nivelArreglarCosas[] = {1,2,3,4,5};
    public int nivelDestruccion[] = {1,2,3,4,5};
   
}
10  Programación / Java / juego de adivinar palabras en consola con 3 dificultades en: 1 Octubre 2018, 04:33 am
hola que tal estoy haciendo un programa que me adivine palabras y que tenga 3 dificultades pero no logro hacer que me lea las letras que escribo porque directamente me manda a la excepcion que puse en el codigo

esto es lo que llevo actualmente

package adivinapalabras;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class AdivinarPalabras {
public static BufferedReader entrada = new BufferedReader (new InputStreamReader(System.in));
private static Set correctas;

String Facil[]= {"reir","hola","jugo","papa","pala","pasa","para","alma","nada","casa","mama","tele","mira","tela","bala","cera","tira"};
String Normal[]={"apretado", "avestruz","ceramica","estimulo","amarillo","eleccion","estrecho","invierno","chatarra","estrella"};
String Dificil[]={"indiscutible","participante","personalismo","perturbacion","contundencia","supervisamos","buscapleitos","vinculandose"};

public String generaPalabra(int Facil)
{
int n;
n= (int)(Math.random()*4);
if(Facil==0)
return Normal[n];

else
return Dificil[n];

}

public boolean checarLetra (char letra,String palabra )
{
boolean mensaje=false;
for(int i=0;i<palabra.length();i++)
{
if(letra==palabra.charAt(i))
{
mensaje = true;
break;
}
}
return mensaje;
}




public Set letrasPalabra(String palabra)
{
Set letras = new HashSet();
for (int i=0;i<palabra.length() ;i++)
{
if(palabra.charAt(i) != ' ')
{
letras.add(palabra.charAt(i));
}
}
return letras;
}

public String actualizaVisible(Set correctas, String palabra, String visible)
{
visible =""; boolean bandera = false;
Iterator it = correctas.iterator();
for(int i=0; i<palabra.length() ;i++)
{
while(it.hasNext())
{
char a = it.next().toString().charAt(0);
System.out.println(" "+a+" "+palabra.trim().charAt(i) );
if ( a == palabra.trim().charAt(i) )
{
visible += a; bandera = true;
break;
}
}
if (bandera == false)
{
visible += "_";
}
bandera=false; it = correctas.iterator();
}
return visible;
}





public static void main(String[] args) throws Exception {

System.out.println("Establezca el nivel de dificultad: ");
System.out.println("Facil(f)");
System.out.println("Normal(n)");
System.out.println("Dificil(d)");
String dificultad = entrada.readLine();


switch(dificultad)
{
case "f":
AdivinarPalabras Operacion = new AdivinarPalabras ();

Operacion.generaPalabra(1);

System.out.println("Palabra generada: ****");
System.out.println("teclea una letra de la palabra");
String letra = entrada.readLine();
char l=letra.charAt(0);
try
{
Operacion.checarLetra(l, letra);
Operacion.letrasPalabra(letra);
Operacion.actualizaVisible( correctas,letra,letra);
}
catch(Exception ex)
{
System.out.println("No introdujo una letra valida "+ex.getMessage());
}
case "n":
}
}
}
[/img][/img][/img][/img][/img][/img][/img][/img]
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines