gpt4 book ai didi

java - 卡牌洗牌和显示小程序

转载 作者:行者123 更新时间:2023-12-02 07:19:56 24 4
gpt4 key购买 nike

我已经编写了一些代码来创建我下载的卡片的 ArrayList,现在尝试对它们进行洗牌,然后使用 Paint 方法显示它们。如何使用 g.drawImage 显示十张卡片?

    import java.awt.Image;
import java.applet.Applet;
import java.util.*;

public class DeckofCards1 extends Applet {

public void init ( ) {
String[] suits = {"c", "s", "h", "d"};
String[] values = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "j", "q", "k"};

ArrayList<Image> images = new ArrayList<Image>( );
for(String suit : suits){
for(String value : values){
Image img = getImage ( getDocumentBase ( ), "images/" + suit + value + ".gif" );
images.add(img);
}
}
Collections.shuffle ( images ); //get ten cards randomly?
}

public void paint ( Graphics g ) { //display ten cards here?

g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 30, this ); //what goes in place of img (which I know isn't right, simply a placeholder for now
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );

}
}

最佳答案

关于混排,Collections.shuffle ( images ); 将随机排列 images 的元素。但我建议添加这一行:

private final Random random = new Random(4454776669L);

并使用Collections.shuffle(images, random);来代替。这里的数字 4454776669L 是伪随机数生成器的种子,当您使用相同的种子时,您会重现相同的随机数序列,如果您想重现相同的游戏或仅用于调试目的,这可能很有用。

关于java - 卡牌洗牌和显示小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com