Java内存游戏卡翻转不起作用



我正在开发一个Java内存游戏,但我有一个问题,我无法解决。如果我点击任何卡片,它就会出现,之后我点击第二张卡片,但它没有出现。如果他们在检查后匹配,则第二张卡翻转。

卡.class

public class Card{
private int img_x, img_y;
private Img img;
private boolean flipped = false;
private boolean flippable = true;
private static Img back_img;
private static int WIDTH, HEIGHT;
public Card(int img_x, int img_y, img img) {
this.img_x = img_x;
this.img_y = img_y;
this.img = img;
}
public void draw(Graphics g) {
if (flipped) {
g.drawImage(img.getimg(), img_x, img_y, WIDTH, HEIGHT, null);
} else {
g.drawImage(back_img.getimg(), img_x, img_y, WIDTH, HEIGHT, null);
}
}
public void flip() {
if (flippable) {
this.flipped = !flipped;
}
}

点击事件

public void clickEvent(int x, int y) {
for (Card card : cards) {
if ((card.getImg_x() < x) && (card.getImg_x() + card.getWIDTH() > x)
&& (card.getImg_y() < y) && (card.getImg_y() + card.getHEIGHT() > y)) {
if (card.isFlippable()) {
card.flip();
selectedCards.add(card);
}
break;
}
}
gamePanel.reapint();
if (selectedCards.size() == 2) {  // if 2 card flipped up
checkFlippedCards();  //check the 2 cards' images name, if matched it lock the cards to not flippable
}
gamePanel.reapint();
}

我花了两天时间来解决这个问题,但我不知道为什么它不起作用。当我单击任何卡但只有一张卡按预期向上翻转时,也会运行相同的方法。

支票翻转卡

private void checkFlippedCards() {
int name1 = selectedCards.get(0).getImgName();
int name2 = selectedCards.get(1).getImgName();
if (name1 == name2) {
score++;
selectedCards.get(0).setFlippable(false);
selectedCards.get(1).setFlippable(false);
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Vezerlo.class.getName()).log(Level.SEVERE, null, ex);
}
selectedCards.get(0).flip();
selectedCards.get(1).flip();
kivalasztottKartyak.clear();
}

如果我正确理解您的代码,您正在翻转第二张卡,然后检查两张卡是否相等,如果它们是,则它们保持翻转状态。

问题是当它们不是时,因为它们在重新粉刷面板之前再次翻转回来。

您有Thread.sleep的事实并不意味着它会刷新,因为重绘也是在休眠的同一线程中完成的。

我的建议是将翻转的卡片检查放在另一个线程上,以便您可以刷新主线程而不会干扰重新绘制。

另一种解决方案是让您在卡片不相等时不要自动翻转卡片。所以,比如说,它们应该在下一次点击时翻转回来。这可以通过移动来完成

selectedCards.get(0).flip();
selectedCards.get(1).flip();
kivalasztottKartyak.clear();

clickEvent,只需检查是否selectedCards.size() == 2.在这种情况下,您只会翻转两张卡,而在此单击中不执行任何其他操作并摆脱sleep

最新更新