Fix some Android Studio warnings.

This commit is contained in:
Peter Osterlund
2019-03-30 15:44:35 +01:00
parent 8a0a495830
commit 78b4ac2762
77 changed files with 324 additions and 664 deletions

View File

@@ -31,8 +31,8 @@ import chess.Position;
/** The main class for the chess GUI. */ /** The main class for the chess GUI. */
public class AppletGUI extends javax.swing.JApplet implements GUIInterface { public class AppletGUI extends javax.swing.JApplet implements GUIInterface {
private static final long serialVersionUID = 7357610346389734323L; private static final long serialVersionUID = 7357610346389734323L;
ChessBoardPainter cbp; private ChessBoardPainter cbp;
ChessController ctrl; private ChessController ctrl;
private final static int ttLogSize = 19; // Use 2^19 hash entries. private final static int ttLogSize = 19; // Use 2^19 hash entries.
private String moveListStr = ""; private String moveListStr = "";
private String thinkingStr = ""; private String thinkingStr = "";

View File

@@ -61,7 +61,6 @@ public class ChessBoardPainter extends JLabel {
/** /**
* Set the board to a given state. * Set the board to a given state.
* @param pos
*/ */
final public void setPosition(Position pos) { final public void setPosition(Position pos) {
this.pos = pos; this.pos = pos;
@@ -70,7 +69,6 @@ public class ChessBoardPainter extends JLabel {
/** /**
* Set/clear the board flipped status. * Set/clear the board flipped status.
* @param flipped
*/ */
final public void setFlipped(boolean flipped) { final public void setFlipped(boolean flipped) {
this.flipped = flipped; this.flipped = flipped;
@@ -227,23 +225,23 @@ public class ChessBoardPainter extends JLabel {
} }
final Move mousePressed(int sq) { final Move mousePressed(int sq) {
Move m = null;
cancelSelection = false; cancelSelection = false;
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
if ((selectedSquare >= 0) && (sq == selectedSquare)) { if ((selectedSquare >= 0) && (sq == selectedSquare)) {
int fromPiece = pos.getPiece(selectedSquare); int fromPiece = pos.getPiece(selectedSquare);
if ((fromPiece == Piece.EMPTY) || (Piece.isWhite(fromPiece) != pos.whiteMove)) { if ((fromPiece == Piece.EMPTY) || (Piece.isWhite(fromPiece) != pos.whiteMove)) {
return m; // Can't move the piece the oppenent just moved. return null; // Can't move the piece the opponent just moved.
} }
} }
if ((selectedSquare < 0) && if ((selectedSquare < 0) &&
((p == Piece.EMPTY) || (Piece.isWhite(p) != pos.whiteMove))) { ((p == Piece.EMPTY) || (Piece.isWhite(p) != pos.whiteMove))) {
return m; // You must click on one of your own pieces. return null; // You must click on one of your own pieces.
} }
activeSquare = sq; activeSquare = sq;
dragging = false; dragging = false;
dragX = dragY = -1; dragX = dragY = -1;
Move m = null;
if (selectedSquare >= 0) { if (selectedSquare >= 0) {
if (sq == selectedSquare) { if (sq == selectedSquare) {
cancelSelection = true; cancelSelection = true;

View File

@@ -22,6 +22,7 @@ import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.LineNumberReader; import java.io.LineNumberReader;
import java.util.Locale;
import uci.UCIProtocol; import uci.UCIProtocol;
import chess.ChessParseError; import chess.ChessParseError;
@@ -89,14 +90,14 @@ public class TUIGame extends Game {
try { try {
int idx = cmd.indexOf(" "); int idx = cmd.indexOf(" ");
String filename = cmd.substring(0, idx); String filename = cmd.substring(0, idx);
String timeStr = cmd.substring(idx + 1, cmd.length()); String timeStr = cmd.substring(idx + 1);
int timeLimit = Integer.parseInt(timeStr); int timeLimit = Integer.parseInt(timeStr);
// System.out.printf("file:%s time:%s (%d)\n", filename, timeStr, timeLimit); // System.out.printf("file:%s time:%s (%d)\n", filename, timeStr, timeLimit);
fr = new LineNumberReader(new FileReader(filename)); fr = new LineNumberReader(new FileReader(filename));
String line; String line;
Player pl = whitePlayer.isHumanPlayer() ? blackPlayer : whitePlayer; Player pl = whitePlayer.isHumanPlayer() ? blackPlayer : whitePlayer;
if (pl.isHumanPlayer()) { if (pl.isHumanPlayer()) {
System.out.printf("No computer player available"); System.out.print("No computer player available");
return false; return false;
} }
ComputerPlayer cp = (ComputerPlayer)pl; ComputerPlayer cp = (ComputerPlayer)pl;
@@ -178,9 +179,9 @@ public class TUIGame extends Game {
if (haveDrawOffer()) { if (haveDrawOffer()) {
moveStr += " (offer draw)"; moveStr += " (offer draw)";
} }
String msg = String.format("Last move: %d%s %s", String msg = String.format(Locale.US, "Last move: %d%s %s",
prevPos.fullMoveCounter, prevPos.whiteMove ? "." : "...", prevPos.fullMoveCounter, prevPos.whiteMove ? "." : "...",
moveStr); moveStr);
System.out.println(msg); System.out.println(msg);
} }
// System.out.printf("Hash: %016x\n", pos.zobristHash()); // System.out.printf("Hash: %016x\n", pos.zobristHash());

View File

@@ -43,37 +43,37 @@ import java.util.Random;
/** Control the search thread. */ /** Control the search thread. */
public class EngineControl { public class EngineControl {
PrintStream os; private PrintStream os;
Thread engineThread; private Thread engineThread;
private final Object threadMutex; private final Object threadMutex;
Search sc; private Search sc;
TranspositionTable tt; private TranspositionTable tt;
History ht; private History ht;
MoveGen moveGen; private MoveGen moveGen;
Position pos; private Position pos;
long[] posHashList; private long[] posHashList;
int posHashListSize; private int posHashListSize;
boolean ponder; // True if currently doing pondering private boolean ponder; // True if currently doing pondering
boolean onePossibleMove; private boolean onePossibleMove;
boolean infinite; private boolean infinite;
int minTimeLimit; private int minTimeLimit;
int maxTimeLimit; private int maxTimeLimit;
int maxDepth; private int maxDepth;
int maxNodes; private int maxNodes;
List<Move> searchMoves; private List<Move> searchMoves;
// Options // Options
int hashSizeMB = 16; private int hashSizeMB = 16;
boolean ownBook = false; private boolean ownBook = false;
boolean analyseMode = false; private boolean analyseMode = false;
boolean ponderMode = true; private boolean ponderMode = true;
// Reduced strength variables // Reduced strength variables
int strength = 1000; private int strength = 1000;
long randomSeed = 0; private long randomSeed = 0;
/** /**
* This class is responsible for sending "info" strings during search. * This class is responsible for sending "info" strings during search.
@@ -202,7 +202,7 @@ public class EngineControl {
final int margin = Math.min(1000, time * 9 / 10); final int margin = Math.min(1000, time * 9 / 10);
int timeLimit = (time + inc * (moves - 1) - margin) / moves; int timeLimit = (time + inc * (moves - 1) - margin) / moves;
minTimeLimit = (int)(timeLimit * 0.85); minTimeLimit = (int)(timeLimit * 0.85);
maxTimeLimit = (int)(minTimeLimit * (Math.max(2.5, Math.min(4.0, moves / 2)))); maxTimeLimit = (int)(minTimeLimit * (Math.max(2.5, Math.min(4.0, moves * 0.5))));
// Leave at least 1s on the clock, but can't use negative time // Leave at least 1s on the clock, but can't use negative time
minTimeLimit = clamp(minTimeLimit, 1, time - margin); minTimeLimit = clamp(minTimeLimit, 1, time - margin);
@@ -368,13 +368,13 @@ public class EngineControl {
} }
static void printOptions(PrintStream os) { static void printOptions(PrintStream os) {
os.printf("option name Hash type spin default 16 min 1 max 2048%n"); os.print("option name Hash type spin default 16 min 1 max 2048%n");
os.printf("option name OwnBook type check default false%n"); os.print("option name OwnBook type check default false%n");
os.printf("option name Ponder type check default true%n"); os.print("option name Ponder type check default true%n");
os.printf("option name UCI_AnalyseMode type check default false%n"); os.print("option name UCI_AnalyseMode type check default false%n");
os.printf("option name UCI_EngineAbout type string default %s by Peter Osterlund, see http://web.comhem.se/petero2home/javachess/index.html%n", os.printf("option name UCI_EngineAbout type string default %s by Peter Osterlund, see http://web.comhem.se/petero2home/javachess/index.html%n",
ComputerPlayer.engineName); ComputerPlayer.engineName);
os.printf("option name Strength type spin default 1000 min 0 max 1000\n"); os.print("option name Strength type spin default 1000 min 0 max 1000\n");
for (String pName : Parameters.instance().getParamNames()) { for (String pName : Parameters.instance().getParamNames()) {
ParamBase p = Parameters.instance().getParam(pName); ParamBase p = Parameters.instance().getParam(pName);
@@ -396,7 +396,7 @@ public class EngineControl {
os.printf("option name %s type combo default %s ", cp.name, cp.defaultValue); os.printf("option name %s type combo default %s ", cp.name, cp.defaultValue);
for (String s : cp.allowedValues) for (String s : cp.allowedValues)
os.printf(" var %s", s); os.printf(" var %s", s);
os.printf("\n"); os.print("\n");
break; break;
} }
case BUTTON: case BUTTON:
@@ -428,7 +428,7 @@ public class EngineControl {
} else { } else {
Parameters.instance().set(optionName, optionValue); Parameters.instance().set(optionName, optionValue);
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }
} }

View File

@@ -33,14 +33,14 @@ import java.util.ArrayList;
/** Handle the UCI protocol mode. */ /** Handle the UCI protocol mode. */
public class UCIProtocol { public class UCIProtocol {
// Data set by the "position" command. // Data set by the "position" command.
Position pos; private Position pos;
ArrayList<Move> moves; private ArrayList<Move> moves;
// Engine data // Engine data
EngineControl engine; private EngineControl engine;
// Set to true to break out of main loop // Set to true to break out of main loop
boolean quit; private boolean quit;
public static void main(boolean autoStart) { public static void main(boolean autoStart) {
@@ -54,7 +54,7 @@ public class UCIProtocol {
quit = false; quit = false;
} }
final public void mainLoop(InputStream is, PrintStream os, boolean autoStart) { private void mainLoop(InputStream is, PrintStream os, boolean autoStart) {
try { try {
if (autoStart) { if (autoStart) {
handleCommand("uci", os); handleCommand("uci", os);
@@ -73,7 +73,7 @@ public class UCIProtocol {
} }
} }
final void handleCommand(String cmdLine, PrintStream os) { private void handleCommand(String cmdLine, PrintStream os) {
String[] tokens = tokenize(cmdLine); String[] tokens = tokenize(cmdLine);
try { try {
String cmd = tokens[0]; String cmd = tokens[0];
@@ -199,9 +199,9 @@ public class UCIProtocol {
} }
quit = true; quit = true;
} }
} catch (ChessParseError ex) { } catch (ChessParseError ignore) {
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException ignore) {
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }

View File

@@ -31,11 +31,11 @@ public class UCIProtocolTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
@Before @Before

View File

@@ -87,7 +87,6 @@ public class ChessBoard extends View {
/** /**
* Set the board to a given state. * Set the board to a given state.
* @param pos
*/ */
final public void setPosition(Position pos) { final public void setPosition(Position pos) {
this.pos = pos; this.pos = pos;
@@ -96,7 +95,6 @@ public class ChessBoard extends View {
/** /**
* Set/clear the board flipped status. * Set/clear the board flipped status.
* @param flipped
*/ */
final public void setFlipped(boolean flipped) { final public void setFlipped(boolean flipped) {
this.flipped = flipped; this.flipped = flipped;

View File

@@ -106,7 +106,7 @@ public class CuckooChess extends Activity implements GUIInterface {
ctrl = new ChessController(this); ctrl = new ChessController(this);
ctrl.setThreadStackSize(32768); ctrl.setThreadStackSize(32768);
readPrefs(); readPrefs();
Typeface chessFont = Typeface.createFromAsset(getAssets(), "casefont.ttf"); Typeface chessFont = Typeface.createFromAsset(getAssets(), "casefont.ttf");
cb.setFont(chessFont); cb.setFont(chessFont);
cb.setFocusable(true); cb.setFocusable(true);
@@ -297,8 +297,7 @@ public class CuckooChess extends Activity implements GUIInterface {
ctrl.reportPromotePiece(item); ctrl.reportPromotePiece(item);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case CLIPBOARD_DIALOG: { case CLIPBOARD_DIALOG: {
final CharSequence[] items = {"Copy Game", "Copy Position", "Paste"}; final CharSequence[] items = {"Copy Game", "Copy Position", "Paste"};
@@ -334,8 +333,7 @@ public class CuckooChess extends Activity implements GUIInterface {
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
} }
return null; return null;

View File

@@ -18,12 +18,8 @@
package chess; package chess;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;

View File

@@ -40,16 +40,16 @@ public class ComputerPlayer implements Player {
engineName = name; engineName = name;
} }
int minTimeMillis; private int minTimeMillis;
int maxTimeMillis; int maxTimeMillis;
int maxDepth; int maxDepth;
int maxNodes; private int maxNodes;
public boolean verbose; public boolean verbose;
TranspositionTable tt; private TranspositionTable tt;
Book book; private Book book;
boolean bookEnabled; private boolean bookEnabled;
boolean randomMode; private boolean randomMode;
Search currentSearch; private Search currentSearch;
public ComputerPlayer() { public ComputerPlayer() {
minTimeMillis = 10000; minTimeMillis = 10000;
@@ -67,7 +67,7 @@ public class ComputerPlayer implements Player {
tt = new TranspositionTable(logSize); tt = new TranspositionTable(logSize);
} }
Search.Listener listener; private Search.Listener listener;
public void setListener(Search.Listener listener) { public void setListener(Search.Listener listener) {
this.listener = listener; this.listener = listener;
} }
@@ -107,7 +107,7 @@ public class ComputerPlayer implements Player {
currentSearch = sc; currentSearch = sc;
sc.setListener(listener); sc.setListener(listener);
Move bestM; Move bestM;
if ((moves.size == 1) && (canClaimDraw(pos, posHashList, posHashListSize, moves.m[0]) == "")) { if ((moves.size == 1) && canClaimDraw(pos, posHashList, posHashListSize, moves.m[0]).isEmpty()) {
bestM = moves.m[0]; bestM = moves.m[0];
bestM.score = 0; bestM.score = 0;
} else if (randomMode) { } else if (randomMode) {
@@ -123,7 +123,7 @@ public class ComputerPlayer implements Player {
// Claim draw if appropriate // Claim draw if appropriate
if (bestM.score <= 0) { if (bestM.score <= 0) {
String drawClaim = canClaimDraw(pos, posHashList, posHashListSize, bestM); String drawClaim = canClaimDraw(pos, posHashList, posHashListSize, bestM);
if (drawClaim != "") if (!drawClaim.isEmpty())
strMove = drawClaim; strMove = drawClaim;
} }
return strMove; return strMove;

View File

@@ -340,7 +340,7 @@ public class Evaluate {
// Knights // Knights
{ {
final int t1 = qV + 2 * rV + 1 * bV + 1 * nV + 6 * pV; final int t1 = qV + 2 * rV + bV + nV + 6 * pV;
final int t2 = nV + 8 * pV; final int t2 = nV + 8 * pV;
int n1 = pos.psScore1[Piece.WKNIGHT]; int n1 = pos.psScore1[Piece.WKNIGHT];
int n2 = pos.psScore2[Piece.WKNIGHT]; int n2 = pos.psScore2[Piece.WKNIGHT];

View File

@@ -26,12 +26,12 @@ import java.util.Locale;
public class Game { public class Game {
protected List<Move> moveList = null; protected List<Move> moveList = null;
protected List<UndoInfo> uiInfoList = null; protected List<UndoInfo> uiInfoList = null;
List<Boolean> drawOfferList = null; private List<Boolean> drawOfferList = null;
protected int currentMove; protected int currentMove;
boolean pendingDrawOffer; boolean pendingDrawOffer;
GameState drawState; GameState drawState;
String drawStateMoveStr; // Move required to claim DRAW_REP or DRAW_50 private String drawStateMoveStr; // Move required to claim DRAW_REP or DRAW_50
GameState resignState; private GameState resignState;
public Position pos = null; public Position pos = null;
protected Player whitePlayer; protected Player whitePlayer;
protected Player blackPlayer; protected Player blackPlayer;
@@ -373,10 +373,7 @@ public class Game {
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();
pos.makeMove(move, ui); pos.makeMove(move, ui);
} }
if ((whiteMove.length() > 0) || (blackMove.length() > 0)) { if (whiteMove.length() > 0) {
if (whiteMove.length() == 0) {
whiteMove = "...";
}
if (compressed) { if (compressed) {
ret.append(String.format(Locale.US, "%d. %s %s ", ret.append(String.format(Locale.US, "%d. %s %s ",
pos.fullMoveCounter, whiteMove, blackMove)); pos.fullMoveCounter, whiteMove, blackMove));

View File

@@ -773,12 +773,12 @@ public final class MoveGen {
switch (d1) { switch (d1) {
case 8: case -8: case 1: case -1: // Rook direction case 8: case -8: case 1: case -1: // Rook direction
if ((p == Piece.WQUEEN) || (p == Piece.WROOK)) if ((p == Piece.WQUEEN) || (p == Piece.WROOK))
if ((d1 != 0) && (MoveGen.nextPiece(pos, m.to, d1) == oKing)) if (MoveGen.nextPiece(pos, m.to, d1) == oKing)
return true; return true;
break; break;
case 9: case 7: case -9: case -7: // Bishop direction case 9: case 7: case -9: case -7: // Bishop direction
if ((p == Piece.WQUEEN) || (p == Piece.WBISHOP)) { if ((p == Piece.WQUEEN) || (p == Piece.WBISHOP)) {
if ((d1 != 0) && (MoveGen.nextPiece(pos, m.to, d1) == oKing)) if (MoveGen.nextPiece(pos, m.to, d1) == oKing)
return true; return true;
} else if (p == Piece.WPAWN) { } else if (p == Piece.WPAWN) {
if (((d1 > 0) == wtm) && (pos.getPiece(m.to + d1) == oKing)) if (((d1 > 0) == wtm) && (pos.getPiece(m.to + d1) == oKing))

View File

@@ -5,7 +5,7 @@ import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
public class Parameters { public class Parameters {
public static enum Type { public enum Type {
CHECK, CHECK,
SPIN, SPIN,
COMBO, COMBO,
@@ -115,8 +115,7 @@ public class Parameters {
return ((CheckParam)params.get(name.toLowerCase())).value; return ((CheckParam)params.get(name.toLowerCase())).value;
} }
final int getIntPar(String name) { final int getIntPar(String name) {
int ret = ((SpinParam)params.get(name.toLowerCase())).value; return ((SpinParam)params.get(name.toLowerCase())).value;
return ret;
} }
final String getStringPar(String name) { final String getStringPar(String name) {
return ((StringParam)params.get(name.toLowerCase())).value; return ((StringParam)params.get(name.toLowerCase())).value;
@@ -141,7 +140,7 @@ public class Parameters {
int val = Integer.parseInt(value); int val = Integer.parseInt(value);
if ((val >= sp.minValue) && (val <= sp.maxValue)) if ((val >= sp.minValue) && (val <= sp.maxValue))
sp.value = val; sp.value = val;
} catch (NumberFormatException ex) { } catch (NumberFormatException ignore) {
} }
break; break;
} }

View File

@@ -307,7 +307,7 @@ public class Position {
* Set a square to a piece value. * Set a square to a piece value.
* Special version that only updates enough of the state for the SEE function to be happy. * Special version that only updates enough of the state for the SEE function to be happy.
*/ */
public final void setSEEPiece(int square, int piece) { private void setSEEPiece(int square, int piece) {
int removedPiece = squares[square]; int removedPiece = squares[square];
// Update board // Update board

View File

@@ -396,13 +396,12 @@ public class TextIO {
* @return A move object, or null if move has invalid syntax * @return A move object, or null if move has invalid syntax
*/ */
public static Move uciStringToMove(String move) { public static Move uciStringToMove(String move) {
Move m = null;
if ((move.length() < 4) || (move.length() > 5)) if ((move.length() < 4) || (move.length() > 5))
return m; return null;
int fromSq = TextIO.getSquare(move.substring(0, 2)); int fromSq = TextIO.getSquare(move.substring(0, 2));
int toSq = TextIO.getSquare(move.substring(2, 4)); int toSq = TextIO.getSquare(move.substring(2, 4));
if ((fromSq < 0) || (toSq < 0)) { if ((fromSq < 0) || (toSq < 0)) {
return m; return null;
} }
char prom = ' '; char prom = ' ';
boolean white = true; boolean white = true;
@@ -413,7 +412,7 @@ public class TextIO {
} else if (Position.getY(toSq) == 0) { } else if (Position.getY(toSq) == 0) {
white = false; white = false;
} else { } else {
return m; return null;
} }
} }
int promoteTo; int promoteTo;
@@ -434,20 +433,15 @@ public class TextIO {
promoteTo = white ? Piece.WKNIGHT : Piece.BKNIGHT; promoteTo = white ? Piece.WKNIGHT : Piece.BKNIGHT;
break; break;
default: default:
return m; return null;
} }
m = new Move(fromSq, toSq, promoteTo); return new Move(fromSq, toSq, promoteTo);
return m;
} }
private static boolean isCapture(Position pos, Move move) { private static boolean isCapture(Position pos, Move move) {
if (pos.getPiece(move.to) == Piece.EMPTY) { if (pos.getPiece(move.to) == Piece.EMPTY) {
int p = pos.getPiece(move.from); int p = pos.getPiece(move.from);
if ((p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare())) { return (p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare());
return true;
} else {
return false;
}
} else { } else {
return true; return true;
} }
@@ -460,9 +454,8 @@ public class TextIO {
*/ */
public static Move stringToMove(Position pos, String strMove) { public static Move stringToMove(Position pos, String strMove) {
strMove = strMove.replaceAll("=", ""); strMove = strMove.replaceAll("=", "");
Move move = null;
if (strMove.length() == 0) if (strMove.length() == 0)
return move; return null;
MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos); MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos, moves); MoveGen.removeIllegal(pos, moves);
{ {
@@ -501,7 +494,8 @@ public class TextIO {
} }
} }
} }
Move move = null;
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
// Search for unique substring match // Search for unique substring match
for (int mi = 0; mi < moves.size; mi++) { for (int mi = 0; mi < moves.size; mi++) {
@@ -526,7 +520,7 @@ public class TextIO {
if (move != null) if (move != null)
return move; return move;
} }
return move; return null;
} }
/** /**

View File

@@ -107,9 +107,9 @@ public class TranspositionTable {
depthSlot |= (s << 15); depthSlot |= (s << 15);
} }
} }
TTEntry[] table; private TTEntry[] table;
TTEntry emptySlot; private TTEntry emptySlot;
byte generation; private byte generation;
/** Constructor. Creates an empty transposition table with numEntries slots. */ /** Constructor. Creates an empty transposition table with numEntries slots. */
public TranspositionTable(int log2Size) { public TranspositionTable(int log2Size) {

View File

@@ -37,7 +37,7 @@ import chess.TranspositionTable.TTEntry;
public final class TreeLogger { public final class TreeLogger {
private byte[] entryBuffer = new byte[16]; private byte[] entryBuffer = new byte[16];
private ByteBuffer bb = ByteBuffer.wrap(entryBuffer); private ByteBuffer bb = ByteBuffer.wrap(entryBuffer);
// Used in write mode // Used in write mode
private FileOutputStream os = null; private FileOutputStream os = null;
private BufferedOutputStream bos = null; private BufferedOutputStream bos = null;
@@ -96,7 +96,7 @@ public final class TreeLogger {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(); throw new RuntimeException();
} finally { } finally {
if (raf != null) try { raf.close(); } catch (IOException e) {} if (raf != null) try { raf.close(); } catch (IOException ignore) {}
} }
} }
@@ -104,7 +104,7 @@ public final class TreeLogger {
try { try {
if (bos != null) bos.close(); if (bos != null) bos.close();
if (fc != null) fc.close(); if (fc != null) fc.close();
} catch (IOException e) { } catch (IOException ignore) {
} }
} }
@@ -143,7 +143,7 @@ public final class TreeLogger {
/** /**
* Log information when entering a search node. * Log information when entering a search node.
* @param parentId Index of parent node. * @param parentIndex Index of parent node.
* @param m Move made to go from parent node to this node * @param m Move made to go from parent node to this node
* @param alpha Search parameter * @param alpha Search parameter
* @param beta Search parameter * @param beta Search parameter
@@ -199,7 +199,7 @@ public final class TreeLogger {
private void computeForwardPointers() { private void computeForwardPointers() {
if ((mapBuf.get(127) & (1<<7)) != 0) if ((mapBuf.get(127) & (1<<7)) != 0)
return; return;
System.out.printf("Computing forward pointers...\n"); System.out.print("Computing forward pointers...\n");
StartEntry se = new StartEntry(); StartEntry se = new StartEntry();
EndEntry ee = new EndEntry(); EndEntry ee = new EndEntry();
for (int i = 0; i < numEntries; i++) { for (int i = 0; i < numEntries; i++) {
@@ -296,7 +296,7 @@ public final class TreeLogger {
ArrayList<Move> moves = getMoveSequence(currIndex); ArrayList<Move> moves = getMoveSequence(currIndex);
for (Move m : moves) for (Move m : moves)
System.out.printf(" %s", TextIO.moveToUCIString(m)); System.out.printf(" %s", TextIO.moveToUCIString(m));
System.out.printf("\n"); System.out.print("\n");
printNodeInfo(rootPos, currIndex); printNodeInfo(rootPos, currIndex);
Position pos = getPosition(rootPos, currIndex); Position pos = getPosition(rootPos, currIndex);
System.out.print(TextIO.asciiBoard(pos)); System.out.print(TextIO.asciiBoard(pos));
@@ -309,7 +309,7 @@ public final class TreeLogger {
} }
} }
doPrint = true; doPrint = true;
System.out.printf("Command:"); System.out.print("Command:");
String cmdStr = in.readLine(); String cmdStr = in.readLine();
if (cmdStr == null) if (cmdStr == null)
return; return;
@@ -332,10 +332,10 @@ public final class TreeLogger {
found.add(c); found.add(c);
} }
if (found.size() == 0) { if (found.size() == 0) {
System.out.printf("No such move\n"); System.out.print("No such move\n");
doPrint = false; doPrint = false;
} else if (found.size() > 1) { } else if (found.size() > 1) {
System.out.printf("Ambiguous move\n"); System.out.print("Ambiguous move\n");
for (Integer c : found) for (Integer c : found)
printNodeInfo(rootPos, c); printNodeInfo(rootPos, c);
doPrint = false; doPrint = false;
@@ -370,7 +370,7 @@ public final class TreeLogger {
ArrayList<Move> moves = getMoveSequence(currIndex); ArrayList<Move> moves = getMoveSequence(currIndex);
for (Move m : moves) for (Move m : moves)
System.out.printf(" %s", TextIO.moveToUCIString(m)); System.out.printf(" %s", TextIO.moveToUCIString(m));
System.out.printf("\n"); System.out.print("\n");
doPrint = false; doPrint = false;
} else if (cmdStr.startsWith("h")) { } else if (cmdStr.startsWith("h")) {
long hashKey = getPosition(rootPos, currIndex).historyHash(); long hashKey = getPosition(rootPos, currIndex).historyHash();
@@ -384,7 +384,7 @@ public final class TreeLogger {
int i = Integer.parseInt(cmdStr); int i = Integer.parseInt(cmdStr);
if ((i >= -1) && (i < numEntries)) if ((i >= -1) && (i < numEntries))
currIndex = i; currIndex = i;
} catch (NumberFormatException e) { } catch (NumberFormatException ignore) {
} }
} }
prevStr = cmdStr; prevStr = cmdStr;
@@ -437,7 +437,7 @@ public final class TreeLogger {
s = s.substring(2); s = s.substring(2);
try { try {
key = Long.parseLong(s, 16); key = Long.parseLong(s, 16);
} catch (NumberFormatException e) { } catch (NumberFormatException ignore) {
} }
} }
return key; return key;
@@ -450,13 +450,13 @@ public final class TreeLogger {
if (idx > 0) { if (idx > 0) {
return Integer.parseInt(s.substring(idx+1)); return Integer.parseInt(s.substring(idx+1));
} }
} catch (NumberFormatException e) { } catch (NumberFormatException ignore) {
} }
return defVal; return defVal;
} }
/** Get a list of integer parameters from an input string. */ /** Get a list of integer parameters from an input string. */
final ArrayList<Integer> getArgs(String s, int defVal) { private ArrayList<Integer> getArgs(String s, int defVal) {
ArrayList<Integer> ret = new ArrayList<>(); ArrayList<Integer> ret = new ArrayList<>();
String[] split = s.split(" "); String[] split = s.split(" ");
try { try {
@@ -612,7 +612,7 @@ public final class TreeLogger {
System.out.printf(" s:%s%6d e:%6d sub:%d", type, ee.score, ee.evalScore, System.out.printf(" s:%s%6d e:%6d sub:%d", type, ee.score, ee.evalScore,
subTreeNodes); subTreeNodes);
} }
System.out.printf("\n"); System.out.print("\n");
} }
} }
} }

View File

@@ -41,16 +41,16 @@ import java.util.Scanner;
/** The glue between the chess engine and the GUI. */ /** The glue between the chess engine and the GUI. */
public class ChessController { public class ChessController {
Player humanPlayer; private Player humanPlayer;
ComputerPlayer computerPlayer; private ComputerPlayer computerPlayer;
Game game; Game game;
GUIInterface gui; private GUIInterface gui;
boolean humanIsWhite; private boolean humanIsWhite;
Thread computerThread; private Thread computerThread;
int threadStack; // Thread stack size, or zero to use OS default private int threadStack; // Thread stack size, or zero to use OS default
// Search statistics // Search statistics
String thinkingPV; private String thinkingPV;
class SearchListener implements Search.Listener { class SearchListener implements Search.Listener {
int currDepth = 0; int currDepth = 0;
@@ -133,7 +133,7 @@ public class ChessController {
setSearchInfo(); setSearchInfo();
} }
} }
SearchListener listener; private SearchListener listener;
public ChessController(GUIInterface gui) { public ChessController(GUIInterface gui) {
this.gui = gui; this.gui = gui;
@@ -172,10 +172,8 @@ public class ChessController {
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
game.processString("new"); game.processString("new");
game.pos = pos; game.pos = pos;
String[] strArr = posHistStr.get(1).split(" "); for (String s : posHistStr.get(1).split(" ")) {
final int arrLen = strArr.length; game.processString(s);
for (int i = 0; i < arrLen; i++) {
game.processString(strArr[i]);
} }
int numUndo = Integer.parseInt(posHistStr.get(2)); int numUndo = Integer.parseInt(posHistStr.get(2));
for (int i = 0; i < numUndo; i++) { for (int i = 0; i < numUndo; i++) {
@@ -223,11 +221,9 @@ public class ChessController {
pgn.append("[SetUp \"1\"]\n"); pgn.append("[SetUp \"1\"]\n");
} }
pgn.append("\n"); pgn.append("\n");
String[] strArr = moves.split(" ");
int currLineLength = 0; int currLineLength = 0;
final int arrLen = strArr.length; for (String s : moves.split(" ")) {
for (int i = 0; i < arrLen; i++) { String move = s.trim();
String move = strArr[i].trim();
int moveLen = move.length(); int moveLen = move.length();
if (moveLen > 0) { if (moveLen > 0) {
if (currLineLength + 1 + moveLen >= 80) { if (currLineLength + 1 + moveLen >= 80) {
@@ -408,7 +404,7 @@ public class ChessController {
} }
} }
Move promoteMove; private Move promoteMove;
public final void reportPromotePiece(int choice) { public final void reportPromotePiece(int choice) {
final boolean white = game.pos.whiteMove; final boolean white = game.pos.whiteMove;
int promoteTo; int promoteTo;
@@ -482,7 +478,7 @@ public class ChessController {
gui.setMoveListString(str); gui.setMoveListString(str);
} }
public final void setThinkingPV() { private void setThinkingPV() {
String str = ""; String str = "";
if (gui.showThinking()) { if (gui.showThinking()) {
str = thinkingPV; str = thinkingPV;

View File

@@ -29,16 +29,15 @@ public class BitBoardTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/** Test of kingAttacks, of class BitBoard. */
@Test @Test
public void testKingAttacks() throws ChessParseError { public void testKingAttacks() {
System.out.println("kingAttacks"); System.out.println("kingAttacks");
assertEquals(5, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("g1")])); assertEquals(5, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("g1")]));
assertEquals(3, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("h1")])); assertEquals(3, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("h1")]));
@@ -49,9 +48,8 @@ public class BitBoardTest {
assertEquals(8, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("b2")])); assertEquals(8, Long.bitCount(BitBoard.kingAttacks[TextIO.getSquare("b2")]));
} }
/** Test of knightAttacks, of class BitBoard. */
@Test @Test
public void testKnightAttacks() throws ChessParseError { public void testKnightAttacks() {
System.out.println("knightAttacks"); System.out.println("knightAttacks");
assertEquals(3, Long.bitCount(BitBoard.knightAttacks[TextIO.getSquare("g1")])); assertEquals(3, Long.bitCount(BitBoard.knightAttacks[TextIO.getSquare("g1")]));
assertEquals(2, Long.bitCount(BitBoard.knightAttacks[TextIO.getSquare("a1")])); assertEquals(2, Long.bitCount(BitBoard.knightAttacks[TextIO.getSquare("a1")]));
@@ -65,9 +63,8 @@ public class BitBoardTest {
BitBoard.knightAttacks[TextIO.getSquare("g1")]); BitBoard.knightAttacks[TextIO.getSquare("g1")]);
} }
/** Test of squaresBetween[][], of class BitBoard. */
@Test @Test
public void testSquaresBetween() throws ChessParseError { public void testSquaresBetween() {
System.out.println("squaresBetween"); System.out.println("squaresBetween");
// Tests that the set of nonzero elements is correct // Tests that the set of nonzero elements is correct
for (int sq1 = 0; sq1 < 64; sq1++) { for (int sq1 = 0; sq1 < 64; sq1++) {

View File

@@ -29,16 +29,13 @@ public class BookTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of getBookMove method, of class Book.
*/
@Test @Test
public void testGetBookMove() throws ChessParseError { public void testGetBookMove() throws ChessParseError {
System.out.println("getBookMove"); System.out.println("getBookMove");
@@ -48,9 +45,6 @@ public class BookTest {
checkValid(pos, move); checkValid(pos, move);
} }
/**
* Test of getAllBookMoves method, of class Book.
*/
@Test @Test
public void testGetAllBookMoves() throws ChessParseError { public void testGetAllBookMoves() throws ChessParseError {
System.out.println("getAllBookMoves"); System.out.println("getAllBookMoves");
@@ -67,7 +61,7 @@ public class BookTest {
/** Check that move is a legal move in position pos. */ /** Check that move is a legal move in position pos. */
private void checkValid(Position pos, Move move) { private void checkValid(Position pos, Move move) {
assertTrue(move != null); assertNotNull(move);
MoveGen.MoveList moveList = new MoveGen().pseudoLegalMoves(pos); MoveGen.MoveList moveList = new MoveGen().pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos, moveList); MoveGen.removeIllegal(pos, moveList);
boolean contains = false; boolean contains = false;

View File

@@ -30,16 +30,13 @@ public class ComputerPlayerTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of getCommand method, of class ComputerPlayer.
*/
@Test @Test
public void testGetCommand() throws ChessParseError { public void testGetCommand() throws ChessParseError {
System.out.println("getCommand"); System.out.println("getCommand");
@@ -71,11 +68,8 @@ public class ComputerPlayerTest {
assertEquals("Kxg8", result); assertEquals("Kxg8", result);
} }
/**
* Test of draw by repetition, of class ComputerPlayer.
*/
@Test @Test
public void testDrawRep() throws ChessParseError { public void testDrawRep() {
System.out.println("drawRep"); System.out.println("drawRep");
Game game = new Game(new HumanPlayer(), new HumanPlayer()); Game game = new Game(new HumanPlayer(), new HumanPlayer());
ComputerPlayer cp = new ComputerPlayer(); ComputerPlayer cp = new ComputerPlayer();

View File

@@ -36,9 +36,6 @@ public class EvaluateTest {
public static void tearDownClass() throws Exception { public static void tearDownClass() throws Exception {
} }
/**
* Test of evalPos method, of class Evaluate.
*/
@Test @Test
public void testEvalPos() throws ChessParseError { public void testEvalPos() throws ChessParseError {
System.out.println("evalPos"); System.out.println("evalPos");
@@ -102,9 +99,6 @@ public class EvaluateTest {
assertTrue(sc2 > sc1); assertTrue(sc2 > sc1);
} }
/**
* Test of pieceSquareEval method, of class Evaluate.
*/
@Test @Test
public void testPieceSquareEval() throws ChessParseError { public void testPieceSquareEval() throws ChessParseError {
System.out.println("pieceSquareEval"); System.out.println("pieceSquareEval");
@@ -143,9 +137,6 @@ public class EvaluateTest {
assertTrue(score > 100); // Two rooks on 7:th rank is very good assertTrue(score > 100); // Two rooks on 7:th rank is very good
} }
/**
* Test of tradeBonus method, of class Evaluate.
*/
@Test @Test
public void testTradeBonus() throws ChessParseError { public void testTradeBonus() throws ChessParseError {
System.out.println("tradeBonus"); System.out.println("tradeBonus");
@@ -172,9 +163,6 @@ public class EvaluateTest {
assertTrue(score2 > score1); // White ahead, trading pieces is good assertTrue(score2 > score1); // White ahead, trading pieces is good
} }
/**
* Test of material method, of class Evaluate.
*/
@Test @Test
public void testMaterial() throws ChessParseError { public void testMaterial() throws ChessParseError {
System.out.println("material"); System.out.println("material");
@@ -204,9 +192,6 @@ public class EvaluateTest {
assertEquals(-pV+qV, Evaluate.material(pos)); assertEquals(-pV+qV, Evaluate.material(pos));
} }
/**
* Test of kingSafety method, of class Evaluate.
*/
@Test @Test
public void testKingSafety() throws ChessParseError { public void testKingSafety() throws ChessParseError {
System.out.println("kingSafety"); System.out.println("kingSafety");
@@ -233,9 +218,6 @@ public class EvaluateTest {
assertTrue(s2 < s1); assertTrue(s2 < s1);
} }
/**
* Test of endGameEval method, of class Evaluate.
*/
@Test @Test
public void testEndGameEval() throws ChessParseError { public void testEndGameEval() throws ChessParseError {
System.out.println("endGameEval"); System.out.println("endGameEval");
@@ -312,9 +294,6 @@ public class EvaluateTest {
assertTrue(score > 0); assertTrue(score > 0);
} }
/**
* Test of endGameEval method, of class Evaluate.
*/
@Test @Test
public void testPassedPawns() throws ChessParseError { public void testPassedPawns() throws ChessParseError {
System.out.println("passedPawns"); System.out.println("passedPawns");
@@ -341,9 +320,6 @@ public class EvaluateTest {
// assertTrue(score2 > score); // Advancing passed pawn is good // assertTrue(score2 > score); // Advancing passed pawn is good
} }
/**
* Test of endGameEval method, of class Evaluate.
*/
@Test @Test
public void testBishAndRookPawns() throws ChessParseError { public void testBishAndRookPawns() throws ChessParseError {
System.out.println("bishAndRookPawns"); System.out.println("bishAndRookPawns");
@@ -394,9 +370,6 @@ public class EvaluateTest {
assertTrue(evalWhite(pos) > 0); // Black has trapped bishop assertTrue(evalWhite(pos) > 0); // Black has trapped bishop
} }
/**
* Test of endGameEval method, of class Evaluate.
*/
@Test @Test
public void testKQKP() throws ChessParseError { public void testKQKP() throws ChessParseError {
System.out.println("KQKP"); System.out.println("KQKP");

View File

@@ -29,16 +29,13 @@ public class GameTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of haveDrawOffer method, of class Game.
*/
@Test @Test
public void testHaveDrawOffer() { public void testHaveDrawOffer() {
System.out.println("haveDrawOffer"); System.out.println("haveDrawOffer");
@@ -129,9 +126,6 @@ public class GameTest {
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
} }
/**
* Test of draw by 50 move rule, of class Game.
*/
@Test @Test
public void testDraw50() { public void testDraw50() {
System.out.println("draw50"); System.out.println("draw50");
@@ -188,9 +182,6 @@ public class GameTest {
assertEquals(Game.GameState.ALIVE, game.drawState); assertEquals(Game.GameState.ALIVE, game.drawState);
} }
/**
* Test of draw by repetition, of class Game.
*/
@Test @Test
public void testDrawRep() { public void testDrawRep() {
System.out.println("drawRep"); System.out.println("drawRep");
@@ -262,9 +253,6 @@ public class GameTest {
assertEquals(Game.GameState.DRAW_REP, game.getGameState()); assertEquals(Game.GameState.DRAW_REP, game.getGameState());
} }
/**
* Test of resign command, of class Game.
*/
@Test @Test
public void testResign() { public void testResign() {
System.out.println("resign"); System.out.println("resign");
@@ -289,9 +277,6 @@ public class GameTest {
assertEquals(Game.GameState.BLACK_MATE, game.getGameState()); // Can't resign after game over assertEquals(Game.GameState.BLACK_MATE, game.getGameState()); // Can't resign after game over
} }
/**
* Test of processString method, of class Game.
*/
@Test @Test
public void testProcessString() throws ChessParseError { public void testProcessString() throws ChessParseError {
System.out.println("processString"); System.out.println("processString");
@@ -344,9 +329,6 @@ public class GameTest {
assertEquals(false, res); assertEquals(false, res);
} }
/**
* Test of getGameState method, of class Game.
*/
@Test @Test
public void testGetGameState() { public void testGetGameState() {
System.out.println("getGameState"); System.out.println("getGameState");
@@ -362,9 +344,6 @@ public class GameTest {
assertEquals(Game.GameState.BLACK_STALEMATE, game.getGameState()); assertEquals(Game.GameState.BLACK_STALEMATE, game.getGameState());
} }
/**
* Test of insufficientMaterial method, of class Game.
*/
@Test @Test
public void testInsufficientMaterial() { public void testInsufficientMaterial() {
System.out.println("insufficientMaterial"); System.out.println("insufficientMaterial");
@@ -407,9 +386,6 @@ public class GameTest {
assertEquals(Game.GameState.ALIVE, game.getGameState()); assertEquals(Game.GameState.ALIVE, game.getGameState());
} }
/**
* Test of perfT method, of class Game.
*/
@Test @Test
public void testPerfT() { public void testPerfT() {
System.out.println("perfT"); System.out.println("perfT");

View File

@@ -31,11 +31,11 @@ public class HistoryTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
@Before @Before
@@ -46,9 +46,6 @@ public class HistoryTest {
public void tearDown() { public void tearDown() {
} }
/**
* Test of getHistScore method, of class History.
*/
@Test @Test
public void testGetHistScore() throws ChessParseError { public void testGetHistScore() throws ChessParseError {
System.out.println("getHistScore"); System.out.println("getHistScore");

View File

@@ -29,16 +29,13 @@ public class KillerTableTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of addKiller method, of class KillerTable.
*/
@Test @Test
public void testAddKiller() { public void testAddKiller() {
System.out.println("addKiller"); System.out.println("addKiller");
@@ -50,9 +47,6 @@ public class KillerTableTest {
kt.addKiller(3, m); kt.addKiller(3, m);
} }
/**
* Test of getKillerScore method, of class KillerTable.
*/
@Test @Test
public void testGetKillerScore() { public void testGetKillerScore() {
System.out.println("getKillerScore"); System.out.println("getKillerScore");

View File

@@ -31,16 +31,13 @@ public class MoveGenTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of pseudoLegalMoves method, of class MoveGen.
*/
@Test @Test
public void testPseudoLegalMoves() throws ChessParseError { public void testPseudoLegalMoves() throws ChessParseError {
System.out.println("pseudoLegalMoves"); System.out.println("pseudoLegalMoves");
@@ -86,9 +83,6 @@ public class MoveGenTest {
assertTrue(strMoves.contains("e1c1")); assertTrue(strMoves.contains("e1c1"));
} }
/**
* Test of pseudoLegalMoves method, of class MoveGen. Pawn moves.
*/
@Test @Test
public void testPawnMoves() throws ChessParseError { public void testPawnMoves() throws ChessParseError {
System.out.println("pawnMoves"); System.out.println("pawnMoves");
@@ -128,9 +122,6 @@ public class MoveGenTest {
assertTrue(strMoves.contains("a2a1b")); assertTrue(strMoves.contains("a2a1b"));
} }
/**
* Test of inCheck method, of class MoveGen.
*/
@Test @Test
public void testInCheck() { public void testInCheck() {
System.out.println("inCheck"); System.out.println("inCheck");
@@ -163,9 +154,6 @@ public class MoveGenTest {
assertEquals(false, MoveGen.inCheck(pos)); assertEquals(false, MoveGen.inCheck(pos));
} }
/**
* Test of givesCheck method, of class MoveGen.
*/
@Test @Test
public void testGivesCheck() throws ChessParseError { public void testGivesCheck() throws ChessParseError {
System.out.println("givesCheck"); System.out.println("givesCheck");
@@ -321,9 +309,6 @@ public class MoveGenTest {
assertTrue(MoveGen.givesCheck(pos, TextIO.stringToMove(pos, "exf3"))); assertTrue(MoveGen.givesCheck(pos, TextIO.stringToMove(pos, "exf3")));
} }
/**
* Test of removeIllegal method, of class MoveGen.
*/
@Test @Test
public void testRemoveIllegal() throws ChessParseError { public void testRemoveIllegal() throws ChessParseError {
System.out.println("removeIllegal"); System.out.println("removeIllegal");
@@ -347,9 +332,6 @@ public class MoveGenTest {
assertEquals(1, strMoves.size()); assertEquals(1, strMoves.size());
} }
/**
* Test that if king capture is possible, only a king capture move is returned in the move list.
*/
@Test @Test
public void testKingCapture() throws ChessParseError { public void testKingCapture() throws ChessParseError {
System.out.println("kingCapture"); System.out.println("kingCapture");

View File

@@ -31,11 +31,11 @@ public class MoveTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
@Before @Before
@@ -46,9 +46,6 @@ public class MoveTest {
public void tearDown() { public void tearDown() {
} }
/**
* Test of move constructor, of class Move.
*/
@Test @Test
public void testMoveConstructor() { public void testMoveConstructor() {
System.out.println("MoveTest"); System.out.println("MoveTest");
@@ -61,9 +58,6 @@ public class MoveTest {
assertEquals(move.promoteTo, p); assertEquals(move.promoteTo, p);
} }
/**
* Test of equals, of class Move.
*/
@Test @Test
public void testEquals() { public void testEquals() {
System.out.println("equals"); System.out.println("equals");

View File

@@ -29,16 +29,13 @@ public class PieceTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of isWhite method, of class Piece.
*/
@Test @Test
public void testIsWhite() { public void testIsWhite() {
System.out.println("isWhite"); System.out.println("isWhite");

View File

@@ -33,11 +33,11 @@ public class PositionTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
@Before @Before
@@ -48,9 +48,6 @@ public class PositionTest {
public void tearDown() { public void tearDown() {
} }
/**
* Test of getPiece method, of class Position.
*/
@Test @Test
public void testGetPiece() throws ChessParseError { public void testGetPiece() throws ChessParseError {
System.out.println("getPiece"); System.out.println("getPiece");
@@ -71,9 +68,6 @@ public class PositionTest {
} }
} }
/**
* Test of getIndex method, of class Position.
*/
@Test @Test
public void testGetIndex() { public void testGetIndex() {
System.out.println("getIndex"); System.out.println("getIndex");
@@ -88,9 +82,6 @@ public class PositionTest {
} }
} }
/**
* Test of setPiece method, of class Position.
*/
@Test @Test
public void testSetPiece() { public void testSetPiece() {
System.out.println("setPiece"); System.out.println("setPiece");
@@ -100,9 +91,6 @@ public class PositionTest {
assertEquals(Piece.WKING, instance.getPiece(Position.getSquare(3, 4))); assertEquals(Piece.WKING, instance.getPiece(Position.getSquare(3, 4)));
} }
/**
* Test of makeMove method, of class Position.
*/
@Test @Test
public void testMakeMove() throws ChessParseError { public void testMakeMove() throws ChessParseError {
System.out.println("makeMove"); System.out.println("makeMove");
@@ -212,9 +200,6 @@ public class PositionTest {
assertEquals(castleMask, pos.getCastleMask()); assertEquals(castleMask, pos.getCastleMask());
} }
/**
* Test of makeMove method, of class Position.
*/
@Test @Test
public void testPromotion() throws ChessParseError { public void testPromotion() throws ChessParseError {
System.out.println("promotion"); System.out.println("promotion");
@@ -251,10 +236,7 @@ public class PositionTest {
pos.unMakeMove(move, ui); pos.unMakeMove(move, ui);
assertEquals(origPos, pos); assertEquals(origPos, pos);
} }
/**
* Test move counters, of class Position.
*/
@Test @Test
public void testMoveCounters() throws ChessParseError { public void testMoveCounters() throws ChessParseError {
System.out.println("moveCounters"); System.out.println("moveCounters");
@@ -316,9 +298,6 @@ public class PositionTest {
assertEquals(69, pos.fullMoveCounter); assertEquals(69, pos.fullMoveCounter);
} }
/**
* Test of drawRuleEquals, of class Position.
*/
@Test @Test
public void testDrawRuleEquals() throws ChessParseError { public void testDrawRuleEquals() throws ChessParseError {
System.out.println("drawRuleEquals"); System.out.println("drawRuleEquals");
@@ -361,9 +340,6 @@ public class PositionTest {
assertEquals(false, pos.drawRuleEquals(origPos)); // Not equal, en passant rights lost assertEquals(false, pos.drawRuleEquals(origPos)); // Not equal, en passant rights lost
} }
/**
* Test of hashCode method, of class Position.
*/
@Test @Test
public void testHashCode() throws ChessParseError { public void testHashCode() throws ChessParseError {
System.out.println("hashCode"); System.out.println("hashCode");
@@ -417,9 +393,6 @@ public class PositionTest {
} }
} }
/**
* Test of getKingSq method, of class Position.
*/
@Test @Test
public void testGetKingSq() throws ChessParseError { public void testGetKingSq() throws ChessParseError {
System.out.println("getKingSq"); System.out.println("getKingSq");

View File

@@ -34,16 +34,13 @@ public class SearchTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of negaScout method, of class Search.
*/
@Test @Test
public void testNegaScout() throws ChessParseError, StopSearch { public void testNegaScout() throws ChessParseError, StopSearch {
System.out.println("negaScout"); System.out.println("negaScout");
@@ -89,9 +86,6 @@ public class SearchTest {
assertTrue(!TextIO.moveToString(pos, bestM, false).equals("Qxb3")); assertTrue(!TextIO.moveToString(pos, bestM, false).equals("Qxb3"));
} }
/**
* Test of draw by 50 move rule, of class Search.
*/
@Test @Test
public void testDraw50() throws ChessParseError, StopSearch { public void testDraw50() throws ChessParseError, StopSearch {
System.out.println("draw50"); System.out.println("draw50");
@@ -151,9 +145,6 @@ public class SearchTest {
assertEquals(mateInThree, score); // Need an extra pawn move to avoid 50-move rule assertEquals(mateInThree, score); // Need an extra pawn move to avoid 50-move rule
} }
/**
* Test of draw by repetition rule, of class Search.
*/
@Test @Test
public void testDrawRep() throws ChessParseError, StopSearch { public void testDrawRep() throws ChessParseError, StopSearch {
System.out.println("drawRep"); System.out.println("drawRep");
@@ -190,9 +181,6 @@ public class SearchTest {
assertEquals(0, score); // Draw, black can not escape from perpetual checks assertEquals(0, score); // Draw, black can not escape from perpetual checks
} }
/**
* Test of hash table, of class Search.
*/
@Test @Test
public void testHashing() throws ChessParseError { public void testHashing() throws ChessParseError {
System.out.println("hashing"); System.out.println("hashing");
@@ -202,9 +190,6 @@ public class SearchTest {
assertEquals(TextIO.stringToMove(pos, "Kb1"), new Move(bestM)); assertEquals(TextIO.stringToMove(pos, "Kb1"), new Move(bestM));
} }
/**
* Late move pruning must not be used in mate search.
*/
@Test @Test
public void testLMP() throws ChessParseError { public void testLMP() throws ChessParseError {
Position pos = TextIO.readFEN("2r2rk1/6p1/p3pq1p/1p1b1p2/3P1n2/PP3N2/3N1PPP/1Q2RR1K b"); // WAC 174 Position pos = TextIO.readFEN("2r2rk1/6p1/p3pq1p/1p1b1p2/3P1n2/PP3N2/3N1PPP/1Q2RR1K b"); // WAC 174
@@ -270,9 +255,6 @@ public class SearchTest {
return see; return see;
} }
/**
* Test of SEE method, of class Search.
*/
@Test @Test
public void testSEE() throws ChessParseError { public void testSEE() throws ChessParseError {
System.out.println("SEE"); System.out.println("SEE");
@@ -423,9 +405,6 @@ public class SearchTest {
assertEquals(h1, h2); assertEquals(h1, h2);
} }
/**
* Test of scoreMoveList method, of class Search.
*/
@Test @Test
public void testScoreMoveList() throws ChessParseError { public void testScoreMoveList() throws ChessParseError {
System.out.println("SEEorder"); System.out.println("SEEorder");

View File

@@ -31,11 +31,11 @@ public class TextIOTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
@Before @Before
@@ -46,9 +46,6 @@ public class TextIOTest {
public void tearDown() { public void tearDown() {
} }
/**
* Test of readFEN method, of class TextIO.
*/
@Test @Test
public void testReadFEN() throws ChessParseError { public void testReadFEN() throws ChessParseError {
System.out.println("readFEN"); System.out.println("readFEN");
@@ -123,9 +120,6 @@ public class TextIOTest {
return wasError; return wasError;
} }
/**
* Test of moveToString method, of class TextIO.
*/
@Test @Test
public void testMoveToString() throws ChessParseError { public void testMoveToString() throws ChessParseError {
System.out.println("moveToString"); System.out.println("moveToString");
@@ -162,9 +156,6 @@ public class TextIOTest {
assertEquals("c7-c8Q+", result); assertEquals("c7-c8Q+", result);
} }
/**
* Test of moveToString method, of class TextIO, mate/stalemate tests.
*/
@Test @Test
public void testMoveToStringMate() throws ChessParseError { public void testMoveToStringMate() throws ChessParseError {
System.out.println("moveToStringMate"); System.out.println("moveToStringMate");
@@ -188,9 +179,6 @@ public class TextIOTest {
assertEquals("b7-b8B", result); // stalemate assertEquals("b7-b8B", result); // stalemate
} }
/**
* Test of moveToString method, of class TextIO, short form.
*/
@Test @Test
public void testMoveToStringShortForm() throws ChessParseError { public void testMoveToStringShortForm() throws ChessParseError {
System.out.println("moveToStringShortForm"); System.out.println("moveToStringShortForm");
@@ -240,9 +228,6 @@ public class TextIOTest {
assertEquals("Rfd8", result); // File disambiguation needed assertEquals("Rfd8", result); // File disambiguation needed
} }
/**
* Test of stringToMove method, of class TextIO.
*/
@Test @Test
public void testStringToMove() throws ChessParseError { public void testStringToMove() throws ChessParseError {
System.out.println("stringToMove"); System.out.println("stringToMove");
@@ -324,9 +309,6 @@ public class TextIOTest {
assertEquals(m2, m); assertEquals(m2, m);
} }
/**
* Test of getSquare method, of class TextIO.
*/
@Test @Test
public void testGetSquare() throws ChessParseError { public void testGetSquare() throws ChessParseError {
System.out.println("getSquare"); System.out.println("getSquare");
@@ -338,9 +320,6 @@ public class TextIOTest {
assertEquals(Position.getSquare(7, 7), TextIO.getSquare("h8")); assertEquals(Position.getSquare(7, 7), TextIO.getSquare("h8"));
} }
/**
* Test of squareToString method, of class TextIO.
*/
@Test @Test
public void testSquareToString() { public void testSquareToString() {
System.out.println("squareToString"); System.out.println("squareToString");
@@ -349,9 +328,6 @@ public class TextIOTest {
assertEquals("e4", TextIO.squareToString(Position.getSquare(4, 3))); assertEquals("e4", TextIO.squareToString(Position.getSquare(4, 3)));
} }
/**
* Test of asciiBoard method, of class TextIO.
*/
@Test @Test
public void testAsciiBoard() throws ChessParseError { public void testAsciiBoard() throws ChessParseError {
System.out.println("asciiBoard"); System.out.println("asciiBoard");
@@ -363,9 +339,6 @@ public class TextIOTest {
assertEquals(3, aBrd.length() - aBrd.replaceAll(" P", " ").length()); // 3 white pawns assertEquals(3, aBrd.length() - aBrd.replaceAll(" P", " ").length()); // 3 white pawns
} }
/**
* Test of uciStringToMove method, of class TextIO.
*/
@Test @Test
public void testUciStringToMove() throws ChessParseError { public void testUciStringToMove() throws ChessParseError {
System.out.println("stringToMove"); System.out.println("stringToMove");

View File

@@ -30,16 +30,13 @@ public class TranspositionTableTest {
} }
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() {
} }
@AfterClass @AfterClass
public static void tearDownClass() throws Exception { public static void tearDownClass() {
} }
/**
* Test of TTEntry nested class, of class TranspositionTable.
*/
@Test @Test
public void testTTEntry() throws ChessParseError { public void testTTEntry() throws ChessParseError {
System.out.println("TTEntry"); System.out.println("TTEntry");
@@ -115,9 +112,6 @@ public class TranspositionTableTest {
assertEquals(score - 2, ent3.getScore(ply - 2)); assertEquals(score - 2, ent3.getScore(ply - 2));
} }
/**
* Test of insert method, of class TranspositionTable.
*/
@Test @Test
public void testInsert() throws ChessParseError { public void testInsert() throws ChessParseError {
System.out.println("insert"); System.out.println("insert");

View File

@@ -35,7 +35,7 @@ public class ChessControllerTest {
ctrl.setPGN("[FEN \"k/8/8/8/8/8/KP/8 w\"]\n"); ctrl.setPGN("[FEN \"k/8/8/8/8/8/KP/8 w\"]\n");
assertEquals(TextIO.getSquare("a2"), ctrl.game.pos.getKingSq(true)); assertEquals(TextIO.getSquare("a2"), ctrl.game.pos.getKingSq(true));
assertEquals(TextIO.getSquare("a8"), ctrl.game.pos.getKingSq(false)); assertEquals(TextIO.getSquare("a8"), ctrl.game.pos.getKingSq(false));
ctrl.setPGN("1.e4 e5 2. Nf3!!! $6 (Nc3 (a3)) Nc6?? Bb5!!? a6?! * Ba4"); ctrl.setPGN("1.e4 e5 2. Nf3!!! $6 (Nc3 (a3)) Nc6?? Bb5!!? a6?! * Ba4");
assertEquals(Piece.BPAWN, ctrl.game.pos.getPiece(TextIO.getSquare("a6"))); assertEquals(Piece.BPAWN, ctrl.game.pos.getPiece(TextIO.getSquare("a6")));
assertEquals(Piece.WBISHOP, ctrl.game.pos.getPiece(TextIO.getSquare("b5"))); assertEquals(Piece.WBISHOP, ctrl.game.pos.getPiece(TextIO.getSquare("b5")));

View File

@@ -35,9 +35,6 @@ public class BookTest extends TestCase {
public BookTest() { public BookTest() {
} }
/**
* Test of getBookMove method, of class Book.
*/
public void testGetBookMove() throws ChessParseError { public void testGetBookMove() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
DroidBook book = DroidBook.getInstance(); DroidBook book = DroidBook.getInstance();
@@ -50,9 +47,6 @@ public class BookTest extends TestCase {
assertEquals(null, move); assertEquals(null, move);
} }
/**
* Test of getAllBookMoves method, of class Book.
*/
public void testGetAllBookMoves() throws ChessParseError { public void testGetAllBookMoves() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
DroidBook book = DroidBook.getInstance(); DroidBook book = DroidBook.getInstance();

View File

@@ -31,9 +31,6 @@ public class PolyglotBookTest extends TestCase {
public PolyglotBookTest() { public PolyglotBookTest() {
} }
/**
* Test of getBookMove method, of class Book.
*/
public void testGetHashKey() throws ChessParseError { public void testGetHashKey() throws ChessParseError {
// starting position // starting position
Position pos = TextIO.readFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); Position pos = TextIO.readFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");

View File

@@ -30,9 +30,6 @@ public class GameTest extends TestCase {
public GameTest() { public GameTest() {
} }
/**
* Test of haveDrawOffer method, of class Game.
*/
public void testHaveDrawOffer() { public void testHaveDrawOffer() {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
@@ -134,9 +131,6 @@ public class GameTest extends TestCase {
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
} }
/**
* Test of draw by 50 move rule, of class Game.
*/
public void testDraw50() throws ChessParseError { public void testDraw50() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
@@ -196,9 +190,6 @@ public class GameTest extends TestCase {
assertEquals(Game.GameState.WHITE_MATE, game.getGameState()); // Can't claim draw when game over assertEquals(Game.GameState.WHITE_MATE, game.getGameState()); // Can't claim draw when game over
} }
/**
* Test of draw by repetition, of class Game.
*/
public void testDrawRep() throws ChessParseError { public void testDrawRep() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
@@ -268,9 +259,6 @@ public class GameTest extends TestCase {
assertEquals(Game.GameState.DRAW_REP, game.getGameState()); assertEquals(Game.GameState.DRAW_REP, game.getGameState());
} }
/**
* Test of draw offer/accept/request command.
*/
public void testDrawBug() throws ChessParseError { public void testDrawBug() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(false, game.haveDrawOffer()); assertEquals(false, game.haveDrawOffer());
@@ -286,9 +274,6 @@ public class GameTest extends TestCase {
assertEquals(Piece.EMPTY, game.tree.currentPos.getPiece(TextIO.getSquare("e5"))); assertEquals(Piece.EMPTY, game.tree.currentPos.getPiece(TextIO.getSquare("e5")));
} }
/**
* Test of resign command, of class Game.
*/
public void testResign() throws ChessParseError { public void testResign() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(Game.GameState.ALIVE, game.getGameState()); assertEquals(Game.GameState.ALIVE, game.getGameState());
@@ -316,9 +301,6 @@ public class GameTest extends TestCase {
assertEquals(Game.GameState.RESIGN_BLACK, game.getGameState()); assertEquals(Game.GameState.RESIGN_BLACK, game.getGameState());
} }
/**
* Test of processString method, of class Game.
*/
public void testProcessString() throws ChessParseError { public void testProcessString() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(TextIO.startPosFEN, TextIO.toFEN(game.currPos())); assertEquals(TextIO.startPosFEN, TextIO.toFEN(game.currPos()));
@@ -373,9 +355,6 @@ public class GameTest extends TestCase {
assertEquals(null, p.second); assertEquals(null, p.second);
} }
/**
* Test of getGameState method, of class Game.
*/
public void testGetGameState() throws ChessParseError { public void testGetGameState() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(Game.GameState.ALIVE, game.getGameState()); assertEquals(Game.GameState.ALIVE, game.getGameState());
@@ -389,9 +368,6 @@ public class GameTest extends TestCase {
assertEquals(Game.GameState.BLACK_STALEMATE, game.getGameState()); assertEquals(Game.GameState.BLACK_STALEMATE, game.getGameState());
} }
/**
* Test of insufficientMaterial method, of class Game.
*/
public void testInsufficientMaterial() throws ChessParseError { public void testInsufficientMaterial() throws ChessParseError {
Game game = new Game(null, new TimeControlData()); Game game = new Game(null, new TimeControlData());
assertEquals(Game.GameState.ALIVE, game.getGameState()); assertEquals(Game.GameState.ALIVE, game.getGameState());

View File

@@ -28,9 +28,6 @@ public class MoveGenTest extends TestCase {
public MoveGenTest() { public MoveGenTest() {
} }
/**
* Test of pseudoLegalMoves method, of class MoveGen.
*/
public void testPseudoLegalMoves() throws ChessParseError { public void testPseudoLegalMoves() throws ChessParseError {
String fen = "8/3k4/8/2n2pP1/1P6/1NB5/2QP4/R3K2R w KQ f6 0 2"; String fen = "8/3k4/8/2n2pP1/1P6/1NB5/2QP4/R3K2R w KQ f6 0 2";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -74,9 +71,6 @@ public class MoveGenTest extends TestCase {
assertTrue(strMoves.contains("O-O-O")); assertTrue(strMoves.contains("O-O-O"));
} }
/**
* Test of pseudoLegalMoves method, of class MoveGen. Pawn moves.
*/
public void testPawnMoves() throws ChessParseError { public void testPawnMoves() throws ChessParseError {
String fen = "1r2k3/P1pppp2/8/1pP3p1/1nPp2P1/n4p1P/1P2PP2/4KBNR w K b6 0 1"; String fen = "1r2k3/P1pppp2/8/1pP3p1/1nPp2P1/n4p1P/1P2PP2/4KBNR w K b6 0 1";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -114,9 +108,6 @@ public class MoveGenTest extends TestCase {
assertTrue(strMoves.contains("a2-a1B")); assertTrue(strMoves.contains("a2-a1B"));
} }
/**
* Test of inCheck method, of class MoveGen.
*/
public void testInCheck() { public void testInCheck() {
Position pos = new Position(); Position pos = new Position();
pos.setPiece(Position.getSquare(4,2), Piece.WKING); pos.setPiece(Position.getSquare(4,2), Piece.WKING);
@@ -147,9 +138,6 @@ public class MoveGenTest extends TestCase {
assertEquals(false, MoveGen.inCheck(pos)); assertEquals(false, MoveGen.inCheck(pos));
} }
/**
* Test of removeIllegal method, of class MoveGen.
*/
public void testRemoveIllegal() throws ChessParseError { public void testRemoveIllegal() throws ChessParseError {
Position pos = TextIO.readFEN("8/3k4/8/2n1rpP1/1P6/1NB5/2QP4/R3K2R w KQ f6 0 1"); Position pos = TextIO.readFEN("8/3k4/8/2n1rpP1/1P6/1NB5/2QP4/R3K2R w KQ f6 0 1");
List<String> strMoves = getMoveList(pos, true); List<String> strMoves = getMoveList(pos, true);

View File

@@ -25,9 +25,6 @@ public class MoveTest extends TestCase {
public MoveTest() { public MoveTest() {
} }
/**
* Test of move constructor, of class Move.
*/
public void testMoveConstructor() { public void testMoveConstructor() {
int f = Position.getSquare(4, 1); int f = Position.getSquare(4, 1);
int t = Position.getSquare(4, 3); int t = Position.getSquare(4, 3);
@@ -38,9 +35,6 @@ public class MoveTest extends TestCase {
assertEquals(move.promoteTo, p); assertEquals(move.promoteTo, p);
} }
/**
* Test of equals, of class Move.
*/
public void testEquals() { public void testEquals() {
Move m1 = new Move(Position.getSquare(0, 6), Position.getSquare(1, 7), Piece.WROOK); Move m1 = new Move(Position.getSquare(0, 6), Position.getSquare(1, 7), Piece.WROOK);
Move m2 = new Move(Position.getSquare(0, 6), Position.getSquare(0, 7), Piece.WROOK); Move m2 = new Move(Position.getSquare(0, 6), Position.getSquare(0, 7), Piece.WROOK);

View File

@@ -26,9 +26,6 @@ public class PieceTest extends TestCase {
public PieceTest() { public PieceTest() {
} }
/**
* Test of isWhite method, of class Piece.
*/
public void testIsWhite() { public void testIsWhite() {
assertEquals(false, Piece.isWhite(Piece.BBISHOP)); assertEquals(false, Piece.isWhite(Piece.BBISHOP));
assertEquals(true , Piece.isWhite(Piece.WBISHOP)); assertEquals(true , Piece.isWhite(Piece.WBISHOP));

View File

@@ -28,9 +28,6 @@ public class PositionTest extends TestCase {
public PositionTest() { public PositionTest() {
} }
/**
* Test of getPiece method, of class Position.
*/
public void testGetPiece() throws ChessParseError { public void testGetPiece() throws ChessParseError {
Position pos = new Position(); Position pos = new Position();
int result = pos.getPiece(0); int result = pos.getPiece(0);
@@ -49,9 +46,6 @@ public class PositionTest extends TestCase {
} }
} }
/**
* Test of getIndex method, of class Position.
*/
public void testGetIndex() { public void testGetIndex() {
for (int x = 0; x < 8; x++) { for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) { for (int y = 0; y < 8; y++) {
@@ -64,9 +58,6 @@ public class PositionTest extends TestCase {
} }
} }
/**
* Test of setPiece method, of class Position.
*/
public void testSetPiece() { public void testSetPiece() {
Position instance = new Position(); Position instance = new Position();
assertEquals(Piece.EMPTY, instance.getPiece(Position.getSquare(0, 0))); assertEquals(Piece.EMPTY, instance.getPiece(Position.getSquare(0, 0)));
@@ -74,9 +65,6 @@ public class PositionTest extends TestCase {
assertEquals(Piece.WKING, instance.getPiece(Position.getSquare(3, 4))); assertEquals(Piece.WKING, instance.getPiece(Position.getSquare(3, 4)));
} }
/**
* Test of makeMove method, of class Position.
*/
public void testMakeMove() throws ChessParseError { public void testMakeMove() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
Position origPos = new Position(pos); Position origPos = new Position(pos);
@@ -172,9 +160,6 @@ public class PositionTest extends TestCase {
assertTrue(pos.equals(origPos2)); assertTrue(pos.equals(origPos2));
} }
/**
* Test of makeMove method, of class Position.
*/
public void testPromotion() throws ChessParseError { public void testPromotion() throws ChessParseError {
String fen = "r1bqk2r/1Pppbppp/p1n2n2/2P1p3/B3P3/5N2/Pp1P1PPP/R1BQK2R w KQkq - 0 1"; String fen = "r1bqk2r/1Pppbppp/p1n2n2/2P1p3/B3P3/5N2/Pp1P1PPP/R1BQK2R w KQkq - 0 1";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -210,9 +195,6 @@ public class PositionTest extends TestCase {
assertEquals(origPos, pos); assertEquals(origPos, pos);
} }
/**
* Test move counters, of class Position.
*/
public void testMoveCounters() throws ChessParseError { public void testMoveCounters() throws ChessParseError {
String fen = "r1bqk2r/2ppbppp/p1n2n2/1pP1p3/B3P3/5N2/PP1P1PPP/RNBQK2R w KQkq b6 0 7"; String fen = "r1bqk2r/2ppbppp/p1n2n2/1pP1p3/B3P3/5N2/PP1P1PPP/RNBQK2R w KQkq b6 0 7";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -272,9 +254,6 @@ public class PositionTest extends TestCase {
assertEquals(69, pos.fullMoveCounter); assertEquals(69, pos.fullMoveCounter);
} }
/**
* Test of drawRuleEquals, of class Position.
*/
public void testDrawRuleEquals() throws ChessParseError { public void testDrawRuleEquals() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
Position origPos = new Position(pos); Position origPos = new Position(pos);
@@ -315,9 +294,6 @@ public class PositionTest extends TestCase {
assertEquals(false, pos.drawRuleEquals(origPos)); // Not equal, en passant rights lost assertEquals(false, pos.drawRuleEquals(origPos)); // Not equal, en passant rights lost
} }
/**
* Test of hashCode method, of class Position.
*/
public void testHashCode() throws ChessParseError { public void testHashCode() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
long h1 = pos.zobristHash(); long h1 = pos.zobristHash();
@@ -369,9 +345,6 @@ public class PositionTest extends TestCase {
} }
} }
/**
* Test of getKingSq method, of class Position.
*/
public void testGetKingSq() throws ChessParseError { public void testGetKingSq() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
assertEquals(TextIO.getSquare("e1"), pos.getKingSq(true)); assertEquals(TextIO.getSquare("e1"), pos.getKingSq(true));

View File

@@ -26,9 +26,6 @@ public class TextIOTest extends TestCase {
public TextIOTest() { public TextIOTest() {
} }
/**
* Test of readFEN method, of class TextIO.
*/
public void testReadFEN() throws ChessParseError { public void testReadFEN() throws ChessParseError {
String fen = "rnbqk2r/1p3ppp/p7/1NpPp3/QPP1P1n1/P4N2/4KbPP/R1B2B1R b kq - 0 1"; String fen = "rnbqk2r/1p3ppp/p7/1NpPp3/QPP1P1n1/P4N2/4KbPP/R1B2B1R b kq - 0 1";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -119,9 +116,6 @@ public class TextIOTest extends TestCase {
assertTrue(pos.equals(TextIO.readFEN("rnbqkbnr/pp1ppppp/8/8/2pPP3/3P4/PP3PPP/RNBQKBNR b KQkq - 0 1"))); assertTrue(pos.equals(TextIO.readFEN("rnbqkbnr/pp1ppppp/8/8/2pPP3/3P4/PP3PPP/RNBQKBNR b KQkq - 0 1")));
} }
/**
* Test that readFEN removes bogus castle flags.
*/
public void testReadFENCastleFlags() throws ChessParseError { public void testReadFENCastleFlags() throws ChessParseError {
String fenBogus = "rnbqk2r/1p3ppp/p7/1NpPp3/QPP1P1n1/P4N2/4KbPP/R1B2B1R w KQkq - 0 1"; String fenBogus = "rnbqk2r/1p3ppp/p7/1NpPp3/QPP1P1n1/P4N2/4KbPP/R1B2B1R w KQkq - 0 1";
Position pos = TextIO.readFEN(fenBogus); Position pos = TextIO.readFEN(fenBogus);
@@ -145,9 +139,6 @@ public class TextIOTest extends TestCase {
return TextIO.moveToString(pos, move, longForm, false); return TextIO.moveToString(pos, move, longForm, false);
} }
/**
* Test of moveToString method, of class TextIO.
*/
public void testMoveToString() throws ChessParseError { public void testMoveToString() throws ChessParseError {
Position pos = TextIO.readFEN(TextIO.startPosFEN); Position pos = TextIO.readFEN(TextIO.startPosFEN);
assertEquals(TextIO.startPosFEN, TextIO.toFEN(pos)); assertEquals(TextIO.startPosFEN, TextIO.toFEN(pos));
@@ -190,9 +181,6 @@ public class TextIOTest extends TestCase {
assertEquals("--", result); assertEquals("--", result);
} }
/**
* Test of moveToString method, of class TextIO, mate/stalemate tests.
*/
public void testMoveToStringMate() throws ChessParseError { public void testMoveToStringMate() throws ChessParseError {
Position pos = TextIO.readFEN("3k4/1PR5/3N4/8/4K3/8/8/8 w - - 0 1"); Position pos = TextIO.readFEN("3k4/1PR5/3N4/8/4K3/8/8/8 w - - 0 1");
boolean longForm = true; boolean longForm = true;
@@ -214,9 +202,6 @@ public class TextIOTest extends TestCase {
assertEquals("b7-b8B", result); // stalemate assertEquals("b7-b8B", result); // stalemate
} }
/**
* Test of moveToString method, of class TextIO, short form.
*/
public void testMoveToStringShortForm() throws ChessParseError { public void testMoveToStringShortForm() throws ChessParseError {
String fen = "r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1"; String fen = "r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1";
Position pos = TextIO.readFEN(fen); Position pos = TextIO.readFEN(fen);
@@ -264,9 +249,6 @@ public class TextIOTest extends TestCase {
assertEquals("Rfd8", result); // File disambiguation needed assertEquals("Rfd8", result); // File disambiguation needed
} }
/**
* Test of stringToMove method, of class TextIO.
*/
public void testStringToMove() throws ChessParseError { public void testStringToMove() throws ChessParseError {
Position pos = TextIO.readFEN("r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1"); Position pos = TextIO.readFEN("r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1");
@@ -369,9 +351,6 @@ public class TextIOTest extends TestCase {
assertEquals(mNf3, TextIO.stringToMove(pos, "Nf")); assertEquals(mNf3, TextIO.stringToMove(pos, "Nf"));
} }
/**
* Test of getSquare method, of class TextIO.
*/
public void testGetSquare() throws ChessParseError { public void testGetSquare() throws ChessParseError {
assertEquals(Position.getSquare(0, 0), TextIO.getSquare("a1")); assertEquals(Position.getSquare(0, 0), TextIO.getSquare("a1"));
assertEquals(Position.getSquare(1, 7), TextIO.getSquare("b8")); assertEquals(Position.getSquare(1, 7), TextIO.getSquare("b8"));
@@ -381,18 +360,12 @@ public class TextIOTest extends TestCase {
assertEquals(Position.getSquare(7, 7), TextIO.getSquare("h8")); assertEquals(Position.getSquare(7, 7), TextIO.getSquare("h8"));
} }
/**
* Test of squareToString method, of class TextIO.
*/
public void testSquareToString() { public void testSquareToString() {
assertEquals("a1", TextIO.squareToString(Position.getSquare(0, 0))); assertEquals("a1", TextIO.squareToString(Position.getSquare(0, 0)));
assertEquals("h6", TextIO.squareToString(Position.getSquare(7, 5))); assertEquals("h6", TextIO.squareToString(Position.getSquare(7, 5)));
assertEquals("e4", TextIO.squareToString(Position.getSquare(4, 3))); assertEquals("e4", TextIO.squareToString(Position.getSquare(4, 3)));
} }
/**
* Test of asciiBoard method, of class TextIO.
*/
public void testAsciiBoard() throws ChessParseError { public void testAsciiBoard() throws ChessParseError {
Position pos = TextIO.readFEN("r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1"); Position pos = TextIO.readFEN("r4rk1/2pn3p/2q1q1n1/8/2q2p2/6R1/p4PPP/1R4K1 b - - 0 1");
String aBrd = TextIO.asciiBoard(pos); String aBrd = TextIO.asciiBoard(pos);

View File

@@ -120,8 +120,8 @@ public class ColorTheme {
colorTable[i] = 0; colorTable[i] = 0;
try { try {
colorTable[i] = Color.parseColor(colorString); colorTable[i] = Color.parseColor(colorString);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException ignore) {
} catch (StringIndexOutOfBoundsException e) { } catch (StringIndexOutOfBoundsException ignore) {
} }
} }
} }

View File

@@ -1592,7 +1592,7 @@ public class DroidFish extends Activity
if (lines.length >= 3) if (lines.length >= 3)
id = lines[1] + ":" + lines[2]; id = lines[1] + ":" + lines[2];
} }
} catch (IOException e) { } catch (IOException ignore) {
} }
engineOptions.networkID = id; engineOptions.networkID = id;
} }
@@ -1783,7 +1783,7 @@ public class DroidFish extends Activity
String fen = data.getAction(); String fen = data.getAction();
ctrl.setFENOrPGN(fen); ctrl.setFENOrPGN(fen);
setBoardFlip(false); setBoardFlip(false);
} catch (ChessParseError e) { } catch (ChessParseError ignore) {
} }
} }
break; break;
@@ -1830,7 +1830,7 @@ public class DroidFish extends Activity
if (pathName != null) { if (pathName != null) {
if ((pathName.length() > 0) && !pathName.contains(".")) if ((pathName.length() > 0) && !pathName.contains("."))
pathName += ".pgn"; pathName += ".pgn";
savePGNToFile(pathName, false); savePGNToFile(pathName);
} }
} }
break; break;
@@ -2350,8 +2350,8 @@ public class DroidFish extends Activity
} }
case PASTE: { case PASTE: {
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) { ClipData clip = clipboard.getPrimaryClip();
ClipData clip = clipboard.getPrimaryClip(); if (clip != null) {
StringBuilder fenPgn = new StringBuilder(); StringBuilder fenPgn = new StringBuilder();
for (int i = 0; i < clip.getItemCount(); i++) for (int i = 0; i < clip.getItemCount(); i++)
fenPgn.append(clip.getItemAt(i).coerceToText(getApplicationContext())); fenPgn.append(clip.getItemAt(i).coerceToText(getApplicationContext()));
@@ -2458,7 +2458,7 @@ public class DroidFish extends Activity
try { try {
startActivity(Intent.createChooser(i, getString(game ? R.string.share_game : startActivity(Intent.createChooser(i, getString(game ? R.string.share_game :
R.string.share_text))); R.string.share_text)));
} catch (ActivityNotFoundException ex) { } catch (ActivityNotFoundException ignore) {
} }
} }
@@ -2493,7 +2493,7 @@ public class DroidFish extends Activity
i.setType("image/png"); i.setType("image/png");
try { try {
startActivity(Intent.createChooser(i, getString(R.string.share_image))); startActivity(Intent.createChooser(i, getString(R.string.share_image)));
} catch (ActivityNotFoundException ex) { } catch (ActivityNotFoundException ignore) {
} }
} }
@@ -2575,12 +2575,12 @@ public class DroidFish extends Activity
String data = FileUtil.readFromStream(is); String data = FileUtil.readFromStream(is);
if (data == null) if (data == null)
data = ""; data = "";
try { is.close(); } catch (IOException e1) {} try { is.close(); } catch (IOException ignore) {}
wv.loadDataWithBaseURL(null, data, "text/html", "utf-8", null); wv.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
try { try {
PackageInfo pi = getPackageManager().getPackageInfo("org.petero.droidfish", 0); PackageInfo pi = getPackageManager().getPackageInfo("org.petero.droidfish", 0);
title += " " + pi.versionName; title += " " + pi.versionName;
} catch (NameNotFoundException e) { } catch (NameNotFoundException ignore) {
} }
builder.setTitle(title); builder.setTitle(title);
return builder.create(); return builder.create();
@@ -2812,7 +2812,7 @@ public class DroidFish extends Activity
pgnFile = fileNames[item]; pgnFile = fileNames[item];
String sep = File.separator; String sep = File.separator;
String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile; String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile;
savePGNToFile(pathName, false); savePGNToFile(pathName);
} }
} }
}); });
@@ -2834,7 +2834,7 @@ public class DroidFish extends Activity
pgnFile += ".pgn"; pgnFile += ".pgn";
String sep = File.separator; String sep = File.separator;
String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile; String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile;
savePGNToFile(pathName, false); savePGNToFile(pathName);
} }
}; };
builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
@@ -3239,7 +3239,7 @@ public class DroidFish extends Activity
seekBar.setProgress(p); seekBar.setProgress(p);
updateText(editTxt, progressToNumPV(p, maxPV)); updateText(editTxt, progressToNumPV(p, maxPV));
} catch (NumberFormatException ex) { } catch (NumberFormatException ignore) {
} }
} }
@Override @Override
@@ -3560,7 +3560,7 @@ public class DroidFish extends Activity
if (lines.length > 2) if (lines.length > 2)
port = lines[2]; port = lines[2];
} }
} catch (IOException e1) { } catch (IOException ignore) {
} }
hostNameView.setText(hostName); hostNameView.setText(hostName);
portView.setText(port); portView.setText(port);
@@ -3776,7 +3776,7 @@ public class DroidFish extends Activity
} }
/** Save current game to a PGN file. */ /** Save current game to a PGN file. */
private void savePGNToFile(String pathName, boolean silent) { private void savePGNToFile(String pathName) {
String pgn = ctrl.getPGN(); String pgn = ctrl.getPGN();
String pgnToken = cache.storeString(pgn); String pgnToken = cache.storeString(pgn);
Editor editor = settings.edit(); Editor editor = settings.edit();
@@ -3787,7 +3787,7 @@ public class DroidFish extends Activity
i.setAction("org.petero.droidfish.saveFile"); i.setAction("org.petero.droidfish.saveFile");
i.putExtra("org.petero.droidfish.pathname", pathName); i.putExtra("org.petero.droidfish.pathname", pathName);
i.putExtra("org.petero.droidfish.pgn", pgnToken); i.putExtra("org.petero.droidfish.pgn", pgnToken);
i.putExtra("org.petero.droidfish.silent", silent); i.putExtra("org.petero.droidfish.silent", false);
startActivity(i); startActivity(i);
} }
@@ -3881,7 +3881,7 @@ public class DroidFish extends Activity
moveSound = MediaPlayer.create(this, R.raw.movesound); moveSound = MediaPlayer.create(this, R.raw.movesound);
if (moveSound != null) if (moveSound != null)
moveSound.start(); moveSound.start();
} catch (NotFoundException ex) { } catch (NotFoundException ignore) {
} }
} }
} else if (moveAnnounceType.startsWith("speech_")) { } else if (moveAnnounceType.startsWith("speech_")) {
@@ -3915,8 +3915,8 @@ public class DroidFish extends Activity
return; return;
notificationActive = show; notificationActive = show;
final int cpuUsage = 1; final int cpuUsage = 1;
String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager =
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns); (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (show) { if (show) {
boolean silhouette = Build.VERSION.SDK_INT >= 21; boolean silhouette = Build.VERSION.SDK_INT >= 21;
int icon = silhouette ? R.drawable.silhouette : R.mipmap.icon; int icon = silhouette ? R.drawable.silhouette : R.mipmap.icon;

View File

@@ -33,7 +33,7 @@ public interface GUIInterface {
/** Mark square sq as selected. Set to -1 to clear selection. */ /** Mark square sq as selected. Set to -1 to clear selection. */
void setSelection(int sq); void setSelection(int sq);
final static class GameStatus { final class GameStatus {
public Game.GameState state = Game.GameState.ALIVE; public Game.GameState state = Game.GameState.ALIVE;
public int moveNr = 0; public int moveNr = 0;
/** Move required to claim draw, or empty string. */ /** Move required to claim draw, or empty string. */
@@ -50,7 +50,7 @@ public interface GUIInterface {
/** Update the list of moves. */ /** Update the list of moves. */
void moveListUpdated(); void moveListUpdated();
final public static class ThinkingInfo { final class ThinkingInfo {
public int id; public int id;
public String pvStr; public String pvStr;
public String statStr; public String statStr;

View File

@@ -117,7 +117,7 @@ public class ObjectCache {
try { try {
tokens[i] = Long.valueOf(files[i].getName()); tokens[i] = Long.valueOf(files[i].getName());
token = Math.max(token, tokens[i]); token = Math.max(token, tokens[i]);
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }
Arrays.sort(tokens); Arrays.sort(tokens);
@@ -140,7 +140,7 @@ public class ObjectCache {
} }
} }
} }
} catch (IOException e) { } catch (IOException ignore) {
} }
} }
return -1; return -1;
@@ -167,7 +167,7 @@ public class ObjectCache {
} finally { } finally {
raf.close(); raf.close();
} }
} catch (IOException ex) { } catch (IOException ignore) {
} }
} }
return null; return null;

View File

@@ -105,7 +105,7 @@ public class Speech {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void say(String text) { private void say(String text) {
if (initialized) { if (initialized) {
if (lang != Language.NONE && text != null) { if (lang != Language.NONE && text != null) {
if (!tts.isSpeaking()) if (!tts.isSpeaking())

View File

@@ -22,11 +22,11 @@ import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
final class BufferedRandomAccessFileReader { final class BufferedRandomAccessFileReader {
RandomAccessFile f; private RandomAccessFile f;
byte[] buffer = new byte[8192]; private byte[] buffer = new byte[8192];
long bufStartFilePos = 0; private long bufStartFilePos = 0;
int bufLen = 0; private int bufLen = 0;
int bufPos = 0; private int bufPos = 0;
BufferedRandomAccessFileReader(String fileName) throws FileNotFoundException { BufferedRandomAccessFileReader(String fileName) throws FileNotFoundException {
f = new RandomAccessFile(fileName, "r"); f = new RandomAccessFile(fileName, "r");
@@ -34,7 +34,7 @@ final class BufferedRandomAccessFileReader {
final long length() throws IOException { final long length() throws IOException {
return f.length(); return f.length();
} }
final long getFilePointer() throws IOException { final long getFilePointer() {
return bufStartFilePos + bufPos; return bufStartFilePos + bufPos;
} }
final void close() throws IOException { final void close() throws IOException {

View File

@@ -81,8 +81,6 @@ import android.widget.Toast;
public class EditBoard extends Activity { public class EditBoard extends Activity {
private ChessBoardEdit cb; private ChessBoardEdit cb;
private TextView status; private TextView status;
private Button okButton;
private Button cancelButton;
private boolean egtbHints; private boolean egtbHints;
private boolean autoScrollTitle; private boolean autoScrollTitle;
@@ -111,7 +109,7 @@ public class EditBoard extends Activity {
Util.setFullScreenMode(this, settings); Util.setFullScreenMode(this, settings);
Intent i = getIntent(); Intent i = getIntent();
Position pos = null; Position pos;
try { try {
pos = TextIO.readFEN(i.getAction()); pos = TextIO.readFEN(i.getAction());
} catch (ChessParseError e) { } catch (ChessParseError e) {
@@ -147,8 +145,8 @@ public class EditBoard extends Activity {
cb = findViewById(R.id.eb_chessboard); cb = findViewById(R.id.eb_chessboard);
cb.setFlipped(boardFlipped); cb.setFlipped(boardFlipped);
status = findViewById(R.id.eb_status); status = findViewById(R.id.eb_status);
okButton = findViewById(R.id.eb_ok); Button okButton = findViewById(R.id.eb_ok);
cancelButton = findViewById(R.id.eb_cancel); Button cancelButton = findViewById(R.id.eb_cancel);
TextView whiteTitleText = findViewById(R.id.white_clock); TextView whiteTitleText = findViewById(R.id.white_clock);
whiteTitleText.setVisibility(View.GONE); whiteTitleText.setVisibility(View.GONE);
@@ -258,9 +256,9 @@ public class EditBoard extends Activity {
class DrawerItem { class DrawerItem {
int id; int id;
int itemId; // Item string resource id private int itemId; // Item string resource id
DrawerItem(int id, int itemId) { private DrawerItem(int id, int itemId) {
this.id = id; this.id = id;
this.itemId = itemId; this.itemId = itemId;
} }
@@ -322,7 +320,7 @@ public class EditBoard extends Activity {
cb.setPosition(pos); cb.setPosition(pos);
setSelection(-1); setSelection(-1);
checkValidAndUpdateMaterialDiff(); checkValidAndUpdateMaterialDiff();
} catch (ChessParseError e) { } catch (ChessParseError ignore) {
} }
break; break;
} }
@@ -353,8 +351,8 @@ public class EditBoard extends Activity {
} }
case PASTE_POSITION: { case PASTE_POSITION: {
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) { ClipData clip = clipboard.getPrimaryClip();
ClipData clip = clipboard.getPrimaryClip(); if (clip != null) {
if (clip.getItemCount() > 0) { if (clip.getItemCount() > 0) {
String fen = clip.getItemAt(0).coerceToText(getApplicationContext()).toString(); String fen = clip.getItemAt(0).coerceToText(getApplicationContext()).toString();
setFEN(fen); setFEN(fen);
@@ -413,7 +411,7 @@ public class EditBoard extends Activity {
} }
} }
Position pos = new Position(cb.pos); Position pos = new Position(cb.pos);
int piece = Piece.EMPTY; int piece;
if (m.from >= 0) { if (m.from >= 0) {
piece = pos.getPiece(m.from); piece = pos.getPiece(m.from);
} else { } else {
@@ -534,8 +532,7 @@ public class EditBoard extends Activity {
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case CASTLE_DIALOG: { case CASTLE_DIALOG: {
final CharSequence[] items = { final CharSequence[] items = {
@@ -572,8 +569,7 @@ public class EditBoard extends Activity {
checkValidAndUpdateMaterialDiff(); checkValidAndUpdateMaterialDiff();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case EP_DIALOG: { case EP_DIALOG: {
final CharSequence[] items = { final CharSequence[] items = {
@@ -587,8 +583,7 @@ public class EditBoard extends Activity {
dialog.cancel(); dialog.cancel();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case MOVCNT_DIALOG: { case MOVCNT_DIALOG: {
View content = View.inflate(this, R.layout.edit_move_counters, null); View content = View.inflate(this, R.layout.edit_move_counters, null);

View File

@@ -139,7 +139,7 @@ public class EditOptions extends Activity {
so.set(so.maxValue); so.set(so.maxValue);
else else
so.set(newVal); so.set(newVal);
} catch (NumberFormatException ex) { } catch (NumberFormatException ignore) {
} }
} }
}); });

View File

@@ -58,7 +58,7 @@ import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemLongClickListener;
public class EditPGN extends ListActivity { public abstract class EditPGN extends ListActivity {
static ArrayList<GameInfo> gamesInFile = new ArrayList<>(); static ArrayList<GameInfo> gamesInFile = new ArrayList<>();
static boolean cacheValid = false; static boolean cacheValid = false;
PGNFile pgnFile; PGNFile pgnFile;
@@ -105,7 +105,7 @@ public class EditPGN extends ListActivity {
String action = i.getAction(); String action = i.getAction();
String fileName = i.getStringExtra("org.petero.droidfish.pathname"); String fileName = i.getStringExtra("org.petero.droidfish.pathname");
canceled = false; canceled = false;
if (action.equals("org.petero.droidfish.loadFile")) { if ("org.petero.droidfish.loadFile".equals(action)) {
pgnFile = new PGNFile(fileName); pgnFile = new PGNFile(fileName);
loadGame = true; loadGame = true;
showDialog(PROGRESS_DIALOG); showDialog(PROGRESS_DIALOG);
@@ -127,8 +127,8 @@ public class EditPGN extends ListActivity {
} }
}); });
workThread.start(); workThread.start();
} else if (action.equals("org.petero.droidfish.loadFileNextGame") || } else if ("org.petero.droidfish.loadFileNextGame".equals(action) ||
action.equals("org.petero.droidfish.loadFilePrevGame")) { "org.petero.droidfish.loadFilePrevGame".equals(action)) {
pgnFile = new PGNFile(fileName); pgnFile = new PGNFile(fileName);
loadGame = true; loadGame = true;
boolean next = action.equals("org.petero.droidfish.loadFileNextGame"); boolean next = action.equals("org.petero.droidfish.loadFileNextGame");
@@ -158,7 +158,7 @@ public class EditPGN extends ListActivity {
}); });
workThread.start(); workThread.start();
} }
} else if (action.equals("org.petero.droidfish.saveFile")) { } else if ("org.petero.droidfish.saveFile".equals(action)) {
loadGame = false; loadGame = false;
String token = i.getStringExtra("org.petero.droidfish.pgn"); String token = i.getStringExtra("org.petero.droidfish.pgn");
pgnToSave = (new ObjectCache()).retrieveString(token); pgnToSave = (new ObjectCache()).retrieveString(token);
@@ -223,7 +223,7 @@ public class EditPGN extends ListActivity {
workThread.interrupt(); workThread.interrupt();
try { try {
workThread.join(); workThread.join();
} catch (InterruptedException e) { } catch (InterruptedException ignore) {
} }
workThread = null; workThread = null;
} }
@@ -365,8 +365,7 @@ public class EditPGN extends ListActivity {
dialog.cancel(); dialog.cancel();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case SAVE_GAME_DIALOG: { case SAVE_GAME_DIALOG: {
final GameInfo gi = selectedGi; final GameInfo gi = selectedGi;
@@ -394,8 +393,7 @@ public class EditPGN extends ListActivity {
finish(); finish();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
case DELETE_PGN_FILE_DIALOG: { case DELETE_PGN_FILE_DIALOG: {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
@@ -414,8 +412,7 @@ public class EditPGN extends ListActivity {
dialog.cancel(); dialog.cancel();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
default: default:
return null; return null;

View File

@@ -97,7 +97,7 @@ public class FENFile {
return new Pair<>(FenInfoResult.CANCEL, null); return new Pair<>(FenInfoResult.CANCEL, null);
} }
f.close(); f.close();
} catch (IOException e) { } catch (IOException ignore) {
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
fensInFile.clear(); fensInFile.clear();
fensInFile = null; fensInFile = null;

View File

@@ -78,7 +78,6 @@ public class LoadFEN extends ListActivity {
private ChessBoardPlay cb; private ChessBoardPlay cb;
private Button okButton; private Button okButton;
private Button cancelButton;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@@ -101,7 +100,7 @@ public class LoadFEN extends ListActivity {
Intent i = getIntent(); Intent i = getIntent();
String action = i.getAction(); String action = i.getAction();
String fileName = i.getStringExtra("org.petero.droidfish.pathname"); String fileName = i.getStringExtra("org.petero.droidfish.pathname");
if (action.equals("org.petero.droidfish.loadFen")) { if ("org.petero.droidfish.loadFen".equals(action)) {
fenFile = new FENFile(fileName); fenFile = new FENFile(fileName);
progressLatch = new CountDownLatch(1); progressLatch = new CountDownLatch(1);
showProgressDialog(); showProgressDialog();
@@ -130,8 +129,8 @@ public class LoadFEN extends ListActivity {
} }
}); });
workThread.start(); workThread.start();
} else if (action.equals("org.petero.droidfish.loadNextFen") || } else if ("org.petero.droidfish.loadNextFen".equals(action) ||
action.equals("org.petero.droidfish.loadPrevFen")) { "org.petero.droidfish.loadPrevFen".equals(action)) {
fenFile = new FENFile(fileName); fenFile = new FENFile(fileName);
boolean next = action.equals("org.petero.droidfish.loadNextFen"); boolean next = action.equals("org.petero.droidfish.loadNextFen");
final int loadItem = defaultItem + (next ? 1 : -1); final int loadItem = defaultItem + (next ? 1 : -1);
@@ -204,7 +203,7 @@ public class LoadFEN extends ListActivity {
cb = findViewById(R.id.loadfen_chessboard); cb = findViewById(R.id.loadfen_chessboard);
okButton = findViewById(R.id.loadfen_ok); okButton = findViewById(R.id.loadfen_ok);
cancelButton = findViewById(R.id.loadfen_cancel); Button cancelButton = findViewById(R.id.loadfen_cancel);
okButton.setEnabled(false); okButton.setEnabled(false);
okButton.setOnClickListener(new OnClickListener() { okButton.setOnClickListener(new OnClickListener() {

View File

@@ -135,7 +135,7 @@ public class LoadScid extends ListActivity {
fileName = i.getStringExtra("org.petero.droidfish.pathname"); fileName = i.getStringExtra("org.petero.droidfish.pathname");
resultSentBack = false; resultSentBack = false;
canceled = false; canceled = false;
if (action.equals("org.petero.droidfish.loadScid")) { if ("org.petero.droidfish.loadScid".equals(action)) {
progressLatch = new CountDownLatch(1); progressLatch = new CountDownLatch(1);
showProgressDialog(); showProgressDialog();
final LoadScid lpgn = this; final LoadScid lpgn = this;
@@ -163,8 +163,8 @@ public class LoadScid extends ListActivity {
}); });
} }
}); });
} else if (action.equals("org.petero.droidfish.loadScidNextGame") || } else if ("org.petero.droidfish.loadScidNextGame".equals(action) ||
action.equals("org.petero.droidfish.loadScidPrevGame")) { "org.petero.droidfish.loadScidPrevGame".equals(action)) {
boolean next = action.equals("org.petero.droidfish.loadScidNextGame"); boolean next = action.equals("org.petero.droidfish.loadScidNextGame");
final int loadItem = defaultItem + (next ? 1 : -1); final int loadItem = defaultItem + (next ? 1 : -1);
if (loadItem < 0) { if (loadItem < 0) {
@@ -222,7 +222,7 @@ public class LoadScid extends ListActivity {
workThread.interrupt(); workThread.interrupt();
try { try {
workThread.join(); workThread.join();
} catch (InterruptedException e) { } catch (InterruptedException ignore) {
} }
workThread = null; workThread = null;
} }
@@ -319,7 +319,7 @@ public class LoadScid extends ListActivity {
} }
addGameInfo(cursor); addGameInfo(cursor);
gameNo++; gameNo++;
final int newPercent = (int)(gameNo * 100 / noGames); final int newPercent = gameNo * 100 / noGames;
if (newPercent > percent) { if (newPercent > percent) {
percent = newPercent; percent = newPercent;
if (progress != null) { if (progress != null) {

View File

@@ -154,7 +154,7 @@ public class PGNFile {
public void close() { public void close() {
try { try {
is.close(); is.close();
} catch (IOException ex) { } catch (IOException ignore) {
} }
} }
} }
@@ -364,7 +364,7 @@ public class PGNFile {
gi.info = hi.toString(); gi.info = hi.toString();
gamesInFile.add(gi); gamesInFile.add(gi);
} }
} catch (IOException e) { } catch (IOException ignore) {
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
gamesInFile.clear(); gamesInFile.clear();
gamesInFile = null; gamesInFile = null;
@@ -393,7 +393,7 @@ public class PGNFile {
f.readFully(pgnData); f.readFully(pgnData);
f.close(); f.close();
return new String(pgnData); return new String(pgnData);
} catch (IOException e) { } catch (IOException ignore) {
} }
return null; return null;
} }
@@ -444,7 +444,7 @@ public class PGNFile {
return false; return false;
} }
final boolean replacePGN(String pgnToSave, GameInfo gi) { final void replacePGN(String pgnToSave, GameInfo gi) {
try { try {
File tmpFile = new File(fileName + ".tmp_delete"); File tmpFile = new File(fileName + ".tmp_delete");
RandomAccessFile fileReader = new RandomAccessFile(fileName, "r"); RandomAccessFile fileReader = new RandomAccessFile(fileName, "r");
@@ -458,11 +458,9 @@ public class PGNFile {
if (!tmpFile.renameTo(fileName)) if (!tmpFile.renameTo(fileName))
throw new IOException(); throw new IOException();
DroidFishApp.toast(R.string.game_saved, Toast.LENGTH_SHORT); DroidFishApp.toast(R.string.game_saved, Toast.LENGTH_SHORT);
return true;
} catch (IOException e) { } catch (IOException e) {
DroidFishApp.toast(R.string.failed_to_save_game, Toast.LENGTH_SHORT); DroidFishApp.toast(R.string.failed_to_save_game, Toast.LENGTH_SHORT);
} }
return false;
} }
private static void copyData(RandomAccessFile fileReader, private static void copyData(RandomAccessFile fileReader,

View File

@@ -151,7 +151,7 @@ public class SeekBarPreference extends Preference
if (value < 0) value = 0; if (value < 0) value = 0;
if (value > maxValue) value = maxValue; if (value > maxValue) value = maxValue;
onProgressChanged(bar, value, false); onProgressChanged(bar, value, false);
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }
}; };

View File

@@ -120,9 +120,9 @@ class CtgBook implements IOpeningBook {
} catch (IOException e) { } catch (IOException e) {
return null; return null;
} finally { } finally {
if (ctgF != null) try { ctgF.close(); } catch (IOException e) { } if (ctgF != null) try { ctgF.close(); } catch (IOException ignore) { }
if (ctbF != null) try { ctbF.close(); } catch (IOException e) { } if (ctbF != null) try { ctbF.close(); } catch (IOException ignore) { }
if (ctoF != null) try { ctoF.close(); } catch (IOException e) { } if (ctoF != null) try { ctoF.close(); } catch (IOException ignore) { }
} }
} }
@@ -163,7 +163,7 @@ class CtgBook implements IOpeningBook {
int byteIdx = length / 8; int byteIdx = length / 8;
int bitIdx = 7 - (length & 7); int bitIdx = 7 - (length & 7);
while (buf.size() <= byteIdx) while (buf.size() <= byteIdx)
buf.add(Byte.valueOf((byte)0)); buf.add((byte)0);
if (value) if (value)
buf.set(byteIdx, (byte)(buf.get(byteIdx) | (1 << bitIdx))); buf.set(byteIdx, (byte)(buf.get(byteIdx) | (1 << bitIdx)));
length++; length++;
@@ -266,8 +266,7 @@ class CtgBook implements IOpeningBook {
final int getPage(int hashIndex) throws IOException { final int getPage(int hashIndex) throws IOException {
byte[] buf = readBytes(f, 16 + 4 * hashIndex, 4); byte[] buf = readBytes(f, 16 + 4 * hashIndex, 4);
int page = extractInt(buf, 0, 4); return extractInt(buf, 0, 4);
return page;
} }
private final static int tbl[] = { private final static int tbl[] = {
@@ -292,8 +291,7 @@ class CtgBook implements IOpeningBook {
private static int getHashValue(byte[] encodedPos) { private static int getHashValue(byte[] encodedPos) {
int hash = 0; int hash = 0;
int tmp = 0; int tmp = 0;
for (int i = 0; i < encodedPos.length; i++) { for (int ch : encodedPos) {
int ch = encodedPos[i];
tmp += ((0x0f - (ch & 0x0f)) << 2) + 1; tmp += ((0x0f - (ch & 0x0f)) << 2) + 1;
hash += tbl[tmp & 0x3f]; hash += tbl[tmp & 0x3f];
tmp += ((0xf0 - (ch & 0xf0)) >> 2) + 1; tmp += ((0xf0 - (ch & 0xf0)) >> 2) + 1;
@@ -437,8 +435,7 @@ class CtgBook implements IOpeningBook {
final int getRecommendation() { final int getRecommendation() {
int statStart = posLen + moveBytes; int statStart = posLen + moveBytes;
int recom = extractInt(buf, statStart + 30, 1); return extractInt(buf, statStart + 30, 1);
return recom;
} }
private static final class MoveInfo { private static final class MoveInfo {
@@ -651,8 +648,7 @@ class CtgBook implements IOpeningBook {
int promoteTo = Piece.EMPTY; int promoteTo = Piece.EMPTY;
if ((pos.getPiece(from) == Piece.WPAWN) && (toY == 7)) if ((pos.getPiece(from) == Piece.WPAWN) && (toY == 7))
promoteTo = Piece.WQUEEN; promoteTo = Piece.WQUEEN;
Move m = new Move(from, to, promoteTo); return new Move(from, to, promoteTo);
return m;
} }
} }

View File

@@ -19,6 +19,7 @@
package org.petero.droidfish.book; package org.petero.droidfish.book;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.text.style.TabStopSpan;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@@ -254,8 +255,6 @@ public class EcoDb {
try { try {
ByteArrayOutputStream bufStream = new ByteArrayOutputStream(); ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
InputStream inStream = DroidFishApp.getContext().getAssets().open("eco.dat"); InputStream inStream = DroidFishApp.getContext().getAssets().open("eco.dat");
if (inStream == null)
throw new IOException("Can't read ECO database");
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
while (true) { while (true) {
int len = inStream.read(buf); int len = inStream.read(buf);
@@ -365,8 +364,8 @@ public class EcoDb {
private int maxSize; private int maxSize;
public WeakLRUCache(int maxSize) { public WeakLRUCache(int maxSize) {
mapNew = new WeakHashMap<K, V>(); mapNew = new WeakHashMap<>();
mapOld = new WeakHashMap<K, V>(); mapOld = new WeakHashMap<>();
this.maxSize = maxSize; this.maxSize = maxSize;
} }
@@ -375,8 +374,7 @@ public class EcoDb {
if (mapNew.containsKey(key)) { if (mapNew.containsKey(key)) {
mapNew.put(key, val); mapNew.put(key, val);
} else { } else {
if (mapOld.containsKey(key)) mapOld.remove(key);
mapOld.remove(key);
insertNew(key, val); insertNew(key, val);
} }
} }

View File

@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import org.petero.droidfish.DroidFishApp;
import org.petero.droidfish.book.DroidBook.BookEntry; import org.petero.droidfish.book.DroidBook.BookEntry;
import org.petero.droidfish.gamelogic.ChessParseError; import org.petero.droidfish.gamelogic.ChessParseError;
import org.petero.droidfish.gamelogic.Move; import org.petero.droidfish.gamelogic.Move;
@@ -34,7 +33,6 @@ import org.petero.droidfish.gamelogic.TextIO;
import org.petero.droidfish.gamelogic.UndoInfo; import org.petero.droidfish.gamelogic.UndoInfo;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.widget.Toast;
@SuppressLint("UseSparseArrays") @SuppressLint("UseSparseArrays")
final class InternalBook implements IOpeningBook { final class InternalBook implements IOpeningBook {
@@ -78,7 +76,7 @@ final class InternalBook implements IOpeningBook {
enabled = options.filename.equals("internal:"); enabled = options.filename.equals("internal:");
} }
private synchronized final void initInternalBook() { private synchronized void initInternalBook() {
if (numBookMoves >= 0) if (numBookMoves >= 0)
return; return;
// long t0 = System.currentTimeMillis(); // long t0 = System.currentTimeMillis();

View File

@@ -53,7 +53,7 @@ public class DroidComputerPlayer {
private String engineName = "Computer"; private String engineName = "Computer";
/** Engine state. */ /** Engine state. */
private static enum MainState { private enum MainState {
READ_OPTIONS, // "uci" command sent, waiting for "option" and "uciok" response. READ_OPTIONS, // "uci" command sent, waiting for "option" and "uciok" response.
WAIT_READY, // "isready" sent, waiting for "readyok". WAIT_READY, // "isready" sent, waiting for "readyok".
IDLE, // engine not searching. IDLE, // engine not searching.
@@ -138,7 +138,6 @@ public class DroidComputerPlayer {
* Create a search request object. * Create a search request object.
* @param id Search ID. * @param id Search ID.
* @param now Current system time. * @param now Current system time.
* @param pos An earlier position from the game.
* @param mList List of moves to go from the earlier position to the current position. * @param mList List of moves to go from the earlier position to the current position.
* This list makes it possible for the computer to correctly handle draw * This list makes it possible for the computer to correctly handle draw
* by repetition/50 moves. * by repetition/50 moves.
@@ -406,7 +405,7 @@ public class DroidComputerPlayer {
// If we have a book move, play it. // If we have a book move, play it.
Move bookMove = book.getBookMove(sr.currPos); Move bookMove = book.getBookMove(sr.currPos);
if (bookMove != null) { if (bookMove != null) {
if (canClaimDraw(sr.currPos, posHashList, posHashListSize, bookMove) == "") { if (canClaimDraw(sr.currPos, posHashList, posHashListSize, bookMove).isEmpty()) {
listener.notifySearchResult(sr.searchId, listener.notifySearchResult(sr.searchId,
TextIO.moveToString(sr.currPos, bookMove, false, false), TextIO.moveToString(sr.currPos, bookMove, false, false),
null); null);
@@ -422,7 +421,7 @@ public class DroidComputerPlayer {
} }
if (moves.size() == 1) { if (moves.size() == 1) {
Move bestMove = moves.get(0); Move bestMove = moves.get(0);
if (canClaimDraw(sr.currPos, posHashList, posHashListSize, bestMove) == "") { if (canClaimDraw(sr.currPos, posHashList, posHashListSize, bestMove).isEmpty()) {
listener.notifySearchResult(sr.searchId, TextIO.moveToUCIString(bestMove), null); listener.notifySearchResult(sr.searchId, TextIO.moveToUCIString(bestMove), null);
return; return;
} }
@@ -497,7 +496,7 @@ public class DroidComputerPlayer {
} }
/** Type of search the engine is currently requested to perform. */ /** Type of search the engine is currently requested to perform. */
public static enum SearchType { public enum SearchType {
NONE, NONE,
SEARCH, SEARCH,
PONDER, PONDER,
@@ -807,7 +806,7 @@ public class DroidComputerPlayer {
if (statScore <= 0) { if (statScore <= 0) {
String drawClaim = canClaimDraw(sr.currPos, sr.posHashList, sr.posHashListSize, String drawClaim = canClaimDraw(sr.currPos, sr.posHashList, sr.posHashListSize,
TextIO.UCIstringToMove(bestMove)); TextIO.UCIstringToMove(bestMove));
if (drawClaim != "") { if (!drawClaim.isEmpty()) {
bestMove = drawClaim; bestMove = drawClaim;
canPonder = false; canPonder = false;
} }
@@ -820,7 +819,7 @@ public class DroidComputerPlayer {
if (canPonder) { if (canPonder) {
Move bestM = TextIO.stringToMove(sr.currPos, bestMove); Move bestM = TextIO.stringToMove(sr.currPos, bestMove);
if ((bestM == null) || !TextIO.isValid(sr.currPos, bestM)) if (!TextIO.isValid(sr.currPos, bestM))
canPonder = false; canPonder = false;
if (canPonder) { if (canPonder) {
Position tmpPos = new Position(sr.currPos); Position tmpPos = new Position(sr.currPos);

View File

@@ -54,7 +54,7 @@ public class EngineUtil {
if ((inFile.read(buf) == 4) && "NETE".equals(new String(buf))) if ((inFile.read(buf) == 4) && "NETE".equals(new String(buf)))
netEngine = true; netEngine = true;
inFile.close(); inFile.close();
} catch (IOException e) { } catch (IOException ignore) {
} }
return netEngine; return netEngine;
} }

View File

@@ -43,7 +43,7 @@ public class ExternalEngine extends UCIEngineBase {
private Thread exitThread; private Thread exitThread;
private Thread stdInThread; private Thread stdInThread;
private Thread stdErrThread; private Thread stdErrThread;
private LocalPipe inLines; private final LocalPipe inLines;
private boolean startedOk; private boolean startedOk;
private boolean isRunning; private boolean isRunning;
@@ -107,7 +107,7 @@ public class ExternalEngine extends UCIEngineBase {
else { else {
report.reportError(context.getString(R.string.engine_terminated)); report.reportError(context.getString(R.string.engine_terminated));
} }
} catch (InterruptedException e) { } catch (InterruptedException ignore) {
} }
} }
}); });
@@ -127,7 +127,7 @@ public class ExternalEngine extends UCIEngineBase {
try { try {
boolean first = true; boolean first = true;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
if ((ep == null) || Thread.currentThread().isInterrupted()) if (Thread.currentThread().isInterrupted())
return; return;
synchronized (inLines) { synchronized (inLines) {
inLines.addLine(line); inLines.addLine(line);
@@ -138,7 +138,7 @@ public class ExternalEngine extends UCIEngineBase {
} }
} }
} }
} catch (IOException e) { } catch (IOException ignore) {
} }
inLines.close(); inLines.close();
} }
@@ -177,7 +177,7 @@ public class ExternalEngine extends UCIEngineBase {
f.setAccessible(true); f.setAccessible(true);
int pid = f.getInt(engineProc); int pid = f.getInt(engineProc);
EngineUtil.reNice(pid, 10); EngineUtil.reNice(pid, 10);
} catch (Throwable t) { } catch (Throwable ignore) {
} }
} }
@@ -193,7 +193,7 @@ public class ExternalEngine extends UCIEngineBase {
f.delete(); f.delete();
} }
new File(context.getFilesDir(), "engine.exe").delete(); new File(context.getFilesDir(), "engine.exe").delete();
} catch (IOException e) { } catch (IOException ignore) {
} }
} }
@@ -276,7 +276,7 @@ public class ExternalEngine extends UCIEngineBase {
ep.getOutputStream().write(data.getBytes()); ep.getOutputStream().write(data.getBytes());
ep.getOutputStream().flush(); ep.getOutputStream().flush();
} }
} catch (IOException e) { } catch (IOException ignore) {
} }
} }
@@ -294,7 +294,7 @@ public class ExternalEngine extends UCIEngineBase {
engineProc.exitValue(); engineProc.exitValue();
break; break;
} catch (IllegalThreadStateException e) { } catch (IllegalThreadStateException e) {
try { Thread.sleep(10); } catch (InterruptedException e2) { } try { Thread.sleep(10); } catch (InterruptedException ignore) { }
} }
} }
engineProc.destroy(); engineProc.destroy();
@@ -325,8 +325,8 @@ public class ExternalEngine extends UCIEngineBase {
if (cnt < inFC.size()) if (cnt < inFC.size())
throw new IOException("File copy failed"); throw new IOException("File copy failed");
} finally { } finally {
if (fis != null) { try { fis.close(); } catch (IOException ex) {} } if (fis != null) { try { fis.close(); } catch (IOException ignore) {} }
if (fos != null) { try { fos.close(); } catch (IOException ex) {} } if (fos != null) { try { fos.close(); } catch (IOException ignore) {} }
to.setLastModified(from.lastModified()); to.setLastModified(from.lastModified());
} }
return to.getAbsolutePath(); return to.getAbsolutePath();

View File

@@ -71,7 +71,7 @@ public class InternalStockFish extends ExternalEngine {
} catch (IOException e) { } catch (IOException e) {
return 0; return 0;
} finally { } finally {
if (is != null) try { is.close(); } catch (IOException ex) {} if (is != null) try { is.close(); } catch (IOException ignore) {}
} }
} }
@@ -83,7 +83,7 @@ public class InternalStockFish extends ExternalEngine {
dos.writeLong(checkSum); dos.writeLong(checkSum);
} catch (IOException e) { } catch (IOException e) {
} finally { } finally {
if (dos != null) try { dos.close(); } catch (IOException ex) {} if (dos != null) try { dos.close(); } catch (IOException ignore) {}
} }
} }
@@ -110,7 +110,7 @@ public class InternalStockFish extends ExternalEngine {
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
return -1; return -1;
} finally { } finally {
if (is != null) try { is.close(); } catch (IOException ex) {} if (is != null) try { is.close(); } catch (IOException ignore) {}
} }
} }
@@ -142,8 +142,8 @@ public class InternalStockFish extends ExternalEngine {
os.write(buf, 0, len); os.write(buf, 0, len);
} }
} finally { } finally {
if (is != null) try { is.close(); } catch (IOException ex) {} if (is != null) try { is.close(); } catch (IOException ignore) {}
if (os != null) try { os.close(); } catch (IOException ex) {} if (os != null) try { os.close(); } catch (IOException ignore) {}
} }
writeCheckSum(new File(internalSFPath()), newCSum); writeCheckSum(new File(internalSFPath()), newCSum);

View File

@@ -42,7 +42,7 @@ public class LocalPipe {
while (lines.size() > 10000) { while (lines.size() > 10000) {
try { try {
wait(10); wait(10);
} catch (InterruptedException e) { } catch (InterruptedException ignore) {
} }
} }
lines.add(line); lines.add(line);

View File

@@ -44,8 +44,8 @@ public class NetworkEngine extends UCIEngineBase {
private Thread startupThread; private Thread startupThread;
private Thread stdInThread; private Thread stdInThread;
private Thread stdOutThread; private Thread stdOutThread;
private LocalPipe guiToEngine; private final LocalPipe guiToEngine;
private LocalPipe engineToGui; private final LocalPipe engineToGui;
private boolean startedOk; private boolean startedOk;
private boolean isRunning; private boolean isRunning;
private boolean isError; private boolean isError;
@@ -78,7 +78,7 @@ public class NetworkEngine extends UCIEngineBase {
port = lines[2]; port = lines[2];
ok = true; ok = true;
} }
} catch (IOException e1) { } catch (IOException ignore) {
} }
} }
if (!ok) { if (!ok) {
@@ -151,7 +151,7 @@ public class NetworkEngine extends UCIEngineBase {
} }
} }
} }
} catch (IOException e) { } catch (IOException ignore) {
} finally { } finally {
if (isRunning) { if (isRunning) {
isError = true; isError = true;
@@ -191,8 +191,8 @@ public class NetworkEngine extends UCIEngineBase {
report.reportError(context.getString(R.string.engine_terminated)); report.reportError(context.getString(R.string.engine_terminated));
} }
isRunning = false; isRunning = false;
try { socket.getOutputStream().write("quit\n".getBytes()); } catch (IOException e) {} try { socket.getOutputStream().write("quit\n".getBytes()); } catch (IOException ignore) {}
try { socket.close(); } catch (IOException ex) {} try { socket.close(); } catch (IOException ignore) {}
} }
} }
}); });

View File

@@ -40,7 +40,7 @@ public abstract class UCIEngineBase implements UCIEngine {
public static UCIEngine getEngine(String engine, public static UCIEngine getEngine(String engine,
EngineOptions engineOptions, Report report) { EngineOptions engineOptions, Report report) {
if ("cuckoochess".equals(engine)) if ("cuckoochess".equals(engine))
return new CuckooChessEngine(report); return new CuckooChessEngine();
else if ("stockfish".equals(engine)) else if ("stockfish".equals(engine))
return new InternalStockFish(report); return new InternalStockFish(report);
else if (EngineUtil.isOpenExchangeEngine(engine)) else if (EngineUtil.isOpenExchangeEngine(engine))
@@ -80,10 +80,10 @@ public abstract class UCIEngineBase implements UCIEngine {
try { try {
is = new FileInputStream(optionsFile); is = new FileInputStream(optionsFile);
iniOptions.load(is); iniOptions.load(is);
} catch (IOException ex) { } catch (IOException ignore) {
} finally { } finally {
if (is != null) if (is != null)
try { is.close(); } catch (IOException ex) {} try { is.close(); } catch (IOException ignore) {}
} }
for (Map.Entry<Object,Object> ent : iniOptions.entrySet()) { for (Map.Entry<Object,Object> ent : iniOptions.entrySet()) {
if (ent.getKey() instanceof String && ent.getValue() instanceof String) { if (ent.getKey() instanceof String && ent.getValue() instanceof String) {
@@ -99,8 +99,8 @@ public abstract class UCIEngineBase implements UCIEngine {
public final boolean setUCIOptions(Map<String,String> uciOptions) { public final boolean setUCIOptions(Map<String,String> uciOptions) {
boolean modified = false; boolean modified = false;
for (Map.Entry<String,String> ent : uciOptions.entrySet()) { for (Map.Entry<String,String> ent : uciOptions.entrySet()) {
String key = ((String)ent.getKey()).toLowerCase(Locale.US); String key = ent.getKey().toLowerCase(Locale.US);
String value = (String)ent.getValue(); String value = ent.getValue();
if (configurableOption(key)) if (configurableOption(key))
modified |= setOption(key, value); modified |= setOption(key, value);
} }
@@ -120,10 +120,10 @@ public abstract class UCIEngineBase implements UCIEngine {
try { try {
os = new FileOutputStream(optionsFile); os = new FileOutputStream(optionsFile);
iniOptions.store(os, null); iniOptions.store(os, null);
} catch (IOException ex) { } catch (IOException ignore) {
} finally { } finally {
if (os != null) if (os != null)
try { os.close(); } catch (IOException ex) {} try { os.close(); } catch (IOException ignore) {}
} }
} }

View File

@@ -49,7 +49,7 @@ public class CuckooChessEngine extends UCIEngineBase {
private LocalPipe engineToGui; private LocalPipe engineToGui;
private Thread engineThread; private Thread engineThread;
public CuckooChessEngine(Report report) { public CuckooChessEngine() {
pos = null; pos = null;
moves = new ArrayList<>(); moves = new ArrayList<>();
quit = false; quit = false;
@@ -263,9 +263,9 @@ public class CuckooChessEngine extends UCIEngineBase {
} }
quit = true; quit = true;
} }
} catch (ChessParseError ex) { } catch (ChessParseError ignore) {
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException ignore) {
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }

View File

@@ -42,31 +42,31 @@ import org.petero.droidfish.engine.LocalPipe;
public class DroidEngineControl { public class DroidEngineControl {
LocalPipe os; LocalPipe os;
Thread engineThread; private Thread engineThread;
private final Object threadMutex; private final Object threadMutex;
Search sc; private Search sc;
TranspositionTable tt; private TranspositionTable tt;
History ht; private History ht;
MoveGen moveGen; private MoveGen moveGen;
Position pos; private Position pos;
long[] posHashList; private long[] posHashList;
int posHashListSize; private int posHashListSize;
boolean ponder; // True if currently doing pondering private boolean ponder; // True if currently doing pondering
boolean onePossibleMove; private boolean onePossibleMove;
boolean infinite; private boolean infinite;
int minTimeLimit; private int minTimeLimit;
int maxTimeLimit; private int maxTimeLimit;
int maxDepth; private int maxDepth;
int maxNodes; private int maxNodes;
List<Move> searchMoves; private List<Move> searchMoves;
// Options // Options
int hashSizeMB = 2; private int hashSizeMB = 2;
boolean ownBook = false; private boolean ownBook = false;
boolean analyseMode = false; private boolean analyseMode = false;
boolean ponderMode = true; private boolean ponderMode = true;
// Reduced strength variables // Reduced strength variables
private int strength = 1000; private int strength = 1000;
@@ -208,7 +208,7 @@ public class DroidEngineControl {
} }
} }
static int clamp(int val, int min, int max) { private static int clamp(int val, int min, int max) {
if (val < min) { if (val < min) {
return min; return min;
} else if (val > max) { } else if (val > max) {
@@ -302,7 +302,7 @@ public class DroidEngineControl {
tt = new TranspositionTable(logSize); tt = new TranspositionTable(logSize);
} }
final void setupPosition(Position pos, List<Move> moves) { private void setupPosition(Position pos, List<Move> moves) {
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();
posHashList = new long[200 + moves.size()]; posHashList = new long[200 + moves.size()];
posHashListSize = 0; posHashListSize = 0;
@@ -316,7 +316,7 @@ public class DroidEngineControl {
/** /**
* Try to find a move to ponder from the transposition table. * Try to find a move to ponder from the transposition table.
*/ */
final Move getPonderMove(Position pos, Move m) { private Move getPonderMove(Position pos, Move m) {
if (m == null) if (m == null)
return null; return null;
Move ret = null; Move ret = null;
@@ -336,7 +336,7 @@ public class DroidEngineControl {
return ret; return ret;
} }
static String moveToString(Move m) { private static String moveToString(Move m) {
if (m == null) if (m == null)
return "0000"; return "0000";
String ret = TextIO.squareToString(m.from); String ret = TextIO.squareToString(m.from);
@@ -388,7 +388,7 @@ public class DroidEngineControl {
} else if (optionName.equals("strength")) { } else if (optionName.equals("strength")) {
strength = Integer.parseInt(optionValue); strength = Integer.parseInt(optionValue);
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException ignore) {
} }
} }
} }

View File

@@ -218,13 +218,13 @@ public class DroidChessController {
dis = new DataInputStream(bais); dis = new DataInputStream(bais);
game.readFromStream(dis, version); game.readFromStream(dis, version);
game.tree.translateMoves(); game.tree.translateMoves();
} catch (IOException e) { } catch (IOException ignore) {
} catch (ChessParseError e) { } catch (ChessParseError ignore) {
} finally { } finally {
if (dis != null) if (dis != null)
try { dis.close(); } catch (IOException ex) {} try { dis.close(); } catch (IOException ignore) {}
if (bais != null) if (bais != null)
try { bais.close(); } catch (IOException ex) {} try { bais.close(); } catch (IOException ignore) {}
} }
} }
@@ -242,9 +242,9 @@ public class DroidChessController {
return null; return null;
} finally { } finally {
if (dos != null) if (dos != null)
try { dos.close(); } catch (IOException ex) {} try { dos.close(); } catch (IOException ignore) {}
if (baos != null) if (baos != null)
try { baos.close(); } catch (IOException ex) {} try { baos.close(); } catch (IOException ignore) {}
} }
} }
@@ -775,8 +775,7 @@ public class DroidChessController {
if (ponderMove != null) { if (ponderMove != null) {
ArrayList<Move> tmp = new ArrayList<>(); ArrayList<Move> tmp = new ArrayList<>();
tmp.add(ponderMove); tmp.add(ponderMove);
for (Move m : pvInfoV.get(i).pv) tmp.addAll(pvInfoV.get(i).pv);
tmp.add(m);
pvMoves.add(tmp); pvMoves.add(tmp);
} else { } else {
pvMoves.add(pvInfoV.get(i).pv); pvMoves.add(pvInfoV.get(i).pv);

View File

@@ -255,7 +255,7 @@ public class Game {
try { try {
if (TextIO.readFEN(TextIO.startPosFEN).equals(currPos)) if (TextIO.readFEN(TextIO.startPosFEN).equals(currPos))
stopTimer = true; stopTimer = true;
} catch (ChessParseError e) { } catch (ChessParseError ignore) {
} }
} }
if (stopTimer) { if (stopTimer) {
@@ -382,7 +382,7 @@ public class Game {
updateTimeControl(true); updateTimeControl(true);
} }
public static enum GameState { public enum GameState {
ALIVE, ALIVE,
WHITE_MATE, // White mates WHITE_MATE, // White mates
BLACK_MATE, // Black mates BLACK_MATE, // Black mates

View File

@@ -37,7 +37,8 @@ import org.petero.droidfish.gamelogic.TimeControlData.TimeControlField;
public class GameTree { public class GameTree {
// Data from the seven tag roster (STR) part of the PGN standard // Data from the seven tag roster (STR) part of the PGN standard
String event, site, date, round, white, black; private String event, site, date, round;
public String white, black;
// Result is the last tag pair in the STR, but it is computed on demand from the game tree. // Result is the last tag pair in the STR, but it is computed on demand from the game tree.
public Position startPos; public Position startPos;
@@ -63,7 +64,7 @@ public class GameTree {
this.gameStateListener = gameStateListener; this.gameStateListener = gameStateListener;
try { try {
setStartPos(TextIO.readFEN(TextIO.startPosFEN)); setStartPos(TextIO.readFEN(TextIO.startPosFEN));
} catch (ChessParseError e) { } catch (ChessParseError ignore) {
} }
} }
@@ -114,11 +115,9 @@ public class GameTree {
ret.append(header); ret.append(header);
ret.append('\n'); ret.append('\n');
String[] words = sb.toString().split(" ");
int currLineLength = 0; int currLineLength = 0;
final int arrLen = words.length; for (String s : sb.toString().split(" ")) {
for (int i = 0; i < arrLen; i++) { String word = s.trim();
String word = words[i].trim();
int wordLen = word.length(); int wordLen = word.length();
if (wordLen > 0) { if (wordLen > 0) {
if (currLineLength == 0) { if (currLineLength == 0) {
@@ -1390,7 +1389,7 @@ public class GameTree {
break; break;
nodeToAdd.playerAction = cmdPars; nodeToAdd.playerAction = cmdPars;
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException ignore) {
} }
if (options.imp.comments) { if (options.imp.comments) {
if (moveAdded) if (moveAdded)
@@ -1605,10 +1604,9 @@ public class GameTree {
private ArrayList<TimeControlField> stringToTCFields(String tcStr) { private ArrayList<TimeControlField> stringToTCFields(String tcStr) {
String[] fields = tcStr.split(":"); String[] fields = tcStr.split(":");
int nf = fields.length; ArrayList<TimeControlField> ret = new ArrayList<>(fields.length);
ArrayList<TimeControlField> ret = new ArrayList<>(nf); for (String s : fields) {
for (int i = 0; i < nf; i++) { String f = s.trim();
String f = fields[i].trim();
if (f.equals("?") || f.equals("-") || f.contains("*")) { if (f.equals("?") || f.equals("-") || f.contains("*")) {
// Not supported // Not supported
} else { } else {
@@ -1625,8 +1623,7 @@ public class GameTree {
if (idx >= 0) { if (idx >= 0) {
if (idx > 0) if (idx > 0)
time = (int)(Double.parseDouble(f.substring(0, idx).trim())*1e3); time = (int)(Double.parseDouble(f.substring(0, idx).trim())*1e3);
if (idx >= 0) f = f.substring(idx+1);
f = f.substring(idx+1);
inc = (int)(Double.parseDouble(f.trim())*1e3); inc = (int)(Double.parseDouble(f.trim())*1e3);
} else { } else {
time = (int)(Double.parseDouble(f.trim())*1e3); time = (int)(Double.parseDouble(f.trim())*1e3);

View File

@@ -166,7 +166,7 @@ public class MoveGen {
/** /**
* Return true if a square is attacked by the opposite side. * Return true if a square is attacked by the opposite side.
*/ */
public static boolean sqAttacked(Position pos, int sq) { private static boolean sqAttacked(Position pos, int sq) {
int x = Position.getX(sq); int x = Position.getX(sq);
int y = Position.getY(sq); int y = Position.getY(sq);
boolean isWhiteMove = pos.whiteMove; boolean isWhiteMove = pos.whiteMove;

View File

@@ -42,7 +42,7 @@ class GtbProbe {
public void run() { public void run() {
// Sleep 0.5s to increase probability that engine // Sleep 0.5s to increase probability that engine
// is initialized before TB. // is initialized before TB.
try { Thread.sleep(500); } catch (InterruptedException e) { } try { Thread.sleep(500); } catch (InterruptedException ignore) { }
initIfNeeded(); initIfNeeded();
} }
}); });

View File

@@ -310,8 +310,7 @@ public class Probe {
} }
} }
} }
for (Move m : unknownMoves) optimalMoves.addAll(unknownMoves);
optimalMoves.add(m);
return (optimalMoves.size() < moveList.size()) ? optimalMoves : null; return (optimalMoves.size() < moveList.size()) ? optimalMoves : null;
} }

View File

@@ -20,7 +20,7 @@ package org.petero.droidfish.tb;
/** Tablebase probe result. */ /** Tablebase probe result. */
public final class ProbeResult implements Comparable<ProbeResult> { public final class ProbeResult implements Comparable<ProbeResult> {
public static enum Type { public enum Type {
DTM, // score is distance (full moves) to mate, or 0 DTM, // score is distance (full moves) to mate, or 0
DTZ, // score is distance (full moves) to zeroing move, or 0 DTZ, // score is distance (full moves) to zeroing move, or 0
WDL, // score is +-1 or 0 WDL, // score is +-1 or 0

View File

@@ -42,7 +42,7 @@ public class RtbProbe {
public void run() { public void run() {
// Sleep 0.4s to increase probability that engine // Sleep 0.4s to increase probability that engine
// is initialized before TB. // is initialized before TB.
try { Thread.sleep(400); } catch (InterruptedException e) { } try { Thread.sleep(400); } catch (InterruptedException ignore) { }
initIfNeeded(); initIfNeeded();
} }
}); });
@@ -82,7 +82,6 @@ public class RtbProbe {
* x>0: Win in x plies * x>0: Win in x plies
* x<0: Loss in -x plies * x<0: Loss in -x plies
* NOINFO: No info available * NOINFO: No info available
* @return True if success.
*/ */
public final native void probe(byte[] squares, public final native void probe(byte[] squares,
boolean wtm, boolean wtm,

View File

@@ -652,7 +652,7 @@ public abstract class ChessBoard extends View {
} }
public final void setMoveHints(List<Move> moveHints) { public final void setMoveHints(List<Move> moveHints) {
boolean equal = false; boolean equal;
if ((this.moveHints == null) || (moveHints == null)) { if ((this.moveHints == null) || (moveHints == null)) {
equal = this.moveHints == moveHints; equal = this.moveHints == moveHints;
} else { } else {
@@ -665,7 +665,7 @@ public abstract class ChessBoard extends View {
} }
public final void setSquareDecorations(ArrayList<SquareDecoration> decorations) { public final void setSquareDecorations(ArrayList<SquareDecoration> decorations) {
boolean equal = false; boolean equal;
if ((this.decorations == null) || (decorations == null)) { if ((this.decorations == null) || (decorations == null)) {
equal = this.decorations == decorations; equal = this.decorations == decorations;
} else { } else {