Foro de elhacker.net

Programación => Java => Mensaje iniciado por: keypanda en 2 Octubre 2018, 19:07 pm



Título: Juego Piedra-Papel-Tijera
Publicado por: keypanda en 2 Octubre 2018, 19:07 pm
Hola Buenas!

Estoy haciendo un sencillo juego en java para practicar utilizando java swing.
El problema que tengo, es que, cuando selecciono una de las opciones (Piedra, papel o tijera), no muestra nada, y tendría que mostrar un mensaje diciendo, por ejemplo: "Usuario gana. Roca gana a Papel" o "Computadora gana. Tijeras gana a Papel".

Con la variable que tengo que se llama "rating", tendría que mostrar dichos textos, pero no lo hace.

Si alguien puede ayudarme o darme algún consejo será bienvenido :)

A continuación dejo el código:

Código
  1. import java.awt.event.*;
  2. import javax.swing.*;
  3. import java.awt.Color;
  4. import java.awt.MouseInfo;
  5. import java.awt.Point;
  6. import com.sun.awt.AWTUtilities;
  7. import java.awt.geom.RoundRectangle2D;
  8. import java.awt.Shape;
  9. import java.util.concurrent.ThreadLocalRandom;
  10.  
  11. public class WindowPPT extends javax.swing.JFrame {
  12.  
  13.    /**
  14.      * Declarando Variables
  15.      */
  16.    private static final long serialVersionUID = 1L;    
  17.    private int x, y;    
  18.  
  19.    /**
  20.      * Piezas del Juego: Piedra, Papel y Tijera
  21.      */
  22.    private String[] actions = {"Piedra", "Papel", "Tijeras"};
  23.    //private String actionPiedra = "piedra";
  24.    //private String actionPapel = "papel";
  25.    //private String actionTijera = "tijera";
  26.  
  27.    private ActionListener buttonListener = e -> {
  28.        // Generate a random action
  29.        int random = ThreadLocalRandom.current().nextInt(0, 3);
  30.        String comAction = actions[random];
  31.  
  32.        // Rate the current situation
  33.        String rating = rate(e.getActionCommand(), comAction);
  34.  
  35.  
  36.        // Show a result alert
  37.        JOptionPane.showMessageDialog(null, rating);
  38.    };
  39.  
  40.    /**
  41.      * Creando la GUI
  42.      */
  43.    private WindowPPT() {
  44.  
  45.  
  46.        setUndecorated(true);
  47.        initComponents();
  48.        setLocationRelativeTo(null);
  49.  
  50.        BarraMenu.setBackground(Color.white);
  51.        BarraMenu.setOpaque(true);
  52.        BarraMenu.setFocusable(false);
  53.  
  54.        ExitButton.setFocusable(false);
  55.        DownButton.setFocusable(false);
  56.  
  57.        Shape forma = new RoundRectangle2D.Double(0, 0, this.getBounds().width, this.getBounds().height, 30, 30);
  58.        AWTUtilities.setWindowShape(this, forma);    
  59.  
  60.        // Creando las Acciones de los Botones
  61.            bPiedra.addActionListener(buttonListener);
  62.            bPapel.addActionListener(buttonListener);
  63.            bTijeras.addActionListener(buttonListener);
  64.  
  65.    }
  66.  
  67.    /**
  68.      * Creando la Seleccion Random del Ordenador
  69.      */
  70.     public static int computerRandomChoice() {
  71.        int result = (int) (Math.random() * 3) + 1;
  72.        return result;
  73.    }
  74.  
  75. @SuppressWarnings("unchecked")
  76.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  77.    private void initComponents() {
  78.  
  79.        jButton1 = new javax.swing.JButton();
  80.        jPanel1 = new javax.swing.JPanel();
  81.        BarraMenu = new javax.swing.JPanel();
  82.        ExitButton = new javax.swing.JButton();
  83.        DownButton = new javax.swing.JButton();
  84.        IconoLogo = new javax.swing.JLabel();
  85.        jLabel1 = new javax.swing.JLabel();
  86.        FondoPantalla = new javax.swing.JPanel();
  87.        bTijeras = new javax.swing.JButton();
  88.        bPapel = new javax.swing.JButton();
  89.        bPiedra = new javax.swing.JButton();
  90.  
  91.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  92.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  93.                jButton1ActionPerformed(evt);
  94.            }
  95.        });
  96.  
  97.        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
  98.        jPanel1.setLayout(jPanel1Layout);
  99.        jPanel1Layout.setHorizontalGroup(
  100.            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  101.            .addGap(0, 100, Short.MAX_VALUE)
  102.        );
  103.        jPanel1Layout.setVerticalGroup(
  104.            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  105.            .addGap(0, 100, Short.MAX_VALUE)
  106.        );
  107.  
  108.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  109.        setBackground(new java.awt.Color(255, 255, 255));
  110.  
  111.        BarraMenu.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
  112.            public void mouseDragged(java.awt.event.MouseEvent evt) {
  113.                BarraMenuMouseDragged(evt);
  114.            }
  115.        });
  116.        BarraMenu.addMouseListener(new java.awt.event.MouseAdapter() {
  117.            public void mousePressed(java.awt.event.MouseEvent evt) {
  118.                BarraMenuMousePressed(evt);
  119.            }
  120.        });
  121.  
  122.        ExitButton.setText("X");
  123.        ExitButton.setMaximumSize(new java.awt.Dimension(40, 40));
  124.        ExitButton.setMinimumSize(new java.awt.Dimension(40, 40));
  125.        ExitButton.setPreferredSize(new java.awt.Dimension(40, 40));
  126.        ExitButton.addActionListener(new java.awt.event.ActionListener() {
  127.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  128.                ExitButtonActionPerformed(evt);
  129.            }
  130.        });
  131.  
  132.        DownButton.setText("_");
  133.        DownButton.setMaximumSize(new java.awt.Dimension(40, 40));
  134.        DownButton.setMinimumSize(new java.awt.Dimension(40, 40));
  135.        DownButton.setPreferredSize(new java.awt.Dimension(40, 40));
  136.        DownButton.addActionListener(new java.awt.event.ActionListener() {
  137.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  138.                DownButtonActionPerformed(evt);
  139.            }
  140.        });
  141.  
  142.        IconoLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/IcoLogo.jpg"))); // NOI18N
  143.  
  144.        jLabel1.setFont(new java.awt.Font("Segoe Print", 1, 18)); // NOI18N
  145.        jLabel1.setText("Evuy's Game");
  146.  
  147.        javax.swing.GroupLayout BarraMenuLayout = new javax.swing.GroupLayout(BarraMenu);
  148.        BarraMenu.setLayout(BarraMenuLayout);
  149.        BarraMenuLayout.setHorizontalGroup(
  150.            BarraMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  151.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, BarraMenuLayout.createSequentialGroup()
  152.                .addComponent(IconoLogo)
  153.                .addGap(18, 18, 18)
  154.                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
  155.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  156.                .addComponent(DownButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
  157.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  158.                .addComponent(ExitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
  159.        );
  160.        BarraMenuLayout.setVerticalGroup(
  161.            BarraMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  162.            .addComponent(IconoLogo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  163.            .addGroup(BarraMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  164.                .addComponent(DownButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  165.                .addComponent(ExitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  166.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, BarraMenuLayout.createSequentialGroup()
  167.                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  168.                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
  169.                .addContainerGap())
  170.        );
  171.  
  172.        FondoPantalla.setBackground(new java.awt.Color(238, 249, 243));
  173.  
  174.        bTijeras.setBackground(new java.awt.Color(255, 255, 255));
  175.        bTijeras.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Tijera_opt.png"))); // NOI18N
  176.        bTijeras.addActionListener(new java.awt.event.ActionListener() {
  177.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  178.                bTijerasActionPerformed(evt);
  179.            }
  180.        });
  181.  
  182.        bPapel.setBackground(new java.awt.Color(255, 255, 255));
  183.        bPapel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Papel_opt.png"))); // NOI18N
  184.        bPapel.addActionListener(new java.awt.event.ActionListener() {
  185.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  186.                bPapelActionPerformed(evt);
  187.            }
  188.        });
  189.  
  190.        bPiedra.setBackground(new java.awt.Color(255, 255, 255));
  191.        bPiedra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Piedra_opt.png"))); // NOI18N
  192.        bPiedra.addMouseListener(new java.awt.event.MouseAdapter() {
  193.            public void mouseClicked(java.awt.event.MouseEvent evt) {
  194.                bPiedraMouseClicked(evt);
  195.            }
  196.        });
  197.        bPiedra.addActionListener(new java.awt.event.ActionListener() {
  198.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  199.                bPiedraActionPerformed(evt);
  200.            }
  201.        });
  202.  
  203.        javax.swing.GroupLayout FondoPantallaLayout = new javax.swing.GroupLayout(FondoPantalla);
  204.        FondoPantalla.setLayout(FondoPantallaLayout);
  205.        FondoPantallaLayout.setHorizontalGroup(
  206.            FondoPantallaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  207.            .addGroup(FondoPantallaLayout.createSequentialGroup()
  208.                .addGap(25, 25, 25)
  209.                .addComponent(bPiedra, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
  210.                .addGap(52, 52, 52)
  211.                .addComponent(bPapel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
  212.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
  213.                .addComponent(bTijeras, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
  214.                .addGap(25, 25, 25))
  215.        );
  216.        FondoPantallaLayout.setVerticalGroup(
  217.            FondoPantallaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  218.            .addGroup(FondoPantallaLayout.createSequentialGroup()
  219.                .addGap(88, 88, 88)
  220.                .addGroup(FondoPantallaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  221.                    .addComponent(bTijeras, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
  222.                    .addComponent(bPiedra, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
  223.                    .addComponent(bPapel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
  224.                .addContainerGap(130, Short.MAX_VALUE))
  225.        );
  226.  
  227.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  228.        getContentPane().setLayout(layout);
  229.        layout.setHorizontalGroup(
  230.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  231.            .addComponent(BarraMenu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  232.            .addComponent(FondoPantalla, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  233.        );
  234.        layout.setVerticalGroup(
  235.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  236.            .addGroup(layout.createSequentialGroup()
  237.                .addComponent(BarraMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  238.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  239.                .addComponent(FondoPantalla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  240.        );
  241.  
  242.        pack();
  243.    }
  244.  
  245. private void BarraMenuMousePressed(java.awt.event.MouseEvent evt) {                                      
  246.  
  247.        x = evt.getX();
  248.        y = evt.getY();
  249.  
  250.    }                                      
  251.  
  252.    private void BarraMenuMouseDragged(java.awt.event.MouseEvent evt) {                                      
  253.  
  254.        Point point = MouseInfo.getPointerInfo().getLocation();
  255.        setLocation(point.x - x, point.y - y);
  256.  
  257.    }                                      
  258.  
  259.    private void DownButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
  260.  
  261.        setExtendedState(ICONIFIED);
  262.  
  263.    }                                          
  264.  
  265.    private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
  266.  
  267.        System.exit(0);
  268.  
  269.    }      
  270.  
  271.  
  272. public static void main(String args[]) {
  273.  
  274.        try {
  275.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  276.                if ("Nimbus".equals(info.getName())) {
  277.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  278.                    break;
  279.                }
  280.            }
  281.        } catch (ClassNotFoundException ex) {
  282.            java.util.logging.Logger.getLogger(WindowPPT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  283.        } catch (InstantiationException ex) {
  284.            java.util.logging.Logger.getLogger(WindowPPT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  285.        } catch (IllegalAccessException ex) {
  286.            java.util.logging.Logger.getLogger(WindowPPT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  287.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  288.            java.util.logging.Logger.getLogger(WindowPPT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  289.        }
  290.  
  291.        java.awt.EventQueue.invokeLater(new Runnable() {
  292.            public void run() {
  293.                new WindowPPT().setVisible(true);
  294.            }
  295.        });
  296.    }
  297.  
  298.    /**
  299.      * Creando las Normas
  300.      */
  301.    private String rate(String userAction, String comAction) {
  302.        String msg = "";
  303.  
  304.        switch (userAction) {
  305.                case "Piedra":
  306.                switch (comAction) {
  307.                    case "Piedra":
  308.                        msg = "Empate. Ambos usaron Piedra!";
  309.                        break;
  310.  
  311.                    case "Papel":
  312.                        msg = "Has perdido. Papel gana a Piedra!";
  313.                        break;
  314.  
  315.                    case "Tijeras":
  316.                        msg = "Has ganado. Piedra gana a Tijeras!";
  317.                        break;
  318.                }
  319.                break;
  320.  
  321.            case "Papel":
  322.                switch (comAction) {
  323.                    case "Piedra":
  324.                        msg = "Has ganado. Papel gana a Piedra!";
  325.                        break;
  326.  
  327.                    case "Papel":
  328.                        msg = "Empate. Ambos usaron Papel!";
  329.                        break;
  330.  
  331.                    case "Tijeras":
  332.                        msg = "Has perdido. Tijeras gana a Papel!";
  333.                        break;
  334.                }
  335.                break;
  336.  
  337.            case "Tijeras":
  338.                switch (comAction) {
  339.                    case "Piedra":
  340.                        msg = "Has perdido. Piedra gana a Tijeras!";
  341.                        break;
  342.  
  343.                    case "Papel":
  344.                        msg = "Has ganado. Tijeras gana a Papel!";
  345.                        break;
  346.  
  347.                    case "Tijeras":
  348.                        msg = "Empate. Ambos usaron Tijeras!";
  349.                        break;
  350.                }
  351.                break;
  352.        }
  353.  
  354.        return msg;
  355.    }
  356.  
  357.    // Variables declaration - do not modify                    
  358.    private javax.swing.JPanel BarraMenu;
  359.    private javax.swing.JButton DownButton;
  360.    private javax.swing.JButton ExitButton;
  361.    private javax.swing.JPanel FondoPantalla;
  362.    private javax.swing.JLabel IconoLogo;
  363.    private javax.swing.JButton bPapel;
  364.    private javax.swing.JButton bPiedra;
  365.    private javax.swing.JButton bTijeras;
  366.    private javax.swing.JButton jButton1;
  367.    private javax.swing.JLabel jLabel1;
  368.    private javax.swing.JPanel jPanel1;
  369.    // End of variables declaration                  
  370. }
  371.  
  372.  
  373.  



Título: Re: Juego Piedra-Papel-Tijera
Publicado por: rub'n en 3 Octubre 2018, 01:52 am
El problema  esta aqui en el e.getActionCommnad() siempre viene "" por lo tanto no entra en el switch de la linea 304

Entonces con lo siguiente sabemos que botón se ha clickeado, y si sabemos que botón ha sido clikeado, podemos aplicar bien el click   :xD

Código
  1. String rating = rate(e.getActionCommand(), comAction);

Código
  1.    private ActionListener buttonListener = e -> {
  2.        // Generate a random action
  3.        int random = ThreadLocalRandom.current().nextInt(0, 3);
  4.        String comAction = actions[random];
  5.  
  6.        // Rate the current situation
  7.        String rating;
  8.  
  9.        if(e.getSource() == bTijeras) {
  10.  
  11.            rating = rate("Tijeras", comAction);
  12.        }else if(e.getSource() == bPapel) {
  13.  
  14.            rating = rate("Papel", comAction);
  15.        }else {
  16.  
  17.            rating = rate("Piedra", comAction);
  18.        }
  19.  
  20.  
  21.        // Show a result alert
  22.        JOptionPane.showMessageDialog(null , rating ,"Resultado" , 1);
  23.    };