洗牌和发牌模拟 站点:爱心种子小博士 关键字:洗牌和发牌模拟
|
洗牌和发牌模拟 程序运行图:
//洗牌和发牌模拟
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DeckofCards27 extends JApplet implements
ActionListener{
private Card deck[];
private int currentCard;
private JButton dealButton,shuffleButton;
private JTextField displayCard;
Icon icon;
public void init(){
Container con=getContentPane();
con.setLayout(new GridLayout(3,1));
String faces[]={"1","2","3","4","5","6","7","8",
"9","10","11","12","13"};
String suits[]={"红心","方块","梅花","黑桃"};
icon=new ImageIcon("image/remove.gif");
deck=new Card[52];
currentCard=-1;
for(int i=0;i<deck.length;i++)
deck[i]=new Card(faces[i%13],suits[i/13]);
dealButton=new JButton("发牌",icon);
dealButton.addActionListener(this);
shuffleButton=new JButton("洗牌");
shuffleButton.addActionListener(this);
shuffleButton.setBackground(Color.red);
displayCard=new JTextField(20);
displayCard.setEditable(false);
con.add(dealButton);
con.add(shuffleButton);
con.add(displayCard);
}
public void actionPerformed(ActionEvent e){
JButton bu=(JButton)e.getSource();
if(bu==dealButton){
Card dealt=dealCard();
if(dealt!=null){
displayCard.setText(dealt.toString());
showStatus("Card#: "+currentCard);
}else{
displayCard.setText("NO MORE CARDS TO DEAL");
showStatus("sHOFFLE CARDS TO CONTINUS");
}
}else if(bu==shuffleButton){
displayCard.setText("SHOFFLING...");
showStatus("");
shuffle();
displayCard.setText("Deck is shoffled");
}
}
//洗牌
public void shuffle(){
currentCard=-1;
for(int i=0;i<deck.length;i++){
int j=(int)(Math.random()*52);
Card temp=deck[i];
deck[i]=deck[j];
deck[j]=temp;
}
dealButton.setEnabled(true);
}
public Card dealCard(){
if(++currentCard<deck.length)
return deck[currentCard];
else{
dealButton.setEnabled(false);
return null;
}
}
}
class Card{
private String face;
private String suit;
public Card(String f,String s){
face=f;
suit=s;
}
public String toString(){
return " "+suit+face;
}
} |
|
|
|