Java Memory Game如何翻转个人卡?

时间:2013-11-04 09:57:44

标签: java

当我点击它们时,我正试图翻转个人卡片。在我点击所有卡同时翻转的那一刻。

这是我的代码。任何帮助将不胜感激,并提前非常感谢。

package cards;

import processing.core.PApplet;

public class MemoryGame extends PApplet {

static final int COLS=2;
static final int RAWS=3;
Card[] cards;

public void setup() {
    size(RAWS*Card.WIDTH, COLS*Card.HEIGHT); // card witdth 60*9+(10*9) for the gaps=630
    cards = new Card[COLS*RAWS];
    cards[0] = new Card(11, 0, 0);
    cards[1] = new Card(3, Card.WIDTH, 0);
    cards[2] = new Card(7, 2 * Card.WIDTH, 0);
    cards[3] = new Card(3, 0, Card.HEIGHT);
    cards[4] = new Card(7, Card.WIDTH, Card.HEIGHT);
    cards[5] = new Card(11, 2 * Card.WIDTH, Card.HEIGHT);

}

public void draw() {
    background(204);
    for (int i = 0; i < 6; i++) {
        cards[i].display(this);
    }
}

public void mousePressed() {
    for (int i = 0; i < 6; i++) {
        cards[i].flip();
    }
}

public static void main(String[] args) {
    PApplet.main("cards.MemoryGame");
}
}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

package cards;

import processing.core.PApplet;

public class Card {

boolean shown=false;
static final int WIDTH = 120;
static final int HEIGHT = 180;
static final int gap = 20;
int value;
float x,y;   

Card(int _v, float _x, float _y) {

    value = _v;
    x = _x;
    y = _y;
}

public void display(PApplet applet) {
   applet.stroke(0);
    applet.strokeWeight(2);
    if (shown) {
        applet.fill(100);
        applet.rect(x, y, WIDTH, HEIGHT,WIDTH/5);
       applet.textAlign(applet.CENTER,applet.CENTER);
       applet.textSize(WIDTH/2);
       applet.fill(0);
       applet.text(value,x+WIDTH/2,y+HEIGHT/2);
    } else {
        applet.fill(255);
        applet.rect(x, y, WIDTH, HEIGHT,WIDTH/5);
    }
}



public void flip() {
    shown=!shown;
}
}

4 个答案:

答案 0 :(得分:1)

那是因为当你按一张卡时,你会循环掉每张卡片。

public void mousePressed() {
    for (int i = 0; i < 6; i++) {
        cards[i].flip();
    }
}

尝试定义您点击的卡片,并仅对该卡片使用翻转方式。

答案 1 :(得分:1)

您循环浏览mousePressed方法中的所有卡片并翻转它们。你期望发生什么?

我想你想检查用户点击的位置,然后翻转该位置的卡片。

答案 2 :(得分:1)

按下鼠标按钮时,您正在翻转所有卡片。 您必须检查鼠标位置是否与卡相交并且按下鼠标,如果是,请翻转该卡。 使方法mouseX()和mouseY()为您提供鼠标坐标。 只需添加if(鼠标位置与卡相交):

    public void mousePressed() {
    for (int i = 0; i < 6; i++) {
        if(mouseX() >= cards[i].x && mouseX() <= cards[i].x+cards[i].width && mouseY() >= cards[i].y && mouseY() <= cards[i].y+card[i].height) {
            cards[i].flip();
        }
    }
}

答案 3 :(得分:1)

您需要在mousePressed()方法中获取鼠标事件,这样您就可以确定单击哪张卡片以便翻转它。 尝试在MemoryGame类中实现java.awt.MouseListener接口。