【问题标题】:How to find the value of this Boolean in this chess program?如何在这个国际象棋程序中找到这个布尔值的值?
【发布时间】:2017-06-28 05:59:47
【问题描述】:

我有这个 SchachChecker.java 文件,它基本上读入了棋盘上的某些棋子配置。

我的目标是在 Schachbrett.java 中实现一个函数 (moeglicheZuege),该函数会打印出玩家在这一回合可以做出的所有可能动作,这将由 SchachChecker 类调用。

我的方法是遍历所有方格,检查上面有哪个棋子以及来自哪个玩家(黑色或白色),然后检查这个棋子可以执行什么动作。

到目前为止,我已经能够进行迭代并弄清楚每个方块上是哪一块,但我就是不知道这些块的颜色。

SchachChecker.java:

import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.Charset;

public class SchachChecker {
  public static final Map<Character, Class<? extends Schachbrett.Feld>> pieceMap =
      new HashMap<Character, Class<? extends Schachbrett.Feld>>() {
        {
          put('b', Schachbrett.Bauer.class);
          put('s', Schachbrett.Springer.class);
          put('l', Schachbrett.Laeufer.class);
          put('t', Schachbrett.Turm.class);
          put('d', Schachbrett.Dame.class);
          put('k', Schachbrett.Koenig.class);
          put(' ', Schachbrett.Feld.class);
        }
      };

  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      throw new RuntimeException("Parameter fehlt: Schachbrett");
    } else if (args.length < 2) {
      throw new RuntimeException("Parameter fehlt: wer ist am Zug?");
    }
    final boolean whiteToMove = "w".equals(args[1]);
    if (!(whiteToMove || "s".equals(args[1]))) {
      throw new RuntimeException("Unbekannte Farbe: '" + args[1] + "'");
    }
    final BufferedReader reader = Files.newBufferedReader(
        Paths.get(args[0]), Charset.forName("UTF-8"));
    final Schachbrett board = new Schachbrett();
    for (int lineIndex = 8; lineIndex >= 1; lineIndex--) {
      // Lines are enumerated from bottom to top, that's why the first
      // read line is the one with number 8.
      final String line = reader.readLine();
      if (line == null) {
        throw new RuntimeException("Zu wenig Zeilen!");
      }
      for (char column = 'a'; column <= 'h'; column++) {
        final char cur =
            column - 'a' >= line.length() ? ' ' : line.charAt(column - 'a');
        final Class<? extends Schachbrett.Feld> pieceClass =
            pieceMap.get(Character.toLowerCase(cur));
        if (pieceClass == null) {
          throw new RuntimeException("Nicht erlaubtes Zeichen: '" + cur + "''");
        }
        Schachbrett.Feld f;
        if (cur == ' ') {
          // leeres Feld ist nicht schwarz oder weiß
          f = pieceClass.getConstructor().newInstance();
        } else {
          f = pieceClass.getConstructor(
              Boolean.TYPE).newInstance(Character.isUpperCase(cur));
          System.out.println(f);
        }
        board.setFeld(lineIndex, column, f);
      }
    }
    reader.close();
    Set<Schachbrett.Zug> zugSet = board.moeglicheZuege(whiteToMove);
    Schachbrett.Zug[] zuege = zugSet.toArray(new Schachbrett.Zug[zugSet.size()]);
    Arrays.sort(zuege);
    for (final Schachbrett.Zug zug: zuege) {
      System.out.println(zug.toString());
    }
  }
}

Schachbrett.java:

import java.lang.Comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class Schachbrett {
  /**
   * ---------------------------------------------------------------------------
   * Variable part: Classes for the pieces on the squares.
   * ---------------------------------------------------------------------------
   *
   * Note: The constructors must be preserved.
   */

  public static class Feld {}

  /**
   * A square, on which a piece is placed.
   * The piece is either black or white.
   */
  public static abstract class Figur extends Feld {
    final boolean white;
    protected Figur(boolean white) { this.white = white; }

    public boolean isWhite() { return white; }

    public char id() {
      return getClass().getSimpleName().charAt(0);
    }
  }

  public static final class Bauer extends Figur {
    public Bauer(boolean white) { super(white); }
  }

  public static final class Laeufer extends Figur {
    public Laeufer(boolean white) { super(white); }
  }

  public static final class Springer extends Figur {
    public Springer(boolean white) { super(white); }
  }

  public static final class Turm extends Figur {
    public Turm(boolean white) { super(white); }
  }

  public static final class Dame extends Figur {
    public Dame(boolean white) { super(white); }
  }

  public static final class Koenig extends Figur {
    public Koenig(boolean white) { super(white); }
  }

  /**
   * ---------------------------------------------------------------------------
   * End variable part: Classes for the pieces on the squares.
   * ---------------------------------------------------------------------------
   */

  /**
   * Array, that holds all squares of the chessboard. Access results
   * with getFeld(line, column), see below.
   */
  private final Feld[] felder = new Feld[64];

  /**
   * Initialization: all squares empty.
   */
  {
    for (int i = 0; i < 64; ++i) {
      felder[i] = new Feld();
    }
  }

  private static int feldIndex(int line, char column) {
    return (line - 1) * 8 + ((int) column - (int) 'a');
  }

  public Feld getFeld(int line, char column) {
    return felder[feldIndex(line, column)];
  }

  public void setFeld(int line, char column, Feld value) {
    felder[feldIndex(line, column)] = value;
  }

  /**
   * A move of the piece FigurId from square (lineFrom, columnFrom) to square
   * (lineTo, columnTo)
   */
  public final class Zug implements Comparable<Zug> {
    public int lineFrom, lineTo;
    public char columnFrom, columnTo;
    public char pieceId;

    public Zug (int lineFrom, char columnFrom, int lineTo, char columnTo,
                char pieceId) {
      this.lineFrom = lineFrom; this.columnFrom = columnFrom;
      this.lineTo = lineTo; this.columnTo = columnTo;
      this.pieceId = pieceId;
    }

    @Override
    public String toString() {
      return new StringBuilder().append(pieceId).append(columnFrom).append(
          Integer.toString(lineFrom)).append('-').append(columnTo).append(
          Integer.toString(lineTo)).toString();
    }

    // required methods for sorting during the output
    @Override
    public int hashCode() {
      final int fromIndex = feldIndex(lineFrom, columnFrom);
      final int toIndex = feldIndex(lineTo, columnTo);
      int pieceIndex;
      switch(Character.toUpperCase(this.pieceId)) {
        case 'B': pieceIndex = 0; break;
        case 'S': pieceIndex = 1; break;
        case 'L': pieceIndex = 2; break;
        case 'T': pieceIndex = 3; break;
        case 'D': pieceIndex = 4; break;
        case 'K': pieceIndex = 5; break;
        default: throw new RuntimeException("Can never happen");
      }
      if (Character.isUpperCase(pieceIndex)) {
        pieceIndex = pieceIndex + 6;
      }
      // perfect hash (squareindex is at most 63 == 2^6 - 1)
      return toIndex + (fromIndex << 6) + (pieceIndex << 12);
    }

    public int compareTo(final Zug other) {
      return hashCode() - other.hashCode();
    }
  }

  public Set<Zug> moeglicheZuege(boolean whiteToMove) {
    /*
     * -------------------------------------------------------------------------
     * Variable part: algorithm
     * -------------------------------------------------------------------------
     */
     return Collections.<Zug>emptySet();
     // End
  }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!请查看帮助中心,尤其是how to ask a good question?
  • 为什么人们会提出这个问题?放弃打了就跑的技巧,而添加一些有用的东西。
  • 仅供参考:您不应该在变量名或异常消息中混用语言,甚至不应该谈论 cmets。
  • 你的颜色就在Figur.white。那么解决这个问题有什么问题呢?编辑:顺便说一句,棋子不是棋盘上的单元格,所以Figur 不应该扩展Feld,Feld 应该有一个Figur 变量,这意味着它可以容纳一个棋子(或者如果@ 987654330@)。这里只是一个 OO 错误。
  • 你在哪里迭代这一切,moeglicheZuege 几乎是空的...请提供minimal reproducible example

标签: java inheritance chess


【解决方案1】:

看起来像是一份计算机科学作业.... 但它都在那里

 public boolean isWhite() { return white; }

所以如果我理解你的问题并且你想知道黑白的表示......白色是真的,黑色是假的

【讨论】:

    【解决方案2】:

    没有 getFigur() 可以在给定的正方形上找到一块。

    因为你的方格是Feld,这是由

    确认的
    /**
     * Array, that holds all squares of the chessboard. Access results
     * with getFeld(line, column), see below.
     */
    private final Feld[] felder = new Feld[64];
    

    该类目前是每件作品的超类。

     public static abstract class Figur extends Feld {
    

    这就是你在这两个实体之间的关系上犯了错误的地方。

    • Piece 不是Square,
    • Piece 由 Square 持有。

    所以你需要更新你的关系来匹配那些陈述。

    public class Feld{
        private Figur figur;
    
        public Figur getFigur(){ return figur;}
    }
    

    像 Feld 这样的空类通常是存在问题的线索。

    然后这块不应该扩展正方形

    public class Figur {
    final boolean white;
        protected Figur(boolean white) { this.white = white; }
    
        public boolean isWhite() { return white; }
        ...
    }
    

    从那里,您将能够迭代您的电路板,并在其上(或不)获得图形

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多