
在开发基于java的多米诺记忆游戏时,开发者可能遇到以下两个主要问题:
这些问题的根源主要在于Java对象比较的误用以及对象状态管理的不完善。
在Java中,==运算符用于比较基本数据类型的值,以及对象的引用地址。当用于对象时,board[i] == board[k]实际上是检查board[i]和board[k]这两个引用是否指向内存中的同一个对象实例。然而,在记忆游戏中,我们希望比较的是两个多米诺牌的“值”是否相等(即它们的顶部和底部数字是否相同),而不是它们是否是同一个对象。
原始的Domino类中虽然有一个equals(Domino other)方法,但其实现存在逻辑错误(if (top == bottom) return true;),并且在MemoryLane类的guess方法中,并没有调用这个自定义的equals方法,而是使用了board[i] == board[k]进行引用比较。这导致即使两个多米诺牌的值相同,它们也不会被认为是匹配的,因为它们是不同的对象实例。
Domino类中定义了revealed布尔变量和setRevealed(boolean revealed)方法,旨在标记多米诺牌是否已揭示。然而,在MemoryLane的guess方法中,即使判断为匹配(尽管判断方式有误),也没有调用setRevealed(true)来更新相应多米诺牌的revealed状态。这意味着多米诺牌的揭示状态从未被实际改变,导致它们在toString()方法渲染时总是显示为未揭示。
立即学习“Java免费学习笔记(深入)”;
MemoryLane类中的gameOver()方法通过遍历board数组,检查所有多米诺牌的isRevealed()状态来判断游戏是否结束。由于setRevealed()方法从未被调用,isRevealed()始终返回false,导致count变量永远不会达到board.length,因此游戏永远不会结束。
要解决上述问题,我们需要对Domino类和MemoryLane类进行关键性的修改。
在Java中,当需要比较两个对象的逻辑相等性(即它们的值是否相等,而非引用地址)时,必须覆盖Object类提供的equals()方法。同时,根据Java规范,如果覆盖了equals()方法,也必须覆盖hashCode()方法,以维护equals()和hashCode()之间的契约。
Domino 类修改:
public class Domino {
private int top, bottom;
private boolean revealed;
public Domino(int x, int y) {
if (x > y) {
top = y;
bottom = x;
} else {
top = x;
bottom = y;
}
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
public boolean isRevealed() {
// 简化后的isRevealed方法,直接返回revealed状态
return revealed;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.getTop();
hash = 59 * hash + this.getBottom();
return hash;
}
@Override
public boolean equals(Object obj) {
// 检查是否为同一对象引用
if (this == obj) {
return true;
}
// 检查obj是否为null或类型不匹配
if (!(obj instanceof Domino)) {
return false;
}
// 将obj强制转换为Domino类型
final Domino other = (Domino) obj;
// 比较top和bottom属性是否相等
if (this.getTop() != other.getTop()) {
return false;
}
if (this.getBottom() != other.getBottom()) {
return false;
}
return true;
}
}equals() 和 hashCode() 契约的重要性:
现在,Domino对象可以正确地进行值比较了。接下来,我们需要修改MemoryLane类中的guess()方法,使其使用Domino类中新覆盖的equals()方法进行比较,并在匹配成功时更新多米诺牌的揭示状态。
MemoryLane 类修改:
import java.util.Arrays;
import java.util.Random;
public class MemoryLane {
private Domino[] board;
public MemoryLane(int max) {
board = new Domino[(max * max) + max];
int i = 0;
for (int top = 1; top <= max; top++) {
for (int bot = 1; bot <= max; bot++) {
if (top <= bot) {
board[i] = new Domino(top, bot);
i++;
board[i] = new Domino(top, bot);
i++;
}
}
}
shuffle();
}
private void shuffle() {
int index;
Random random = new Random();
for (int i = board.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
Domino temp = board[index];
board[index] = board[i];
board[i] = temp;
}
}
}
public boolean guess(int i, int k) {
// 使用Domino的equals方法进行值比较
if (board[i].equals(board[k])) {
// 如果匹配成功,设置这两张牌为已揭示
board[i].setRevealed(true);
board[k].setRevealed(true);
return true;
}
return false;
}
public String peek(int a, int b) {
String text = new String();
text += ("[" + board[a].getTop() + "] [" + board[b].getTop() + "]\n");
text += ("[" + board[a].getBottom() + "] [" + board[b].getBottom() + "]\n");
return text;
}
public boolean gameOver() {
int count = 0;
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
count++;
}
}
return (count == board.length);
}
public String toString() {
String text = new String();
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getTop() + "] ");
} else {
text += ("[ ] ");
}
}
text += ('\n');
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getBottom() + "] ");
} else {
text += ("[ ] ");
}
}
return text;
}
}为了提供一个可运行的完整示例,我们将Domino和MemoryLane类作为内部类或单独文件进行组织。这里提供一个将它们作为内部类包含在Main类中的示例,以方便测试。
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().runGame();
}
public void runGame() {
String message = "Welcome to Memory Lane!" + "\n"
+ "Choose two indexes to reveal the corresponding dominoes." + "\n"
+ "If the dominoes match, they stay revealed." + "\n"
+ "Reveal all the dominoes to win the game!" + "\n";
System.out.println(message);
Scanner input = new Scanner(System.in);
// 使用max=2,生成(2*2)+2 = 6张多米诺牌
MemoryLane game = new MemoryLane(2);
long start = System.currentTimeMillis();
while (!game.gameOver()) {
// 打印当前游戏板状态
System.out.println(game);
System.out.print("First: ");
int first = input.nextInt();
System.out.print("Second: ");
int second = input.nextInt();
// 检查用户输入的索引是否有效
if (first < 0 || first >= game.board.length || second < 0 || second >= game.board.length) {
System.out.println("Invalid index. Please enter numbers between 0 and " + (game.board.length - 1));
continue; // 跳过本次循环,重新输入
}
// 尝试猜测
boolean isMatch = game.guess(first, second);
System.out.println(game.peek(first, second) + "\n"); // 显示选择的牌
if (isMatch) {
System.out.println("It's a match! These dominoes will stay revealed.");
} else {
System.out.println("No match. Try again!");
// 对于不匹配的情况,需要将牌重新隐藏。
// 原始问题中没有提及此需求,但通常记忆游戏会在不匹配时隐藏牌。
// 这里为了保持与原代码逻辑一致,不自动隐藏。
// 如果需要隐藏,可以在这里添加 board[i].setRevealed(false); board[k].setRevealed(false);
// 但这需要修改peek方法,使其临时揭示,然后根据是否匹配决定是否保持揭示。
// 鉴于驱动程序不允许修改,我们保持现有行为。
}
}
long stop = System.currentTimeMillis();
long elapsed = (stop - start) / 1000;
System.out.println(game); // 游戏结束时显示最终状态
System.out.println("\nYou win!");
System.out.println("Total time: " + elapsed + "s");
input.close();
}
// Domino Class
public class Domino {
private int top, bottom;
private boolean revealed;
public Domino(int x, int y) {
if (x > y) {
top = y;
bottom = x;
} else {
top = x;
bottom = y;
}
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
public boolean isRevealed() {
return revealed;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.getTop();
hash = 59 * hash + this.getBottom();
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) { // 更严格的类型检查
return false;
}
final Domino other = (Domino) obj;
// 确保比较的是多米诺牌的top和bottom值
if (this.getTop() != other.getTop()) {
return false;
}
if (this.getBottom() != other.getBottom()) {
return false;
}
return true;
}
}
// MemoryLane Class
public class MemoryLane {
private Domino[] board;
public MemoryLane(int max) {
board = new Domino[(max * max) + max]; // 例如max=2时,数组大小为6
int i = 0;
// 生成多米诺牌对
for (int top = 1; top <= max; top++) {
for (int bot = 1; bot <= max; bot++) {
if (top <= bot) { // 避免重复,如(1,2)和(2,1)视为同一种牌
board[i] = new Domino(top, bot);
i++;
board[i] = new Domino(top, bot); // 创建一对相同的牌
i++;
}
}
}
shuffle();
}
private void shuffle() {
int index;
Random random = new Random();
for (int i = board.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
// 交换元素
Domino temp = board[index];
board[index] = board[i];
board[i] = temp;
}
}
public boolean guess(int i, int k) {
// 确保索引有效且不相同
if (i == k || i < 0 || i >= board.length || k < 0 || k >= board.length) {
return false; // 无效猜测
}
// 核心修复:使用equals方法比较对象内容
if (board[i].equals(board[k])) {
// 如果匹配,则设置多米诺牌为已揭示状态
board[i].setRevealed(true);
board[k].setRevealed(true);
return true;
}
return false;
}
public String peek(int a, int b) {
// 临时显示所选牌面,无论是否匹配
String text = "";
if (a >= 0 && a < board.length && b >= 0 && b < board.length) {
text += ("[" + board[a].getTop() + "] [" + board[b].getTop() + "]\n");
text += ("[" + board[a].getBottom() + "] [" + board[b].getBottom() + "]\n");
} else {
text = "Invalid peek indices.\n";
}
return text;
}
public boolean gameOver() {
int count = 0;
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
count++;
}
}
// 当所有多米诺牌都被揭示时,游戏结束
return (count == board.length);
}
// 用于调试,显示所有牌的真实值
public String debug() {
String text = "";
for (int i = 0; i < board.length; i++) {
text += ("[" + board[i].getTop() + "," + board[i].getBottom() + "] ");
}
text += ('\n');
return text;
}
@Override
public String toString() {
String text = "";
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getTop() + "] ");
} else {
text += ("[ ] ");
}
}
text += ('\n');
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getBottom() + "] ");
} else {
text += ("[ ] ");
}
}
return text;
}
}
}通过以上修改,多米诺记忆游戏将能够正确地识别匹配、保持揭示状态,并最终在所有牌被揭示后正常结束。这不仅解决了功能上的问题,也强化了对Java中对象比较和状态管理核心概念的理解。
以上就是Java多米诺记忆游戏逻辑修复与对象比较深度解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号