草庐IT

java - 在国际象棋游戏中实现 "Check"

coder 2024-03-19 原文

这个问题相当大,不看我的代码就很难解决,如果非常大,那么范围可能太大了,我会删除这个问题。基本上我有一个有效的国际象棋游戏,其中包含国际象棋的所有规则 except Check (和 因此也不是将死,僵局等.) 实现。

我通过为我的 ChessBoard 的 Squares 分配两个 boolean 值来实现 Check:protectedByWhiteprotectedByBlack .有两个主要的检查逻辑:

  • 如果白方下棋导致他的王在方格上 那是 protectedByBlack ,反之亦然,黑棋是 “撤消”。
  • 如果白方下棋导致黑方王位于protectedByWhite的格子上,反之亦然,黑方下一步必须将王放在不是protectedByWhite的格子上。 .

因此逻辑相当简单。在我的 ChessBoard类,我有testCheckWhitetestCheckBlack每次移动后调用的函数。在我的 Square 中调用了移动类(一个简单的鼠标点击功能)。

主要问题是代码有问题...我不确定原因/位置。主要错误是:

  • 当黑色或白色处于 Check 状态时,如果他们在仍处于 Check 状态的位置移动,则该移动不会撤消。我知道撤消功能工作正常,所以我的逻辑有些错误。

例如,当黑色/白色处于检查状态时,我在侧面有标签提醒。当我最初“检查”对手时,标签会通知我检查。但是,当我尝试将国王移动到我仍处于检查状态的方格时,标签错误地表示没有检查。我已经工作了一段时间,试图找出我哪里出错了,我可以使用一些指导。


相关代码:

ChessBoard.Java

public static void setProtectedSquares() {
        // Reset
        for(Square s : BOARD_SQUARES) {
            s.protectedByWhite = false;
            s.protectedByBlack = false;
        }

        // Now set protections
        for(Square s : BOARD_SQUARES) {
            if(s.hasPiece() && s.getPiece().getTeamColor().equals(TeamColor.WHITE)) {
                Piece p = s.getPiece();
                for(int[] position : p.getLegalMoves(p.getPosition())) {
                    if(hasSquare(position)) {
                        getSquare(position).protectedByWhite = true;
                    }
                }
            }
        }
        for(Square s : BOARD_SQUARES) {
            if(s.hasPiece() && s.getPiece().getTeamColor().equals(TeamColor.BLACK)) {
                Piece p = s.getPiece();
                for(int[] position : p.getLegalMoves(p.getPosition())) {
                    if(hasSquare(position)) {
                        getSquare(position).protectedByBlack = true;
                    }
                }
            }
        }
}

public static boolean testCheckWhite() {

        // Get king position
        int[] whiteKingPosition = new int[]{};
        for(Square s : BOARD_SQUARES) {
            Piece p = s.getPiece();
            if(s.hasPiece() && (p.getPieceType()).equals(PieceType.KING)) {
                if((p.getTeamColor()).equals(TeamColor.WHITE)) {
                    whiteKingPosition = p.getPosition();
                }
            }
        }

        if(hasSquare(whiteKingPosition) && getSquare(whiteKingPosition).protectedByBlack) {
            GameInfoPanel.inCheckWhite.setText("White is in check");
            return true;
        } else {
            GameInfoPanel.inCheckWhite.setText("White is not in check");
            return false;
        }
    }

    public static boolean testCheckBlack() {

        // Get king position
        int[] blackKingPosition = new int[]{};
        for(Square s : BOARD_SQUARES) {
            Piece p = s.getPiece();
            if(s.hasPiece() && (p.getPieceType()).equals(PieceType.KING)) {
                if((p.getTeamColor()).equals(TeamColor.BLACK)) {
                    blackKingPosition = p.getPosition();
                }
            }
        }

        if(hasSquare(blackKingPosition) && getSquare(blackKingPosition).protectedByWhite) {
            GameInfoPanel.inCheckBlack.setText("Black is in check");
            return true;
        } else {
            GameInfoPanel.inCheckBlack.setText("Black is not in check");
            return false;
        }
    }

Square.java

.... // If a square is clicked that IS colored...
        } else {
            for(Square s : ChessBoard.BOARD_SQUARES) {
                if(s.hasPiece() && (s.getPiece()).getFocus()) {

                    // Check to make sure that the target square and current
                    // square are not the same
                    if(!this.equals(s)) {
                        movePiece(s);

                        ChessBoard.setProtectedSquares();

                        // Test for check
                        // 1) Find out what color the moved piece is
                        if((ChessBoard.getTurn()) == TeamColor.WHITE) {
                            if(ChessBoard.testCheckWhite()) {
                                // Undo move
                                s.movePiece(ChessBoard.getSquare(STORED_POSITION));
                                GameInfoPanel.gameStatus.setText("Illegal move, white in check");
                            } else if(ChessBoard.testCheckBlack()) {
                                // Move is okay, black is now in check
                                GameInfoPanel.gameStatus.setText("Okay move, black in check");
                                // Switch players' turn
                                ChessBoard.switchTurn();
                            } else {
                                // Move is okay, nothing happened
                                GameInfoPanel.gameStatus.setText("No one in check");
                                // Switch players' turn
                                ChessBoard.switchTurn();
                            }

                        } else {
                            if(ChessBoard.testCheckBlack()) {
                                // Undo move
                                s.movePiece(ChessBoard.getSquare(STORED_POSITION));
                                GameInfoPanel.gameStatus.setText("Illegal move, black in check");
                            } else if(ChessBoard.testCheckWhite()) {
                                // Move is okay, white is now in check
                                GameInfoPanel.gameStatus.setText("Okay move, white in check");
                                // Switch players' turn
                                ChessBoard.switchTurn();
                            } else {
                                // Move is okay, nothing happened
                                GameInfoPanel.gameStatus.setText("No one in check");
                                // Switch players' turn
                                ChessBoard.switchTurn();
                            }
                        }
                    }
                }
            }

            // Clear all color and focus
            ChessBoard.clearFocus();

            ChessBoard.setProtectedSquares();
        }

最佳答案

我很理解你代码的算法。不幸的是,我没有发现您发布的代码段有任何问题。

这就是为什么在编写代码时应始终使用单元测试的原因。 :)

  1. 对 setProtectedSquares() 进行单元测试
  2. 对 testCheckWhite() 进行单元测试
  3. 对 testcCheckBlack() 进行单元测试
  4. 单元测试然后重构 for(Square s : ChessBoard.BOARD_SQUARES) {...}

从长远来看,这些将对您有所帮助。

但是,如果您想(希望)更快地解决问题,请使用 IDE 中的调试器 模式。

关于java - 在国际象棋游戏中实现 "Check",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23380770/

有关java - 在国际象棋游戏中实现 "Check"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  10. ruby-on-rails - 如何在 Ruby on Rails 中实现无向图? - 2

    我需要在RubyonRails中实现无向图G=(V,E)并考虑构建一个Vertex和一个Edge模型,其中Vertex有_多条边。由于边恰好连接两个顶点,您将如何在Rails中执行此操作?您是否知道任何有助于实现此类图表的gem或库(对重新发明轮子不感兴趣;-))? 最佳答案 不知道有任何现有库在ActiveRecord之上提供图形逻辑。您可能必须实现自己的Vertex、EdgeActiveRecord支持的模型(请参阅Rails安装的rails/activerecord中的vertex.rb和edge.rb/test/fixtur

随机推荐