我为宾果游戏创建了这个静态方法。
public static void bingoCard(){
int [][]card = new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
// First row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][0] = tmp;
valid = false;
}
// Second row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][1] = tmp;
valid = false;
}
// Third row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][2] = tmp;
valid = false;
}
card[2][2] = 0; // The 3rd matrix to the left and right is a 0.
// Fourth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][3] = tmp;
valid = false;
}
// Fifth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][4] = tmp;
valid = false;
}
// Creates an array to make title
String title[] = {"B","I","N","G","O"};
for(int i = 0; i < title.length;i++){
System.out.print(title[i] + "\t");
}
System.out.println();
for(int row = 0; row < card.length; row++){
for(int col = 0; col < card[row].length; col++){
System.out.print(card[row][col] + "\t");
}
System.out.println();
}
}
在输出中,这段代码输出到这个控制台宾果卡: http: //puu.sh/487mz/939c8d7a59.png
我的主要问题是重复数字。我有兴趣知道如何摆脱 5x5 数组中的重复数字。谢谢!
第二次编辑:我也有兴趣让游戏自己玩。意思是,它会提取随机数并对应数字是否在板上。如果满足 BINGO 条件的条件,则执行某些操作。有人对此有什么建议吗?