Étape 3: Le programme
Et voici mon programme (roulement de tambour...),
import java.awt.* ;
import java.awt.event.* ;
import java.util.Random ;
Import javax.swing.* ;
public class GUI_RPS
{
Voici les variables de membre. Ils sont disponibles pour une instance d’une classe.
JFrame RPS ;
JButton Rock, Paper, Scissors ;
JTextField HRPS ;
JTextField SDRC ;
JTextField résultats ;
JTextField Counter ;
JPanel hInput ;
char hChoice = ' ' ;
char cChoice = ' ' ;
Char [] cc = {'R', 'P', les de '} ;
int r3 ;
cravate d’int = 0 ;
int ordinateurGagne = 0 ;
int humanwins = 0 ;
RGen aléatoire = new Random() ;
Il s’agit d’un constructeur. Il est appelée lorsque le nouveau GUI_RPS() est appelée à partir de principal.
public GUI_RPS()
{
RPS = new JFrame ("roche, papier, ciseaux") ;
RPS.setSize (600, 600) ;
Roche = new JButton("Rock") ;
Papier = new JButton("Paper") ;
Ciseaux = new JButton("Scissors") ;
hInput = new JPanel() ;
HRPS = new JTextField(20) ;
CRP = new JTextField(20) ;
Résultats = new JTextField(20) ;
Compteur = new JTextField(30) ;
Rock.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
HRPS.setText ("vous avez choisi Rock") ;
hChoice = « R » ;
Play() ;
}
});
Paper.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
HRPS.setText ("vous avez choisi papier") ;
hChoice = « P » ;
Play() ;
}
});
Scissors.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
HRPS.setText ("vous avez choisi ciseaux") ;
hChoice = les de ' ;
Play() ;
}
});
hInput.setLayout (new FlowLayout()) ;
hInput.add(HRPS) ;
hInput.add(CRPS) ;
hInput.add(Counter) ;
hInput.add(Rock) ;
hInput.add(Paper) ;
hInput.add(Scissors) ;
RPS.getContentPane () .add (hInput, BorderLayout.CENTER) ;
RPS.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
RPS.pack() ;
RPS.setVisible(true) ;
}
Méthode ajoutée
Private Sub play()
{
R3 = rGen.nextInt(3) ;
cChoice = cc [r3] ;
Switch (cChoice)
{
case « R » :
CRPS.setText ("ordinateur choisi Rock") ;
rupture ;
case « P » :
CRPS.setText ("ordinateur choisi papier") ;
rupture ;
de l’affaire ":
CRPS.setText ("ordinateur choisi taillecrayons") ;
rupture ;
}
if(hChoice == cChoice)
{
cravate ++ ;
}
Si (hChoice == « R » & & cChoice == les de ')
{
humanwins ++ ;
}
Si (hChoice == « P » & & cChoice == « R »)
{
humanwins ++ ;
}
Si (hChoice == s ' & & cChoice == « P »)
{
humanwins ++ ;
}
Si (cChoice == « R » & & hChoice == les de ')
{
ordinateurGagne ++ ;
}
Si (cChoice == « P » & & hChoice == « R »)
{
ordinateurGagne ++ ;
}
Si (cChoice == s ' & & hChoice == « P »)
{
ordinateurGagne ++ ;
}
Counter.setText ("liens =" + cravate + ", gagne humaine =" + humanwins + ", ordinateur gagne =" + ordinateurGagne) ;
}
Public Shared Sub main (String [] args)
{
Définir le look and feel de Java Swing regarder
Essayez
{
() UIManager.setLookAndFeel
UIManager.getCrossPlatformLookAndFeelClassName()) ;
} catch (Exception e) {}
Application GUI_RPS = new GUI_RPS() ;
}
}