2011-12-12 18 views
6

Estoy codificando un juego de craps GUI. Hay un JButton llamado "rollo" que al hacer clic arroja los dados para el juego. La GUI luego muestra lo que rodó usando jpeg de las caras de los dados.Java Swing Dice Rolling Animation

Todo funciona muy bien, excepto que se supone que ahora debo agregar una animación a la GUI. Mi idea era de alguna manera mostrar rápidamente diferentes valores faciales durante un corto período de tiempo (simulando un "rollo") usando el mismo método de visualización de los jpeg. Sin embargo, como estoy seguro que todos ustedes saben, eso no funciona.

Estoy familiarizado con la idea de EDT y la clase Timer, pero no estoy seguro de cómo usarlas. Básicamente, quiero que esta animación suceda cuando pulso el botón "rodar", y cuando la animación finaliza, quiero que muestre lo que realmente se rodó como lo hizo antes.

Cualquier ayuda sería muy apreciada. Aquí está el código que tengo hasta el momento:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 


/* This is the GUI declaration */ 
public class NCrapsGUI extends JFrame { 
    //code... 
/* Action when "roll" is clicked */ 
    private void rollActionPerformed(java.awt.event.ActionEvent evt){           
     game.rollDice(); 
      //Rolls both die 
      sumOfDice.setText(Integer.toString(game.getSum())); 
      //Displays the sum of the die 
      numRolls.setText(Integer.toString(game.getNumRolls())); 
      //Displays the number of rolls in each game 
      // <editor-fold defaultstate="collapsed" desc="Die JPEG's"> 
      // If statements display the die face based on the number rolled 
      if (game.getDie1Value() == 1) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face1.jpg"))); 
      } 
      if (game.getDie1Value() == 2) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face2.jpg"))); 
      } 
      if (game.getDie1Value() == 3) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face3.jpg"))); 
      } 
      if (game.getDie1Value() == 4) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face4.jpg"))); 
      } 
      if (game.getDie1Value() == 5) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face5.jpg"))); 
      } 
      if (game.getDie1Value() == 6) { 
       die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face6.jpg"))); 
      } 
      if (game.getDie2Value() == 1) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face1.jpg"))); 
      } 
      if (game.getDie2Value() == 2) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face2.jpg"))); 
      } 
      if (game.getDie2Value() == 3) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face3.jpg"))); 
      } 
      if (game.getDie2Value() == 4) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face4.jpg"))); 
      } 
      if (game.getDie2Value() == 5) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face5.jpg"))); 
      } 
      if (game.getDie2Value() == 6) { 
       die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face6.jpg"))); 
      } 
      //</editor-fold> 
      /* 
      * If the game is beyond the first roll, it checks to see if the sum of the 
      * values rolled equal 7 or the point value for a loss or win respectively. 
      * If it is a win, it adds a win. Likewise for a loss. 
      */ 
      if (game.getGameStatus() == 2) { 
       if (game.getSum() == game.getPoint()) { 
        game.addWin(); 
        numWins.setText(Integer.toString(game.getWins())); 
        game.setGameStatus(1); 
        game.setPoint(0); 
        game.resetRolls(); 
        return; 
       } 
       if (game.getSum() == 7) { 
        game.addLoss(); 
        numLosses.setText(Integer.toString(game.getLosses())); 
        game.setGameStatus(1); 
        game.setPoint(0); 
        game.resetRolls(); 
        return; 
       } 
      } 

      /* 
      * This checks to see if the game is on the first roll. If it is, it checks 
      * if the sum of the die is 7 or 11 for a win, or 2, 3, or 12 for a loss. If 
      * not, it passes it on to the next roll and sets the point value to the sum 
      */ 
      if (game.getGameStatus() == 1) { 
       game.setPoint(game.getSum()); 
       dieSum.setText(Integer.toString(game.getPoint())); 

       if (((game.getSum() == 7) || ((game.getSum() == 11)))) { 
        game.addWin(); 
        numWins.setText(Integer.toString(game.getWins())); 
        game.setPoint(0); 
        dieSum.setText(Integer.toString(game.getPoint())); 
        game.resetRolls(); 
        return; 
       } 

       if (((game.getSum() == 2) || ((game.getSum()) == 3)) || (game.getSum()) == 12) { 
        game.addLoss(); 
        numLosses.setText(Integer.toString(game.getLosses())); 
        game.setPoint(0); 
        dieSum.setText(Integer.toString(game.getPoint())); 
        game.resetRolls(); 
        return; 
       } else { 
        game.setGameStatus(2); 
       } 
      } 
     }          

edición con código actualizado !!!

Aquí es donde el temporizador y la matriz se declaran:

public class NCrapsGUI extends JFrame 
{ 
private Timer timer; 
private int numPlayers; 
private int totalIcons = 6; 

private ImageIcon imageArray[];` 

/* CODE */ 

Y aquí es donde la matriz se rellena dentro del constructor NCrapsGUI:

imageArray = new ImageIcon[totalIcons]; 
    for (int i = 0; i < 6 ;i++) 
    { 
     int temp = i + 1; 
     imageArray[i] = new ImageIcon("face" + temp + ".jpg"); 
    } 

    initComponents();` 

Este es el método completo rollActionPerformed. Supongo que el temporizador comienza correctamente al al principio, pero cada vez que trato de iniciarlo recibo un montón de errores. Sin embargo, cuando hice hice un nuevo JPanel por separado, y lo hice implementar oyente de acción, no obtuve errores . He intentado añadir implementos ActionListner a esta declaración, pero NetBeans literalmente no me dejaba escribir nada en.

private void rollActionPerformed(java.awt.event.ActionEvent evt) {          



game.rollDice(); 
//Rolls both die 

sumOfDice.setText(Integer.toString(game.getSum())); 
//Displays the sum of the die 

numRolls.setText(Integer.toString(game.getNumRolls())); 
//Displays the number of rolls in each game 

// <editor-fold defaultstate="collapsed" desc="Die JPEG's"> 
// If statements display the die face based on the number rolled 
if (game.getDie1Value() == 1) 
{ 
    die1Disp.setIcon(imageArray[0]); 
} 

if (game.getDie1Value() == 2) 
{ 
    die1Disp.setIcon(imageArray[1]); 
} 

if (game.getDie1Value() == 3) 
{ 
    die1Disp.setIcon(imageArray[2]); 
} 

if (game.getDie1Value() == 4) { 
    die1Disp.setIcon(imageArray[3]); 
} 

if (game.getDie1Value() == 5) { 
    die1Disp.setIcon(imageArray[4]); 
} 

if (game.getDie1Value() == 6) 
{ 
    die1Disp.setIcon(imageArray[5]); 
} 

if (game.getDie2Value() == 1) 
{ 
    die2Disp.setIcon(imageArray[0]); 
} 

if (game.getDie2Value() == 2) 
{ 
    die2Disp.setIcon(imageArray[1]); 
} 


if (game.getDie2Value() == 3) 
{ 
    die2Disp.setIcon(imageArray[2]); 
} 

if (game.getDie2Value() == 4) 
{ 
    die2Disp.setIcon(imageArray[3]); 
} 

if (game.getDie2Value() == 5) 
{ 
    die2Disp.setIcon(imageArray[4]); 
} 

if (game.getDie2Value() == 6) 
{ 
    die2Disp.setIcon(imageArray[5]); 
} 

//</editor-fold> 

/* 
* If the game is beyond the first roll, it checks to see if the sum of the 
* values rolled equal 7 or the point value for a loss or win respectively. 
* If it is a win, it adds a win. Likewise for a loss. 
*/ 

if (game.getGameStatus() == 2) { 
    if (game.getSum() == game.getPoint()) { 
     game.addWin(); 
     numWins.setText(Integer.toString(game.getWins())); 
     game.setGameStatus(1); 
     game.setPoint(0); 
     game.resetRolls(); 
     return; 
    } 

    if (game.getSum() == 7) { 
     game.addLoss(); 
     numLosses.setText(Integer.toString(game.getLosses())); 
     game.setGameStatus(1); 
     game.setPoint(0); 
     game.resetRolls(); 
     return; 
    } 
} 

`

+0

No estoy seguro de quién votó negativamente o por qué (un voto a favor), pero le voté para contrarrestarlo. –

+0

para publicar http://sscce.org/ +1 – mKorbel

Respuesta

6

Su idea básica detrás de la animación es una buena idea, creo, pero si funciona o no está todo en los detalles de implementación, por supuesto. Sugiero

  • Que lea en sus imágenes y haga ImageIcons una vez, probablemente al principio del programa.
  • que le ponen los iconos en una matriz ImageIcon con una longitud de 7 - pero voy a poner un icono en las ranuras 1-6, dejando el elemento nulo 0 ª.
  • que utiliza un temporizador de oscilación para intercambiar estos iconos al azar con un retraso apropiado, digamos 200 o 300 mseg.
  • que utilice un objeto al azar para obtener un número aleatorio entre 1 y 6, y luego con este número como su índice de matriz, obtener el icono fuera de la matriz.
  • que muestre los ImageIcons en un JLabel (o dos JLabels si estás mostrando 2 die) e iconos de intercambio simplemente llamando el método del JLabel setIcon(...).

Editar
estado usted en su comentario que ha intentado:

timer = new Timer(100,this); 

Y ese es su problema - el uso de this. No debe intentar usar el mismo ActionListner para todo. En su lugar, crea un ActionListener allí donde lo necesites. Algo así como,

timer = new Timer(100, new ActionListener() { 
    public void actionPerformed(ActionEvent actionEvt) { 
     // ... put your ActionListener's code here 
    } 
    }); 
+2

+1 consejos. También buscaría resolver el problema de dar un solo dado, primero. – trashgod

+0

¿Pongo todo este código en mi método rollActionPerformed? Además de poblar la matriz. – lessthanjacob

+1

Creará sus ImageIcons en un constructor. El rollActionPerformed probablemente se inicie con un botón y se iniciará el temporizador que tendrá su propio ActionListener, y allí es donde se intercambian iconos aleatoriamente hasta que se repite x cantidad de veces (le dará una variable de contador int que se incrementa y comprobar). –