我正在尝试使用JFrame创建一个内存匹配游戏。我正在使用包含.png文件(国家标志)的文件夹,它将使用以下代码填充String数组:
stdin
我之所以这样做是因为我想创建一个动态JButton数组,该数组以随机顺序保存每个标志,两次。每次执行程序时都必须重新标记标记。
这是我目前正在处理的代码:
public String[] listPngFiles(String filePath) {
File[] fileReader = fileReader(filePath);
String[] files = new String[fileReader.length];
for(int i=0; i<files.length; i++)
files[i] = "" + fileReader[i];
arraySize = files.length;
return files;
}
public File[] fileReader(String filePath) {
File folder = new File(filePath);
return folder.listFiles (new FilenameFilter() {
public boolean accept(File filePath, String filename)
{ return filename.endsWith(".png"); }
});
}
非常感谢您对此事的帮助。
答案 0 :(得分:1)
最佳解决方案是:
运行循环,添加两次数字
随机播放阵列
public static List<Integer> shuffleImages(int numOfPhotos)
{
List<Integer> list = new ArrayList<>();
for(int i = 0; i < numOfPhotos; ++i)
{
list.add(i);
list.add(i);
}
Collections.shuffle(list);
System.out.println(list);
return list;
}
你创建一个新游戏的每个时间都会改变名单。
do
{
List<Integer> list = shuffleImages(10);
JButton []buttons = new JButton();// assuming this is your array of buttons
for(int i = 0; i < list.size(); ++i)
{
buttons[i].setIcon(new ImageIcon(files[list.get(i)]));//set your background of your buttons
}
playGame();
}while();//exit conditon
答案 1 :(得分:0)
这是使用列表,HashMap和两个数组实现此目的的一种方法。
public static void main(String[] args) throws InterruptedException {
Random r = new Random();
int[] randoms = new int[5];
List repeated = new ArrayList();
int range = 5;
// This will fill in a first array with unique randoms.
for (int i = 0 ; i < randoms.length ; i++){
int rand;
do{
rand = r.nextInt(range) + 1;
}while(repeated.contains(rand));
repeated.add(rand);
randoms[i] = rand;
}
System.out.println(Arrays.toString(randoms)); // Prints : [2, 3, 5, 1, 4]
// This will fill the second array with duplicates at random places.
int[] finalArray = new int[randoms.length * 2];
HashMap<Integer, Integer> intint = new HashMap<>();
for (int i = 0 ; i < finalArray.length ; i++){
int whichOne;
do{
whichOne = randoms[r.nextInt(randoms.length)];
//Thread.sleep(1000);
}while(intint.get(whichOne) != null && intint.get(whichOne) > 1);
if (intint.containsKey(whichOne)) intint.replace(whichOne, 2);
else intint.put(whichOne, 1);
finalArray[i] = whichOne;
}
System.out.println(Arrays.toString(finalArray)); // Prints : [4, 3, 4, 2, 3, 2, 5, 5, 1, 1]
}