在开发基于对象的记忆游戏时,两个常见的问题可能导致游戏行为异常:
针对上述问题,我们将以一个Java多米诺记忆游戏为例,详细讲解如何通过覆写 equals() 和 hashCode() 方法以及正确管理对象状态来解决这些问题。
在Java中,当我们需要根据对象的实际内容(而非内存地址)来判断它们是否相等时,必须在自定义类中覆写 Object 类的 equals() 方法。同时,为了遵循Java约定和确保集合类(如 HashMap, HashSet)的正确行为,当覆写 equals() 时,也必须覆写 hashCode() 方法。
原始的 Domino 类中的 equals() 方法存在逻辑错误:它只检查 top 和 bottom 是否相等,这导致只有双面牌(如 [2][2])才会被认为是相等的,而不同位置但值相同的牌则无法匹配。
public boolean equals(Domino other) { // 错误的覆写方式 if (top == bottom) // 错误:只检查自身是否为双面牌 return true; return false; }
正确的 equals() 覆写应该比较当前 Domino 对象与传入的 Object 对象(在类型转换后)的 top 和 bottom 属性。
立即学习“Java免费学习笔记(深入)”;
@Override public boolean equals(Object obj) { // 1. 检查是否是同一个对象的引用 if (this == obj) { return true; } // 2. 检查传入对象是否为null或类型不匹配 if (obj == null || getClass() != obj.getClass()) { // 或者使用 !(obj instanceof Domino) return false; } // 3. 类型转换 final Domino other = (Domino) obj; // 4. 比较关键属性 if (this.getTop() != other.getTop()) { return false; } if (this.getBottom() != other.getBottom()) { return false; } return true; }
注意事项:
根据Java约定,如果两个对象通过 equals() 方法判断为相等,那么它们的 hashCode() 方法必须返回相同的值。覆写 hashCode() 的目的是为相等的对象生成一致的哈希码,这对于基于哈希的集合(如 HashMap, HashSet)的正确运行至关重要。
@Override public int hashCode() { int hash = 7; // 任意一个非零常数 hash = 59 * hash + this.getTop(); // 将属性值纳入哈希计算 hash = 59 * hash + this.getBottom(); return hash; }
注意事项:
多米诺牌在匹配成功后未能保持揭示状态,是因为 Domino 对象的 revealed 属性没有被设置为 true。这个状态更新的逻辑应该发生在 MemoryLane 类的 guess() 方法中,当判断两张牌匹配成功时。
原始的 guess() 方法:
public boolean guess(int i, int k) { if(board[i] == board[k]) { // 错误:使用 == 比较对象引用 return true; } return false; }
修正后的 guess() 方法不仅要使用 equals() 进行对象内容比较,还要在匹配成功后调用 setRevealed(true) 来更新多米诺牌的状态。
public boolean guess(int i, int k) { // 使用覆写后的 equals 方法进行内容比较 if (board[i].equals(board[k])) { // 如果匹配成功,设置这两张多米诺牌为已揭示状态 board[i].setRevealed(true); board[k].setRevealed(true); return true; } // 如果不匹配,不需要做任何状态改变,直接返回false return false; }
在 Domino 类中,isRevealed() 方法可以简化,因为它本质上只是返回 revealed 字段的值。
原始的 isRevealed():
public boolean isRevealed() { if (revealed) return true; return false; }
简化后的 isRevealed():
public boolean isRevealed() { return revealed; }
以下是经过上述修正后的 Domino 类和 MemoryLane 类中 guess 方法的关键代码片段。MemoryLaneDriver 类保持不变,因为它已经能够正确调用游戏逻辑。
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; if (this.getTop() != other.getTop()) { return false; } if (this.getBottom() != other.getBottom()) { return false; } return true; } }
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; } } } // 修正后的 guess 方法 public boolean guess(int i, int k) { if (board[i].equals(board[k])) { // 使用覆写后的 equals 方法 board[i].setRevealed(true); // 设置为已揭示 board[k].setRevealed(true); // 设置为已揭示 return true; } return false; } public String peek(int a, int b) { String text = ""; // 可以直接初始化为空字符串 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 = ""; 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号