首页 > Java > java教程 > 正文

Java多米诺记忆游戏逻辑修复与对象比较深度解析

花韻仙語
发布: 2025-07-07 20:26:02
原创
819人浏览过

Java多米诺记忆游戏逻辑修复与对象比较深度解析

本教程旨在解决Java多米诺记忆游戏中常见的逻辑问题,包括多米诺牌无法正确显示为已揭示状态以及游戏无法正常结束。核心解决方案涉及正确覆盖Java对象的equals()和hashCode()方法以实现值比较,并确保在猜对时调用setRevealed()方法更新多米诺牌的状态。通过这些改进,游戏将能够正确识别匹配,并根据牌面状态判断游戏胜利条件。

1. 问题分析

在开发基于java的多米诺记忆游戏时,开发者可能遇到以下两个主要问题:

  1. 多米诺牌匹配后未能保持揭示状态: 即使玩家猜对了匹配的多米诺牌,这些牌在后续的游戏界面刷新中仍然显示为未揭示状态。
  2. 游戏无法正常结束: 即使所有多米诺牌都被正确匹配并理应揭示,游戏也未能检测到胜利条件并终止。

这些问题的根源主要在于Java对象比较的误用以及对象状态管理的不完善。

1.1 对象比较的误区:== 与 equals()

在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]进行引用比较。这导致即使两个多米诺牌的值相同,它们也不会被认为是匹配的,因为它们是不同的对象实例。

1.2 状态管理缺失:setRevealed() 未被调用

Domino类中定义了revealed布尔变量和setRevealed(boolean revealed)方法,旨在标记多米诺牌是否已揭示。然而,在MemoryLane的guess方法中,即使判断为匹配(尽管判断方式有误),也没有调用setRevealed(true)来更新相应多米诺牌的revealed状态。这意味着多米诺牌的揭示状态从未被实际改变,导致它们在toString()方法渲染时总是显示为未揭示。

立即学习Java免费学习笔记(深入)”;

1.3 游戏结束条件判断失误

MemoryLane类中的gameOver()方法通过遍历board数组,检查所有多米诺牌的isRevealed()状态来判断游戏是否结束。由于setRevealed()方法从未被调用,isRevealed()始终返回false,导致count变量永远不会达到board.length,因此游戏永远不会结束。

2. 解决方案与实现

要解决上述问题,我们需要对Domino类和MemoryLane类进行关键性的修改。

2.1 正确覆盖 Domino 类的 equals() 和 hashCode() 方法

在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() 契约的重要性:

  • 如果两个对象根据equals(Object)方法是相等的,那么调用这两个对象中任意一个的hashCode()方法都必须产生同样的整数结果。
  • 如果两个对象根据equals(Object)方法是不相等的,那么调用这两个对象中任意一个的hashCode()方法不要求产生不同的整数结果。但是,为不相等的对象生成不同的哈希码可以提高哈希表(如HashMap、HashSet)的性能。

2.2 更新 MemoryLane 类的 guess() 方法

现在,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;
    }
}
登录后复制

3. 完整示例代码

为了提供一个可运行的完整示例,我们将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;
        }
    }
}
登录后复制

4. 注意事项与总结

  • equals() 和 hashCode() 的重要性: 对于自定义类,当需要比较对象的逻辑内容而非内存地址时,务必正确覆盖equals()方法。同时,为了确保在哈希集合(如HashSet、HashMap的键)中正常工作,必须同时覆盖hashCode()方法,并遵循其契约。这是Java面向对象编程中的一个基本而重要的原则。
  • 对象状态管理: 明确对象应如何响应外部操作并改变自身状态。在本例中,当多米诺牌被成功匹配时,其revealed状态必须被显式更新,才能反映在游戏界面上并影响游戏结束条件。
  • 游戏逻辑的完整性: 确保游戏的胜利或失败条件能够基于正确的状态进行判断。当所有关键状态(如revealed)都得到正确维护时,gameOver()等方法才能准确地反映游戏进程。
  • 代码可读性与维护性: 良好的命名、清晰的逻辑和适当的注释有助于提高代码的可读性和未来的维护性。

通过以上修改,多米诺记忆游戏将能够正确地识别匹配、保持揭示状态,并最终在所有牌被揭示后正常结束。这不仅解决了功能上的问题,也强化了对Java中对象比较和状态管理核心概念的理解。

以上就是Java多米诺记忆游戏逻辑修复与对象比较深度解析的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号