gpt4 book ai didi

java - 如何在设置约束的情况下将按钮的背景设置为随机颜色?

转载 作者:行者123 更新时间:2023-12-02 10:03:54 25 4
gpt4 key购买 nike

我有一个函数,可以将所有按钮的背景颜色设置为红色,目前它的工作原理如下,但是,我想做的是将其设置为带有设置约束的随机颜色,这些是可以从中选取的随机颜色的最大数量,以及分配给每个按钮的相同颜色的最大数量。

例如,如果随机颜色的最大数量为 8,相同颜色的最大数量为 2,则只会选择 8 个随机颜色,并且相同的颜色将仅分配给 2 个按钮。

这是我正在创建的配对游戏。我已经创建了一个函数,该函数在单击所有按钮时为所有按钮设置随机颜色,但是,这没有我之前讨论的约束。

最佳答案

这是错误的:

for (int i = 0; i < arrayButtons.length; i++) {
arrayButtons[i].setDrawColor(new Color(rand.nextInt()));
}

您需要创建一半的随机颜色和颜色 2 按钮,然后对数组进行洗牌。我会使用 ArrayList——更容易洗牌和添加内容。所以假设 List<ColorButton>称为按钮列表:

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

就我自己而言,我会做一些不同的事情:

  • 我不会扩展 JButton
  • 我会使用模型- View - Controller 程序结构的变体将模型与 View 分开
  • 所有逻辑都将保存在模型中,包括 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;
}
}

关于java - 如何在设置约束的情况下将按钮的背景设置为随机颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441659/

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