我有一个将所有按钮的背景色设置为红色的函数,目前它的工作方式是这样,但是,我想做的是将其设置为具有设置约束的随机颜色,这些是可以选择的最大随机颜色数量,以及分配给每个按钮的相同颜色的最大数量。
例如,如果随机颜色的最大数量为8,而同一颜色的最大数量为2,则只能选择8种随机颜色,而同一颜色将仅分配给恰好2个按钮。
这是针对我正在创建的配对游戏。我已经创建了一个函数,该函数可以在单击所有按钮时为所有按钮设置随机颜色,但是,它没有前面提到的约束。
答案 0 :(得分:1)
这是错误的:
for (int i = 0; i < arrayButtons.length; i++) {
arrayButtons[i].setDrawColor(new Color(rand.nextInt()));
}
您需要使用它们创建一半的随机颜色和2个颜色按钮,然后对数组进行随机排列。我将使用ArrayList -易于改组和添加内容。因此,假设一个List<ColorButton>
名为buttonList:
for (int i = 0; i < buttonList.size() / 2; i++) {
Color color = new Color(rand.nextInt();
buttonList.get(2 * i).setDrawColor(color));
buttonList.get(2 * i + 1).setDrawColor(color));
}
Collections.shuffle(buttonList);
,或者如果您必须使用数组,并且将随机播放数组:
for (int i = 0; i < arrayButtons.length / 2; i++) {
Color color = new Color(rand.nextInt();
arrayButtons[2 * i].setDrawColor(color));
arrayButtons[2 * i + 1].setDrawColor(color));
}
// shuffle your array here
编辑:我改变了主意。创建List<Color>
的最简单方法是,将其填充8对不同的颜色,将其随机排列,然后将颜色添加到按钮中。如果您希望所有颜色都明亮,而不是随机颜色,请使用Color的.getHSBColor(...)
方法使用8种不同的色调颜色:
List<Color> colorList = new ArrayList<>();
for (int i = 0; i < 8; i++) {
float hue = i * 1f / 8;
Color c = Color.getHSBColor(hue, 1f, 1f);
colorList.add(c);
colorList.add(c);
}
Collections.shuffle(colorList);
// add colors to buttons in for loop
或...
colorList = new ArrayList<>();
for (int i = 0; i < ROWS * COLS / 2; i++) {
float r = (float) Math.random();
float g = (float) Math.random();
float b = (float) Math.random();
Color color = new Color(r, g, b);
colorList.add(color);
colorList.add(color);
}
Collections.shuffle(colorList);
// add colors to buttons using for loop
我自己,我做的事情会有所不同:
ArrayList<Integer>
中随机排列的8个数字对例如:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class ColorTest extends JPanel {
private static final int ROWS = 4;
private static final int COLS = 4;
private static final int BTN_W = 100;
private static final int BTN_H = 100;
private static final Dimension BTN_SIZE = new Dimension(100, 100);
// how long to show mismatched color pairs
private static final int COLOR_DISPLAY_DELAY = 2000; // msecs
private static final int NO_PICK = -1;
private List<ColorButton2> buttonList = new ArrayList<>();
private List<Color> colorList = new ArrayList<>();
private int firstPick = NO_PICK;
private int secondPick = NO_PICK;
private ButtonListener buttonListener = new ButtonListener();
private boolean listenerEnabled = true;
public ColorTest() {
JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS));
for (int index = 0; index < ROWS * COLS; index++) {
ColorButton2 button = new ColorButton2(index, BTN_W, BTN_H);
button.addActionListener(buttonListener);
button.setPreferredSize(BTN_SIZE);
buttonList.add(button);
gridPanel.add(button);
}
reset();
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(e -> reset());
resetButton.setMnemonic(KeyEvent.VK_R);
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(e -> System.exit(0));
JPanel btnPanel = new JPanel(new GridLayout(1, 0));
btnPanel.add(resetButton);
btnPanel.add(exitButton);
setLayout(new BorderLayout());
add(gridPanel);
add(btnPanel, BorderLayout.PAGE_END);
}
public void reset() {
colorList = new ArrayList<>();
for (int i = 0; i < ROWS * COLS / 2; i++) {
// Color color = randomRgbColor();
float hue = (2f * i) / (ROWS * COLS); // non-random hue
Color color = randomHsbColor(hue); // randomize the saturation and
// brilliance
colorList.add(color);
colorList.add(color);
}
Collections.shuffle(colorList);
for (int i = 0; i < buttonList.size(); i++) {
ColorButton2 btn = buttonList.get(i);
btn.reset();
btn.setColor(colorList.get(i));
}
}
@SuppressWarnings("unused")
private Color randomRgbColor() {
float r = (float) Math.random();
float g = (float) Math.random();
float b = (float) Math.random();
Color color = new Color(r, g, b);
return color;
}
private Color randomHsbColor(float hue) {
// float hue = (float) Math.random();
float sat = ((int) (2 * Math.random()) + 1) / 2f;
float bril = ((int) (2 * Math.random()) + 1) / 2f;
return Color.getHSBColor(hue, sat, bril);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (!listenerEnabled) {
// if button listener disabled -- get out of here
return;
}
ColorButton2 source = (ColorButton2) e.getSource();
if (source.getNumber() == firstPick) {
// if user chooses same button twice, a mistake, so exit
return;
}
if (source.isPairMatched()) {
// button already matched
return;
}
source.flip(true); // show button's real color
// if user has selected first button
if (firstPick == NO_PICK) {
firstPick = source.getNumber(); // set first button pick field
} else {
// else user has selected 2nd button
secondPick = source.getNumber();
// check if the two buttons hold the same color
Color c1 = buttonList.get(firstPick).getColor();
Color c2 = buttonList.get(secondPick).getColor();
if (c1.equals(c2)) {
// matching picks, then disable both buttons
buttonList.get(firstPick).setPairMatched(true);
buttonList.get(secondPick).setPairMatched(true);
// reset these variables
firstPick = NO_PICK;
secondPick = NO_PICK;
// check that the game isn't over
checkForWin();
} else {
// start timer to display buttons for period of time, then
// flip back
listenerEnabled = false; // disable all button's action
// listeners
new Timer(COLOR_DISPLAY_DELAY, e2 -> {
// show background color for both buttons
buttonList.get(firstPick).flip(false);
buttonList.get(secondPick).flip(false);
// re-enable the action listener
listenerEnabled = true;
firstPick = NO_PICK;
secondPick = NO_PICK;
((Timer) e2.getSource()).stop(); // non-repeating timer
}).start();
}
}
}
}
public void checkForWin() {
boolean win = true;
for (ColorButton2 button : buttonList) {
win &= button.isPairMatched();
}
if (win) {
String message = "You've matched all the colors";
String title = "Congratulations!";
int messageType = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(ColorTest.this, message, title, messageType);
}
}
private static void createAndShowGui() {
ColorTest mainPanel = new ColorTest();
JFrame frame = new JFrame("ColorTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
@SuppressWarnings("serial")
class ColorButton2 extends JButton {
// background color
private static final Color BG_COLOR = Color.LIGHT_GRAY;
private int number;
// non-background color
private Color color = null;
// true if a pair has been found for this button
private boolean pairMatched = false;
public ColorButton2(int number, int width, int height) {
this.number = number;
setPreferredSize(new Dimension(width, height));
setBackground(BG_COLOR);
}
// reset back to initial conditions
public void reset() {
setPairMatched(false);
setBackground(BG_COLOR);
}
// if true -- show real color, else show background color
public void flip(boolean flip) {
if (flip) {
setBackground(color);
} else {
setBackground(BG_COLOR);
}
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void setNumber(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
public boolean isPairMatched() {
return pairMatched;
}
// if match is found, disable the button and set the field
public void setPairMatched(boolean pairMatched) {
setEnabled(!pairMatched);
this.pairMatched = pairMatched;
}
}