0

对于学校,我们需要制作名为记忆的游戏,但我的游戏并不能很好地工作。我已经拥有所有卡片,它们也可以转身,但我不知道 javafx 如何比较颜色并在颜色不匹配时将卡片转回,或者如果颜色匹配则让卡片消失。你们能帮帮我吗?这是代码的一小部分:

d = Rectangle {
width: bind 150
height: bind 150
x: bind 500
y: bind 20
arcWidth: 20
arcHeight: 20
fill:  Color.GREEN
stroke: Color.BLACK
strokeWidth: 1.0
onMouseClicked:function(a: MouseEvent)
        {
           if(d.fill == Color.GREEN)
            d.fill = Color1.YELLOW
         else
            d.fill = Color.GREEN
        }
}
 if(Color1.equals("yellow"))
             && (Color2.equals("yellow"))
 {
  d.setVisible(false);
  j.setVisible(false);

 }
4

1 回答 1

1

版本 2.X

JavaFX 显然是部分开源的(堆栈溢出参考)。从该链接中,我找到了2.X版本的类中equals()方法的源代码:Color

/**
 * Indicates whether some other object is "equal to" this one.
 * @param obj the reference object with which to compare.
 * @return {@code true} if this object is equal to the {@code obj} argument; {@code false} otherwise.
 */
@Override public boolean equals(Object obj) {
    if (obj == this) return true;
    if (obj instanceof Color) {
        Color other = (Color) obj;
        return red == other.red
            && green == other.green
            && blue == other.blue
            && opacity == other.opacity;
    } else return false;
}

显然,redgreenblueopacity需要相同。

版本 1.X

对于1.X版本,我只是查看了编译的类文件,并有足够的信心说实现与 2.X 相同(下面的片段):

@com.sun.javafx.runtime.annotation.Public
  public boolean equals(java.lang.Object arg0);
  4  invokestatic javafx.lang.Builtins.isSameObject(java.lang.Object, java.lang.Object) : boolean [87]
 15  instanceof javafx.scene.paint.Color [80]
 18  ifeq 121
 22  checkcast javafx.scene.paint.Color [80]
 28  invokevirtual javafx.scene.paint.Color.get$red() : float [45]
 38  invokevirtual javafx.scene.paint.Color.get$red() : float [45]
 50  invokevirtual javafx.scene.paint.Color.get$green() : float [47]
 60  invokevirtual javafx.scene.paint.Color.get$green() : float [47]
 72  invokevirtual javafx.scene.paint.Color.get$blue() : float [48]
 82  invokevirtual javafx.scene.paint.Color.get$blue() : float [48]
 94  invokevirtual javafx.scene.paint.Color.get$opacity() : float [49]
104  invokevirtual javafx.scene.paint.Color.get$opacity() : float [49]

从 1.X 到 2.X的equals()实现没有改变。

你真正的问题

如果Color1并且Color2确实是 type Color,您正在将它们与 type 的对象进行比较String

if(Color1.equals("yellow")) && (Color2.equals("yellow"))

比较将在此处失败:

if (obj instanceof Color)

因此,该equals()方法将始终返回 false。您应该equals()与另一个类型的对象一起使用Color

于 2013-03-18T12:36:58.007 回答