当前位置: 首页 > 图灵资讯 > 技术篇> Java 记忆游戏多米诺牌显示与游戏结束逻辑修复教程

Java 记忆游戏多米诺牌显示与游戏结束逻辑修复教程

来源:图灵教育
时间:2025-07-03 19:51:30

Java 记忆游戏多米诺牌显示和游戏结束逻辑修复教程

本教程旨在解决多米诺卡在Java记忆游戏项目中无法正确显示猜测卡和游戏无法正常结束的问题。核心解决方案包括重写dominoequals和hashcode方法,以实现对象内容的正确比较,并在memorylaneguess方法中使用setrevealed方法更新多米诺卡的显示状态,以确保游戏逻辑的完整性和正确性。问题分析

在Java记忆游戏代码中,有两个主要问题导致游戏无法按预期运行:

  1. 多米诺牌匹配判断不准确: Memorylane中的guess方法使用boardd[i] == board[k]判断两张多米诺卡是否匹配。在Java中,==操作符比较了两个引用是否指向内存中相同对象的例子,而不是它们所代表的逻辑内容是否相等。因此,即使两张多米诺卡(即两个Domino对象)的顶级值与顶级值相同,只要它们是不同对象的例子,==比较就会返回顶级。
  2. 多米诺品牌状态未更新: 当玩家成功猜对一对多米诺牌时,程序没有调用Domino对象的setrevealed(true)该方法将其标记为已揭示。这导致了以下连锁问题:
    • dominoisrevealed()方法总是返回false(因为revealed成员变量从未设置为true)。
    • Memorylanetostring()方法不能正确显示匹配的多米诺卡(因为它依赖于isrevealed()的状态)。
    • memorylanegameover()方法总是返回false(因为它统计了已经揭示的多米诺牌数量,而且总是为零),导致游戏无法结束。

此外,Domino类中原有的equals方法也存在逻辑错误,与top相比 == bottom,这实际上是为了检查多米诺牌是否是双牌(如[1|1]),而不是比较两个不同的Domino对象是否相等。

解决方案

针对上述问题,我们需要修改Domino类和MemoryLane类。

1. 修复 Domino 类:重写 equals() 和 hashCode() 方法

为了使Memorylane中的guess方法正确比较两个domino对象的内容(即其top和bottom值),我们需要在domino类中重写equals(Object obj)方法。同时,根据Java的协议,如果重写equals()方法,则必须同时重写hashcode()方法,以确保对象在哈希表(如hashmap)、HashSet)可以正确工作,维护equals和hashcode之间的合同:如果两个对象通过equals()相等,那么他们的hashcode()方法必须返回相同的值。

Domino 类修改示例:

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

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() {
        // 简化原始逻辑:直接返回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) {
        // 1. 检查是否引用同一对象
        if (this == obj) {
            return true;
        }
        // 2. 检查输入对象是否为null或类型不匹配
        if (obj == null || !(obj instanceof Domino)) {
            return false;
        }
        // 3. 向下转换传入对象
        final Domino other = (Domino) obj;
        // 4. 比较关键属性(top和bottom)
        if (this.getTop() !(obj instanceof Domino)) {
            return false;
        }
        // 3. 向下转换传入对象
        final Domino other = (Domino) obj;
        // 4. 比较关键属性(top和bottom)
        if (this.getTop() != other.getTop()) {
            return false;
        }
        if (this.getBottom() != other.getBottom()) {
            return false;
        }
        return true; // 如果所有属性都匹配,则认为对象相等
    }
}

注意事项:

  • equals方法的实现遵循标准:自反性、对称性、传递性、一致性和对null的判断。
  • hashcode方法的实现保证了与equals方法的一致性,即相等对象具有相同的哈希码。
2. 修复 MemoryLane 类:更新 guess() 方法

在memorylaneguess方法中,我们需要将对象引用==替换为内容比较equals(),并在匹配成功时调用domino对象的setrevealed(true)方法。

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) {
        // 使用equals方法比较Domino对象的内容
        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);
    }

    // 可选:添加debug方法查看所有牌面,便于测试
    public String debug() {
        String text = new String();
        for (int i = 0; i < board.length; i++) {
            text += ("[" + board[i].getTop() + "] ");
        }
        text += ('\n');
        for (int i = 0; i < board.length; i++) {
            text += ("[" + board[i].getBottom() + "] ");
        }
        return text;
    }

    @Override
    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;
    }
}

MemoryLaneDriver 类:

MemoryLaneDriver 类别不需要任何修改,因为它通过MemoryLane的公共接口进行交互,我们对MemoryLane和Domino的修改保持其公共接口不变(或仅在内部逻辑上进行优化)。

import java.util.Scanner;

public class MemoryLaneDriver {
    public static void main(String[] args) {
        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);

        MemoryLane game = new MemoryLane(2);

        long start = System.currentTimeMillis();

        while (!game.gameOver()) {
            // 可选:本行可在实际游戏中删除或注释,调试时用于显示所有牌面
            // System.out.println(game.debug());
            System.out.println(game);

            System.out.print("First:  ");
            int first = input.nextInt();

            System.out.print("Second: ");
            int second = input.nextInt();

            game.guess(first, second);
            System.out.println(game.peek(first, second) + "\n");
        }

        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");
    }
}

总结

通过以上修改,我们解决了记忆游戏中的核心逻辑问题:

  1. 正确识别匹配: 重写Dominoequals方法,使Memorylane.guess方法可以基于多米诺牌的实际值(top和bottom)准确比较。
  2. 正确更新状态: 在guess方法中,当检测到匹配时,调用setrevealed。(true)已经揭示了匹配多米诺牌的状态。
  3. 正确的显示和游戏结束: Domino.isRevealed()现在可以回到正确的状态,然后MemoryLane。.toString()能正确显示已揭示的牌面,MemoryLane.gameOver()能够准确判断游戏中是否所有的牌都被揭示,使游戏能够正常结束。

本案强调了正确重写equals()和hashCode()方法在Java处理定制对象比较时的重要性,以及理解对象状态管理在游戏逻辑中的关键作用。

以上是Java 记忆游戏多米诺卡显示和游戏结束逻辑修复教程的详细内容,请关注图灵教育的其他相关文章!