我现在正在创建卡牌游戏的基础,我只是为卡牌做一些基本功能。我想洗牌,但不知道如何编写它的函数。它将在主程序中调用,这是我迄今为止拥有的套牌类:
import java.awt.*;
import javax.swing.*;
import java.awt.event.* ; //capture mouse events
import java.awt.Graphics ;
import java.awt.Event;
import java.util.Random;
public class Deck
{
private Random random = new Random ();
protected Card cards[] = new Card[52] ;
protected int numcards = 0;
public Deck()
{
int i = 0;
for (int s = 1; s<5 ; s++)
{
for (int n=1; n<14 ; n++)
{
cards[i] = new Card(n,s);
i++;
numcards = numcards + 1;
}
}
}
public void giveCard(Deck p)
{
numcards = numcards - 1;
p.takeCard(cards[numcards]);
return;
}
public void takeCard(Card c)
{
cards[numcards] = c;
numcards = numcards + 1;
}
public void shuffle ()
{
int temp;
for (int i = 0; i<52; i++)
{
//cards[i] = temp ;
}
}
public void draw (Container c ,Graphics g, int x , int y )
{
for (int i = 0; i<numcards; i++)
{
cards[i].draw(c, g, x+i*20,y) ;
}
}
}
最佳答案
如果您更改 Card[]
进入List<Card>
相反,您可以简单地使用 Collections.shuffle(cards)
。否则,循环遍历数组,在每个点将当前卡与随机选择的卡交换。
关于java - 如何使用java中的基本switch方法洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812687/