【问题标题】:How can I write the winner's logic in a Tic Tac Toe game on Java?如何在 Java 上的井字游戏中编写获胜者的逻辑?
【发布时间】:2015-07-03 09:34:30
【问题描述】:
public void WinnerCheck() 
{
    if (m_allButtons[0][0].getText() == m_allButtons[0][1].getText() && m_allButtons[0][1].getText() == m_allButtons[0][2].getText()) 
    {
        DisableAllButtons();
    }
    else if (m_allButtons[1][0].getText() == m_allButtons[1][1].getText() && m_allButtons[1][1].getText() == m_allButtons[1][2].getText())
    {
        DisableAllButtons();
    }

}   

private void AddAllEventHandlers()
{
    if (m_allButtons != null)
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                JButton currentButton = m_allButtons[i][j];
                currentButton.addActionListener(new ActionListener() 
                {
                    public void actionPerformed(ActionEvent arg0) 
                    {
                        ChangeButtonText(currentButton);
                        WinnerCheck();
                    }
                });
            }
        }
    }
}

当我在 ActionEvent 中调用 WinnerCheck() 方法时,它实际上同时禁用了所有按钮。一旦有人赢得井字游戏,我正在尝试将逻辑写入禁用所有按钮的位置;胜利我的意思是任何行或列具有相同的值(X 或 O),但没有任何玩家值或任何分配。它只是从 X 开始,并以相反的值交替每次点击。谢谢!

【问题讨论】:

  • 如果要比较字符串,请使用.equals 而不是==。而且一个空字符串等价于另一个空字符串,所以当你检查时,你必须确保它们是“X”或“O”,而不仅仅是一个空字符串。
  • “我怎么写这个?”对于不是代码编写服务的 SO 来说,这可能是一个过于宽泛的问题。

标签: java tic-tac-toe


【解决方案1】:

我猜这是学校作业。

您需要一个算法来检查获胜条件。您无需检查整个棋盘,只需检查上一场比赛中可能获胜路径上的方格即可。

通用算法:

  1. 将总数设置为 1。
  2. 如果位置 (x-1)%3、(y-1)%3 不是同一个标记(X 或 Y),则从步骤 6 继续。
  3. 如果位置 (x-1)%3、(y-1)%3 是同一个标记,则加到总数中。
  4. 如果位置 (x+1)%3, (y+1)%3 不是同一个标记,则从步骤 6 继续。
  5. 如果位置 (x+1)%3、(y+1)%3 是相同的标记,则添加到总数中。如果总数为 3,则游戏获胜。
  6. 对这些坐标 ((x-1,y),(x+1,y)), ((x,y-1),(x,y+1)) 和 ((x) 重复 1-5 -1,y+1),(x+1,y-1)) 代替 ((x-1,y-1),(x+1,y+1))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多