Fix some Android Studio warnings.

This commit is contained in:
Peter Osterlund
2019-03-17 22:35:02 +01:00
parent eaadffa6b0
commit 1a533ca1fb
62 changed files with 537 additions and 564 deletions

View File

@@ -33,9 +33,9 @@ public class AppletGUI extends javax.swing.JApplet implements GUIInterface {
private static final long serialVersionUID = 7357610346389734323L; private static final long serialVersionUID = 7357610346389734323L;
ChessBoardPainter cbp; ChessBoardPainter cbp;
ChessController ctrl; ChessController ctrl;
final static int ttLogSize = 19; // Use 2^19 hash entries. private final static int ttLogSize = 19; // Use 2^19 hash entries.
String moveListStr = ""; private String moveListStr = "";
String thinkingStr = ""; private String thinkingStr = "";
/** Initializes the applet AppletGUI */ /** Initializes the applet AppletGUI */
@Override @Override

View File

@@ -210,7 +210,7 @@ public class EngineControl {
} }
} }
private static final 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) {
@@ -220,7 +220,7 @@ public class EngineControl {
} }
} }
final private void startThread(final int minTimeLimit, final int maxTimeLimit, private void startThread(final int minTimeLimit, final int maxTimeLimit,
int maxDepth, final int maxNodes) { int maxDepth, final int maxNodes) {
synchronized (threadMutex) {} // Must not start new search until old search is finished synchronized (threadMutex) {} // Must not start new search until old search is finished
sc = new Search(pos, posHashList, posHashListSize, tt, ht); sc = new Search(pos, posHashList, posHashListSize, tt, ht);
@@ -339,7 +339,7 @@ public class EngineControl {
return ret; return ret;
} }
private static final 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);

View File

@@ -205,7 +205,7 @@ public class UCIProtocol {
} }
} }
final private void initEngine(PrintStream os) { private void initEngine(PrintStream os) {
if (engine == null) { if (engine == null) {
engine = new EngineControl(os); engine = new EngineControl(os);
} }

View File

@@ -94,11 +94,11 @@ public class CuckooChess extends Activity implements GUIInterface {
}); });
setContentView(R.layout.main); setContentView(R.layout.main);
status = (TextView)findViewById(R.id.status); status = findViewById(R.id.status);
moveListScroll = (ScrollView)findViewById(R.id.scrollView); moveListScroll = findViewById(R.id.scrollView);
moveList = (TextView)findViewById(R.id.moveList); moveList = findViewById(R.id.moveList);
thinking = (TextView)findViewById(R.id.thinking); thinking = findViewById(R.id.thinking);
cb = (ChessBoard)findViewById(R.id.chessboard); cb = findViewById(R.id.chessboard);
status.setFocusable(false); status.setFocusable(false);
moveListScroll.setFocusable(false); moveListScroll.setFocusable(false);
moveList.setFocusable(false); moveList.setFocusable(false);
@@ -193,7 +193,7 @@ public class CuckooChess extends Activity implements GUIInterface {
editor.putString("startFEN", posHistStr.get(0)); editor.putString("startFEN", posHistStr.get(0));
editor.putString("moves", posHistStr.get(1)); editor.putString("moves", posHistStr.get(1));
editor.putString("numUndo", posHistStr.get(2)); editor.putString("numUndo", posHistStr.get(2));
editor.commit(); editor.apply();
super.onPause(); super.onPause();
} }

View File

@@ -170,7 +170,7 @@ public class BitBoard {
0x000000007efa8146L, 0x0000007ed3e2ef60L, 0x00007f47243adcd6L, 0x007fb65afabfb3b5L 0x000000007efa8146L, 0x0000007ed3e2ef60L, 0x00007f47243adcd6L, 0x007fb65afabfb3b5L
}; };
private static final long createPattern(int i, long mask) { private static long createPattern(int i, long mask) {
long ret = 0L; long ret = 0L;
for (int j = 0; ; j++) { for (int j = 0; ; j++) {
long nextMask = mask & (mask - 1); long nextMask = mask & (mask - 1);
@@ -184,7 +184,7 @@ public class BitBoard {
return ret; return ret;
} }
private static final long addRookRays(int x, int y, long occupied, boolean inner) { private static long addRookRays(int x, int y, long occupied, boolean inner) {
long mask = 0; long mask = 0;
mask = addRay(mask, x, y, 1, 0, occupied, inner); mask = addRay(mask, x, y, 1, 0, occupied, inner);
mask = addRay(mask, x, y, -1, 0, occupied, inner); mask = addRay(mask, x, y, -1, 0, occupied, inner);
@@ -192,7 +192,7 @@ public class BitBoard {
mask = addRay(mask, x, y, 0, -1, occupied, inner); mask = addRay(mask, x, y, 0, -1, occupied, inner);
return mask; return mask;
} }
private static final long addBishopRays(int x, int y, long occupied, boolean inner) { private static long addBishopRays(int x, int y, long occupied, boolean inner) {
long mask = 0; long mask = 0;
mask = addRay(mask, x, y, 1, 1, occupied, inner); mask = addRay(mask, x, y, 1, 1, occupied, inner);
mask = addRay(mask, x, y, -1, -1, occupied, inner); mask = addRay(mask, x, y, -1, -1, occupied, inner);
@@ -201,7 +201,7 @@ public class BitBoard {
return mask; return mask;
} }
private static final long addRay(long mask, int x, int y, int dx, int dy, private static long addRay(long mask, int x, int y, int dx, int dy,
long occupied, boolean inner) { long occupied, boolean inner) {
int lo = inner ? 1 : 0; int lo = inner ? 1 : 0;
int hi = inner ? 6 : 7; int hi = inner ? 6 : 7;
@@ -270,11 +270,11 @@ public class BitBoard {
} }
} }
public static final long bishopAttacks(int sq, long occupied) { public static long bishopAttacks(int sq, long occupied) {
return bTables[sq][(int)(((occupied & bMasks[sq]) * bMagics[sq]) >>> (64 - bBits[sq]))]; return bTables[sq][(int)(((occupied & bMasks[sq]) * bMagics[sq]) >>> (64 - bBits[sq]))];
} }
public static final long rookAttacks(int sq, long occupied) { public static long rookAttacks(int sq, long occupied) {
return rTables[sq][(int)(((occupied & rMasks[sq]) * rMagics[sq]) >>> (64 - rBits[sq]))]; return rTables[sq][(int)(((occupied & rMasks[sq]) * rMagics[sq]) >>> (64 - rBits[sq]))];
} }
@@ -346,19 +346,19 @@ public class BitBoard {
0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
}; };
public static final int getDistance(int from, int to) { public static int getDistance(int from, int to) {
int offs = to + (to|7) - from - (from|7) + 0x77; int offs = to + (to|7) - from - (from|7) + 0x77;
return distTable[offs]; return distTable[offs];
} }
public static final long southFill(long mask) { public static long southFill(long mask) {
mask |= (mask >>> 8); mask |= (mask >>> 8);
mask |= (mask >>> 16); mask |= (mask >>> 16);
mask |= (mask >>> 32); mask |= (mask >>> 32);
return mask; return mask;
} }
public static final long northFill(long mask) { public static long northFill(long mask) {
mask |= (mask << 8); mask |= (mask << 8);
mask |= (mask << 16); mask |= (mask << 16);
mask |= (mask << 32); mask |= (mask << 32);

View File

@@ -161,7 +161,7 @@ public class Book {
throw new RuntimeException(); throw new RuntimeException();
} }
final private int getWeight(int count) { private int getWeight(int count) {
double tmp = Math.sqrt(count); double tmp = Math.sqrt(count);
return (int)(tmp * Math.sqrt(tmp) * 100 + 1); return (int)(tmp * Math.sqrt(tmp) * 100 + 1);
} }

View File

@@ -50,7 +50,7 @@ public class Evaluate {
} }
/** Piece/square table for king during middle game. */ /** Piece/square table for king during middle game. */
static final int[] kt1b = { -22,-35,-40,-40,-40,-40,-35,-22, private static final int[] kt1b = { -22,-35,-40,-40,-40,-40,-35,-22,
-22,-35,-40,-40,-40,-40,-35,-22, -22,-35,-40,-40,-40,-40,-35,-22,
-25,-35,-40,-45,-45,-40,-35,-25, -25,-35,-40,-45,-45,-40,-35,-25,
-15,-30,-35,-40,-40,-35,-30,-15, -15,-30,-35,-40,-40,-35,-30,-15,
@@ -60,7 +60,7 @@ public class Evaluate {
24, 24, 9, 0, 0, 9, 24, 24 }; 24, 24, 9, 0, 0, 9, 24, 24 };
/** Piece/square table for king during end game. */ /** Piece/square table for king during end game. */
static final int[] kt2b = { 0, 8, 16, 24, 24, 16, 8, 0, private static final int[] kt2b = { 0, 8, 16, 24, 24, 16, 8, 0,
8, 16, 24, 32, 32, 24, 16, 8, 8, 16, 24, 32, 32, 24, 16, 8,
16, 24, 32, 40, 40, 32, 24, 16, 16, 24, 32, 40, 40, 32, 24, 16,
24, 32, 40, 48, 48, 40, 32, 24, 24, 32, 40, 48, 48, 40, 32, 24,
@@ -70,7 +70,7 @@ public class Evaluate {
0, 8, 16, 24, 24, 16, 8, 0 }; 0, 8, 16, 24, 24, 16, 8, 0 };
/** Piece/square table for pawns during middle game. */ /** Piece/square table for pawns during middle game. */
static final int[] pt1b = { 0, 0, 0, 0, 0, 0, 0, 0, private static final int[] pt1b = { 0, 0, 0, 0, 0, 0, 0, 0,
8, 16, 24, 32, 32, 24, 16, 8, 8, 16, 24, 32, 32, 24, 16, 8,
3, 12, 20, 28, 28, 20, 12, 3, 3, 12, 20, 28, 28, 20, 12, 3,
-5, 4, 10, 20, 20, 10, 4, -5, -5, 4, 10, 20, 20, 10, 4, -5,
@@ -80,7 +80,7 @@ public class Evaluate {
0, 0, 0, 0, 0, 0, 0, 0 }; 0, 0, 0, 0, 0, 0, 0, 0 };
/** Piece/square table for pawns during end game. */ /** Piece/square table for pawns during end game. */
static final int[] pt2b = { 0, 0, 0, 0, 0, 0, 0, 0, private static final int[] pt2b = { 0, 0, 0, 0, 0, 0, 0, 0,
25, 40, 45, 45, 45, 45, 40, 25, 25, 40, 45, 45, 45, 45, 40, 25,
17, 32, 35, 35, 35, 35, 32, 17, 17, 32, 35, 35, 35, 35, 32, 17,
5, 24, 24, 24, 24, 24, 24, 5, 5, 24, 24, 24, 24, 24, 24, 5,
@@ -90,7 +90,7 @@ public class Evaluate {
0, 0, 0, 0, 0, 0, 0, 0 }; 0, 0, 0, 0, 0, 0, 0, 0 };
/** Piece/square table for knights during middle game. */ /** Piece/square table for knights during middle game. */
static final int[] nt1b = { -53,-42,-32,-21,-21,-32,-42,-53, private static final int[] nt1b = { -53,-42,-32,-21,-21,-32,-42,-53,
-42,-32,-10, 0, 0,-10,-32,-42, -42,-32,-10, 0, 0,-10,-32,-42,
-21, 5, 10, 16, 16, 10, 5,-21, -21, 5, 10, 16, 16, 10, 5,-21,
-18, 0, 10, 21, 21, 10, 0,-18, -18, 0, 10, 21, 21, 10, 0,-18,
@@ -100,7 +100,7 @@ public class Evaluate {
-53,-42,-32,-21,-21,-32,-42,-53 }; -53,-42,-32,-21,-21,-32,-42,-53 };
/** Piece/square table for knights during end game. */ /** Piece/square table for knights during end game. */
static final int[] nt2b = { -56,-44,-34,-22,-22,-34,-44,-56, private static final int[] nt2b = { -56,-44,-34,-22,-22,-34,-44,-56,
-44,-34,-10, 0, 0,-10,-34,-44, -44,-34,-10, 0, 0,-10,-34,-44,
-22, 5, 10, 17, 17, 10, 5,-22, -22, 5, 10, 17, 17, 10, 5,-22,
-19, 0, 10, 22, 22, 10, 0,-19, -19, 0, 10, 22, 22, 10, 0,-19,
@@ -110,7 +110,7 @@ public class Evaluate {
-56,-44,-34,-22,-22,-34,-44,-56 }; -56,-44,-34,-22,-22,-34,-44,-56 };
/** Piece/square table for bishops during middle game. */ /** Piece/square table for bishops during middle game. */
static final int[] bt1b = { 0, 0, 0, 0, 0, 0, 0, 0, private static final int[] bt1b = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 4, 2, 2, 2, 2, 4, 0, 0, 4, 2, 2, 2, 2, 4, 0,
0, 2, 4, 4, 4, 4, 2, 0, 0, 2, 4, 4, 4, 4, 2, 0,
0, 2, 4, 4, 4, 4, 2, 0, 0, 2, 4, 4, 4, 4, 2, 0,
@@ -120,7 +120,7 @@ public class Evaluate {
-5, -5, -7, -5, -5, -7, -5, -5 }; -5, -5, -7, -5, -5, -7, -5, -5 };
/** Piece/square table for bishops during middle game. */ /** Piece/square table for bishops during middle game. */
static final int[] bt2b = { 0, 0, 0, 0, 0, 0, 0, 0, private static final int[] bt2b = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0,
0, 2, 4, 4, 4, 4, 2, 0, 0, 2, 4, 4, 4, 4, 2, 0,
0, 2, 4, 4, 4, 4, 2, 0, 0, 2, 4, 4, 4, 4, 2, 0,
@@ -130,7 +130,7 @@ public class Evaluate {
0, 0, 0, 0, 0, 0, 0, 0 }; 0, 0, 0, 0, 0, 0, 0, 0 };
/** Piece/square table for queens during middle game. */ /** Piece/square table for queens during middle game. */
static final int[] qt1b = { -10, -5, 0, 0, 0, 0, -5,-10, private static final int[] qt1b = { -10, -5, 0, 0, 0, 0, -5,-10,
-5, 0, 5, 5, 5, 5, 0, -5, -5, 0, 5, 5, 5, 5, 0, -5,
0, 5, 5, 6, 6, 5, 5, 0, 0, 5, 5, 6, 6, 5, 5, 0,
0, 5, 6, 6, 6, 6, 5, 0, 0, 5, 6, 6, 6, 6, 5, 0,
@@ -140,7 +140,7 @@ public class Evaluate {
-10, -5, 0, 0, 0, 0, -5,-10 }; -10, -5, 0, 0, 0, 0, -5,-10 };
/** Piece/square table for rooks during middle game. */ /** Piece/square table for rooks during middle game. */
static final int[] rt1b = { 8, 11, 13, 13, 13, 13, 11, 8, private static final int[] rt1b = { 8, 11, 13, 13, 13, 13, 11, 8,
22, 27, 27, 27, 27, 27, 27, 22, 22, 27, 27, 27, 27, 27, 27, 22,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -149,7 +149,7 @@ public class Evaluate {
-3, 2, 5, 5, 5, 5, 2, -3, -3, 2, 5, 5, 5, 5, 2, -3,
0, 3, 5, 5, 5, 5, 3, 0 }; 0, 3, 5, 5, 5, 5, 3, 0 };
static final int[] kt1w, qt1w, rt1w, bt1w, nt1w, pt1w, kt2w, bt2w, nt2w, pt2w; private static final int[] kt1w, qt1w, rt1w, bt1w, nt1w, pt1w, kt2w, bt2w, nt2w, pt2w;
static { static {
kt1w = new int[64]; kt1w = new int[64];
qt1w = new int[64]; qt1w = new int[64];
@@ -193,9 +193,9 @@ public class Evaluate {
{ 6, 7, 6, 5, 4, 3, 2, 1 }, { 6, 7, 6, 5, 4, 3, 2, 1 },
{ 7, 6, 5, 4, 3, 2, 1, 0 } }; { 7, 6, 5, 4, 3, 2, 1, 0 } };
static final int[] rookMobScore = {-10,-7,-4,-1,2,5,7,9,11,12,13,14,14,14,14}; private static final int[] rookMobScore = {-10,-7,-4,-1,2,5,7,9,11,12,13,14,14,14,14};
static final int[] bishMobScore = {-15,-10,-6,-2,2,6,10,13,16,18,20,22,23,24}; private static final int[] bishMobScore = {-15,-10,-6,-2,2,6,10,13,16,18,20,22,23,24};
static final int[] queenMobScore = {-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,9,10,10,10,10,10,10,10,10,10,10,10,10}; private static final int[] queenMobScore = {-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,9,10,10,10,10,10,10,10,10,10,10,10,10};
private static final class PawnHashData { private static final class PawnHashData {
long key; long key;
@@ -205,7 +205,7 @@ public class Evaluate {
long passedPawnsW; // The most advanced passed pawns for each file long passedPawnsW; // The most advanced passed pawns for each file
long passedPawnsB; long passedPawnsB;
} }
static final PawnHashData[] pawnHash; private static final PawnHashData[] pawnHash;
static { static {
final int numEntries = 1<<16; final int numEntries = 1<<16;
pawnHash = new PawnHashData[numEntries]; pawnHash = new PawnHashData[numEntries];
@@ -217,8 +217,8 @@ public class Evaluate {
} }
} }
static byte[] kpkTable = null; private static byte[] kpkTable = null;
static byte[] krkpTable = null; private static byte[] krkpTable = null;
// King safety variables // King safety variables
private long wKingZone, bKingZone; // Squares close to king that are worth attacking private long wKingZone, bKingZone; // Squares close to king that are worth attacking
@@ -1135,7 +1135,7 @@ public class Evaluate {
return score; return score;
} }
private static final int evalKQKP(int wKing, int wQueen, int bKing, int bPawn, boolean whiteMove) { private static int evalKQKP(int wKing, int wQueen, int bKing, int bPawn, boolean whiteMove) {
boolean canWin = false; boolean canWin = false;
if (((1L << bKing) & 0xFFFF) == 0) { if (((1L << bKing) & 0xFFFF) == 0) {
canWin = true; // King doesn't support pawn canWin = true; // King doesn't support pawn
@@ -1172,7 +1172,7 @@ public class Evaluate {
return score; return score;
} }
private static final int kpkEval(int wKing, int bKing, int wPawn, boolean whiteMove) { private static int kpkEval(int wKing, int bKing, int wPawn, boolean whiteMove) {
if (Position.getX(wKing) >= 4) { // Mirror X if (Position.getX(wKing) >= 4) { // Mirror X
wKing ^= 7; wKing ^= 7;
bKing ^= 7; bKing ^= 7;
@@ -1191,7 +1191,7 @@ public class Evaluate {
return qV - pV / 4 * (7-Position.getY(wPawn)); return qV - pV / 4 * (7-Position.getY(wPawn));
} }
private static final int krkpEval(int wKing, int bKing, int bPawn, boolean whiteMove) { private static int krkpEval(int wKing, int bKing, int bPawn, boolean whiteMove) {
if (Position.getX(bKing) >= 4) { // Mirror X if (Position.getX(bKing) >= 4) { // Mirror X
wKing ^= 7; wKing ^= 7;
bKing ^= 7; bKing ^= 7;
@@ -1216,7 +1216,7 @@ public class Evaluate {
* Interpolate between (x1,y1) and (x2,y2). * Interpolate between (x1,y1) and (x2,y2).
* If x < x1, return y1, if x > x2 return y2. Otherwise, use linear interpolation. * If x < x1, return y1, if x > x2 return y2. Otherwise, use linear interpolation.
*/ */
static final int interpolate(int x, int x1, int y1, int x2, int y2) { static int interpolate(int x, int x1, int y1, int x2, int y2) {
if (x > x2) { if (x > x2) {
return y2; return y2;
} else if (x < x1) { } else if (x < x1) {

View File

@@ -545,7 +545,7 @@ public class Game {
return false; return false;
} }
final static long perfT(MoveGen moveGen, Position pos, int depth) { static long perfT(MoveGen moveGen, Position pos, int depth) {
if (depth == 0) if (depth == 0)
return 1; return 1;
long nodes = 0; long nodes = 0;

View File

@@ -28,7 +28,7 @@ public class KillerTable {
int move0; int move0;
int move1; int move1;
} }
KTEntry[] ktList; private KTEntry[] ktList;
/** Create an empty killer table. */ /** Create an empty killer table. */
public KillerTable() { public KillerTable() {

View File

@@ -717,7 +717,7 @@ public final class MoveGen {
/** /**
* Return true if the side to move is in check. * Return true if the side to move is in check.
*/ */
public static final boolean inCheck(Position pos) { public static boolean inCheck(Position pos) {
int kingSq = pos.getKingSq(pos.whiteMove); int kingSq = pos.getKingSq(pos.whiteMove);
return sqAttacked(pos, kingSq); return sqAttacked(pos, kingSq);
} }
@@ -725,7 +725,7 @@ public final class MoveGen {
/** /**
* Return the next piece in a given direction, starting from sq. * Return the next piece in a given direction, starting from sq.
*/ */
private static final int nextPiece(Position pos, int sq, int delta) { private static int nextPiece(Position pos, int sq, int delta) {
while (true) { while (true) {
sq += delta; sq += delta;
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
@@ -735,7 +735,7 @@ public final class MoveGen {
} }
/** Like nextPiece(), but handles board edges. */ /** Like nextPiece(), but handles board edges. */
private static final int nextPieceSafe(Position pos, int sq, int delta) { private static int nextPieceSafe(Position pos, int sq, int delta) {
int dx = 0, dy = 0; int dx = 0, dy = 0;
switch (delta) { switch (delta) {
case 1: dx=1; dy=0; break; case 1: dx=1; dy=0; break;
@@ -764,7 +764,7 @@ public final class MoveGen {
/** /**
* Return true if making a move delivers check to the opponent * Return true if making a move delivers check to the opponent
*/ */
public static final boolean givesCheck(Position pos, Move m) { public static boolean givesCheck(Position pos, Move m) {
boolean wtm = pos.whiteMove; boolean wtm = pos.whiteMove;
int oKingSq = pos.getKingSq(!wtm); int oKingSq = pos.getKingSq(!wtm);
int oKing = wtm ? Piece.BKING : Piece.WKING; int oKing = wtm ? Piece.BKING : Piece.WKING;
@@ -875,7 +875,7 @@ public final class MoveGen {
/** /**
* Return true if the side to move can take the opponents king. * Return true if the side to move can take the opponents king.
*/ */
public static final boolean canTakeKing(Position pos) { public static boolean canTakeKing(Position pos) {
pos.setWhiteMove(!pos.whiteMove); pos.setWhiteMove(!pos.whiteMove);
boolean ret = inCheck(pos); boolean ret = inCheck(pos);
pos.setWhiteMove(!pos.whiteMove); pos.setWhiteMove(!pos.whiteMove);
@@ -885,7 +885,7 @@ public final 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 final boolean sqAttacked(Position pos, int sq) { public static boolean sqAttacked(Position pos, int sq) {
if (pos.whiteMove) { if (pos.whiteMove) {
if ((BitBoard.knightAttacks[sq] & pos.pieceTypeBB[Piece.BKNIGHT]) != 0) if ((BitBoard.knightAttacks[sq] & pos.pieceTypeBB[Piece.BKNIGHT]) != 0)
return true; return true;
@@ -921,7 +921,7 @@ public final class MoveGen {
* "moveList" is assumed to be a list of pseudo-legal moves. * "moveList" is assumed to be a list of pseudo-legal moves.
* This function removes the moves that don't defend from check threats. * This function removes the moves that don't defend from check threats.
*/ */
public static final void removeIllegal(Position pos, MoveList moveList) { public static void removeIllegal(Position pos, MoveList moveList) {
int length = 0; int length = 0;
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();

View File

@@ -89,7 +89,7 @@ public class Parameters {
for (Map.Entry<String, ParamBase> e : params.entrySet()) for (Map.Entry<String, ParamBase> e : params.entrySet())
if (e.getValue().visible) if (e.getValue().visible)
parNames.add(e.getKey()); parNames.add(e.getKey());
return parNames.toArray(new String[parNames.size()]); return parNames.toArray(new String[0]);
} }
public final ParamBase getParam(String name) { public final ParamBase getParam(String name) {

View File

@@ -42,13 +42,13 @@ public class Piece {
* Return true if p is a white piece, false otherwise. * Return true if p is a white piece, false otherwise.
* Note that if p is EMPTY, an unspecified value is returned. * Note that if p is EMPTY, an unspecified value is returned.
*/ */
public static final boolean isWhite(int pType) { public static boolean isWhite(int pType) {
return pType < BKING; return pType < BKING;
} }
public static final int makeWhite(int pType) { public static int makeWhite(int pType) {
return pType < BKING ? pType : pType - (BKING - WKING); return pType < BKING ? pType : pType - (BKING - WKING);
} }
public static final int makeBlack(int pType) { public static int makeBlack(int pType) {
return ((pType > EMPTY) && (pType < BKING)) ? pType + (BKING - WKING) : pType; return ((pType > EMPTY) && (pType < BKING)) ? pType + (BKING - WKING) : pType;
} }
} }

View File

@@ -188,19 +188,19 @@ public class Position {
} }
} }
/** Return index in squares[] vector corresponding to (x,y). */ /** Return index in squares[] vector corresponding to (x,y). */
public final static int getSquare(int x, int y) { public static int getSquare(int x, int y) {
return y * 8 + x; return y * 8 + x;
} }
/** Return x position (file) corresponding to a square. */ /** Return x position (file) corresponding to a square. */
public final static int getX(int square) { public static int getX(int square) {
return square & 7; return square & 7;
} }
/** Return y position (rank) corresponding to a square. */ /** Return y position (rank) corresponding to a square. */
public final static int getY(int square) { public static int getY(int square) {
return square >> 3; return square >> 3;
} }
/** Return true if (x,y) is a dark square. */ /** Return true if (x,y) is a dark square. */
public final static boolean darkSquare(int x, int y) { public static boolean darkSquare(int x, int y) {
return (x & 1) == (y & 1); return (x & 1) == (y & 1);
} }

View File

@@ -28,15 +28,15 @@ public class Search {
final static int plyScale = 8; // Fractional ply resolution final static int plyScale = 8; // Fractional ply resolution
Position pos; Position pos;
MoveGen moveGen; private MoveGen moveGen;
Evaluate eval; private Evaluate eval;
KillerTable kt; private KillerTable kt;
History ht; private History ht;
long[] posHashList; // List of hashes for previous positions up to the last "zeroing" move. private long[] posHashList; // List of hashes for previous positions up to the last "zeroing" move.
int posHashListSize; // Number of used entries in posHashList private int posHashListSize; // Number of used entries in posHashList
int posHashFirstNew; // First entry in posHashList that has not been played OTB. private int posHashFirstNew; // First entry in posHashList that has not been played OTB.
TranspositionTable tt; private TranspositionTable tt;
TreeLogger log = null; private TreeLogger log = null;
private static final class SearchTreeInfo { private static final class SearchTreeInfo {
UndoInfo undoInfo; UndoInfo undoInfo;
@@ -53,35 +53,35 @@ public class Search {
bestMove = new Move(0, 0, 0); bestMove = new Move(0, 0, 0);
} }
} }
SearchTreeInfo[] searchTreeInfo; private SearchTreeInfo[] searchTreeInfo;
// Time management // Time management
long tStart; // Time when search started private long tStart; // Time when search started
long minTimeMillis; // Minimum recommended thinking time private long minTimeMillis; // Minimum recommended thinking time
long maxTimeMillis; // Maximum allowed thinking time long maxTimeMillis; // Maximum allowed thinking time
boolean searchNeedMoreTime; // True if negaScout should use up to maxTimeMillis time. private boolean searchNeedMoreTime; // True if negaScout should use up to maxTimeMillis time.
private long maxNodes; // Maximum number of nodes to search (approximately) private long maxNodes; // Maximum number of nodes to search (approximately)
int nodesToGo; // Number of nodes until next time check private int nodesToGo; // Number of nodes until next time check
public int nodesBetweenTimeCheck = 5000; // How often to check remaining time public int nodesBetweenTimeCheck = 5000; // How often to check remaining time
// Reduced strength variables // Reduced strength variables
private int strength = 1000; // Strength (0-1000) private int strength = 1000; // Strength (0-1000)
boolean weak = false; // Set to strength < 1000 private boolean weak = false; // Set to strength < 1000
long randomSeed = 0; private long randomSeed = 0;
// Search statistics stuff // Search statistics stuff
long nodes; private long nodes;
long qNodes; private long qNodes;
int[] nodesPlyVec; private int[] nodesPlyVec;
int[] nodesDepthVec; private int[] nodesDepthVec;
long totalNodes; private long totalNodes;
long tLastStats; // Time when notifyStats was last called private long tLastStats; // Time when notifyStats was last called
boolean verbose; private boolean verbose;
public final static int MATE0 = 32000; public final static int MATE0 = 32000;
public final static int UNKNOWN_SCORE = -32767; // Represents unknown static eval score public final static int UNKNOWN_SCORE = -32767; // Represents unknown static eval score
int q0Eval; // Static eval score at first level of quiescence search private int q0Eval; // Static eval score at first level of quiescence search
public Search(Position pos, long[] posHashList, int posHashListSize, TranspositionTable tt, public Search(Position pos, long[] posHashList, int posHashListSize, TranspositionTable tt,
History ht) { History ht) {
@@ -126,7 +126,7 @@ public class Search {
void notifyStats(long nodes, int nps, int time); void notifyStats(long nodes, int nps, int time);
} }
Listener listener; private Listener listener;
public void setListener(Listener listener) { public void setListener(Listener listener) {
this.listener = listener; this.listener = listener;
} }
@@ -905,7 +905,7 @@ public class Search {
return false; return false;
} }
private static final boolean passedPawnPush(Position pos, Move m) { private static boolean passedPawnPush(Position pos, Move m) {
int p = pos.getPiece(m.from); int p = pos.getPiece(m.from);
if (pos.whiteMove) { if (pos.whiteMove) {
if (p != Piece.WPAWN) if (p != Piece.WPAWN)
@@ -925,7 +925,7 @@ public class Search {
/** /**
* Quiescence search. Only non-losing captures are searched. * Quiescence search. Only non-losing captures are searched.
*/ */
final private int quiesce(int alpha, int beta, int ply, int depth, final boolean inCheck) { private int quiesce(int alpha, int beta, int ply, int depth, final boolean inCheck) {
int score; int score;
if (inCheck) { if (inCheck) {
score = -(MATE0 - (ply+1)); score = -(MATE0 - (ply+1));
@@ -1219,7 +1219,7 @@ public class Search {
/** /**
* Find move with highest score and move it to the front of the list. * Find move with highest score and move it to the front of the list.
*/ */
final static void selectBest(MoveGen.MoveList moves, int startIdx) { static void selectBest(MoveGen.MoveList moves, int startIdx) {
int bestIdx = startIdx; int bestIdx = startIdx;
int bestScore = moves.m[bestIdx].score; int bestScore = moves.m[bestIdx].score;
for (int i = startIdx + 1; i < moves.size; i++) { for (int i = startIdx + 1; i < moves.size; i++) {
@@ -1237,7 +1237,7 @@ public class Search {
} }
/** If hashMove exists in the move list, move the hash move to the front of the list. */ /** If hashMove exists in the move list, move the hash move to the front of the list. */
final static boolean selectHashMove(MoveGen.MoveList moves, Move hashMove) { static boolean selectHashMove(MoveGen.MoveList moves, Move hashMove) {
if (hashMove == null) { if (hashMove == null) {
return false; return false;
} }
@@ -1253,11 +1253,11 @@ public class Search {
return false; return false;
} }
public final static boolean canClaimDraw50(Position pos) { public static boolean canClaimDraw50(Position pos) {
return (pos.halfMoveClock >= 100); return (pos.halfMoveClock >= 100);
} }
public final static boolean canClaimDrawRep(Position pos, long[] posHashList, int posHashListSize, int posHashFirstNew) { public static boolean canClaimDrawRep(Position pos, long[] posHashList, int posHashListSize, int posHashFirstNew) {
int reps = 0; int reps = 0;
for (int i = posHashListSize - 4; i >= 0; i -= 2) { for (int i = posHashListSize - 4; i >= 0; i -= 2) {
if (pos.zobristHash() == posHashList[i]) { if (pos.zobristHash() == posHashList[i]) {

View File

@@ -24,7 +24,7 @@ public class TextIO {
static public final String startPosFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; static public final String startPosFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
/** Parse a FEN string and return a chess Position object. */ /** Parse a FEN string and return a chess Position object. */
public static final Position readFEN(String fen) throws ChessParseError { public static Position readFEN(String fen) throws ChessParseError {
Position pos = new Position(); Position pos = new Position();
String[] words = fen.split(" "); String[] words = fen.split(" ");
if (words.length < 2) { if (words.length < 2) {
@@ -148,7 +148,7 @@ public class TextIO {
} }
/** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */ /** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */
public static final void fixupEPSquare(Position pos) { public static void fixupEPSquare(Position pos) {
int epSquare = pos.getEpSquare(); int epSquare = pos.getEpSquare();
if (epSquare >= 0) { if (epSquare >= 0) {
MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos); MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos);
@@ -169,7 +169,7 @@ public class TextIO {
} }
} }
private static final void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError { private static void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError {
if (row < 0) throw new ChessParseError("Too many rows"); if (row < 0) throw new ChessParseError("Too many rows");
if (col > 7) throw new ChessParseError("Too many columns"); if (col > 7) throw new ChessParseError("Too many columns");
if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) { if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) {
@@ -180,7 +180,7 @@ public class TextIO {
} }
/** Return a FEN string corresponding to a chess Position object. */ /** Return a FEN string corresponding to a chess Position object. */
public static final String toFEN(Position pos) { public static String toFEN(Position pos) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
// Piece placement // Piece placement
for (int r = 7; r >=0; r--) { for (int r = 7; r >=0; r--) {
@@ -271,12 +271,12 @@ public class TextIO {
* @param longForm If true, use long notation, eg Ng1-f3. * @param longForm If true, use long notation, eg Ng1-f3.
* Otherwise, use short notation, eg Nf3 * Otherwise, use short notation, eg Nf3
*/ */
public static final String moveToString(Position pos, Move move, boolean longForm) { public static String moveToString(Position pos, Move move, boolean longForm) {
MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos); MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos, moves); MoveGen.removeIllegal(pos, moves);
return moveToString(pos, move, longForm, moves); return moveToString(pos, move, longForm, moves);
} }
private static final String moveToString(Position pos, Move move, boolean longForm, MoveGen.MoveList moves) { private static String moveToString(Position pos, Move move, boolean longForm, MoveGen.MoveList moves) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int wKingOrigPos = Position.getSquare(4, 0); int wKingOrigPos = Position.getSquare(4, 0);
int bKingOrigPos = Position.getSquare(4, 7); int bKingOrigPos = Position.getSquare(4, 7);
@@ -365,7 +365,7 @@ public class TextIO {
} }
/** Convert a move object to UCI string format. */ /** Convert a move object to UCI string format. */
public static final String moveToUCIString(Move m) { public static String moveToUCIString(Move m) {
String ret = squareToString(m.from); String ret = squareToString(m.from);
ret += squareToString(m.to); ret += squareToString(m.to);
switch (m.promoteTo) { switch (m.promoteTo) {
@@ -395,7 +395,7 @@ public class TextIO {
* Convert a string to a Move object. * Convert a string to a Move object.
* @return A move object, or null if move has invalid syntax * @return A move object, or null if move has invalid syntax
*/ */
public static final Move uciStringToMove(String move) { public static Move uciStringToMove(String move) {
Move m = null; Move m = null;
if ((move.length() < 4) || (move.length() > 5)) if ((move.length() < 4) || (move.length() > 5))
return m; return m;
@@ -440,7 +440,7 @@ public class TextIO {
return m; return m;
} }
private static final 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())) { if ((p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare())) {
@@ -458,7 +458,7 @@ public class TextIO {
* Any prefix of the string representation of a valid move counts as a legal move string, * Any prefix of the string representation of a valid move counts as a legal move string,
* as long as the string only matches one valid move. * as long as the string only matches one valid move.
*/ */
public static final Move stringToMove(Position pos, String strMove) { public static Move stringToMove(Position pos, String strMove) {
strMove = strMove.replaceAll("=", ""); strMove = strMove.replaceAll("=", "");
Move move = null; Move move = null;
if (strMove.length() == 0) if (strMove.length() == 0)
@@ -533,7 +533,7 @@ public class TextIO {
* Convert a string, such as "e4" to a square number. * Convert a string, such as "e4" to a square number.
* @return The square number, or -1 if not a legal square. * @return The square number, or -1 if not a legal square.
*/ */
public static final int getSquare(String s) { public static int getSquare(String s) {
int x = s.charAt(0) - 'a'; int x = s.charAt(0) - 'a';
int y = s.charAt(1) - '1'; int y = s.charAt(1) - '1';
if ((x < 0) || (x > 7) || (y < 0) || (y > 7)) if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
@@ -544,7 +544,7 @@ public class TextIO {
/** /**
* Convert a square number to a string, such as "e4". * Convert a square number to a string, such as "e4".
*/ */
public static final String squareToString(int square) { public static String squareToString(int square) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int x = Position.getX(square); int x = Position.getX(square);
int y = Position.getY(square); int y = Position.getY(square);
@@ -556,7 +556,7 @@ public class TextIO {
/** /**
* Create an ascii representation of a position. * Create an ascii representation of a position.
*/ */
public static final String asciiBoard(Position pos) { public static String asciiBoard(Position pos) {
StringBuilder ret = new StringBuilder(400); StringBuilder ret = new StringBuilder(400);
String nl = String.format(Locale.US, "%n"); String nl = String.format(Locale.US, "%n");
ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl);
@@ -587,7 +587,7 @@ public class TextIO {
/** /**
* Convert move string to lower case and remove special check/mate symbols. * Convert move string to lower case and remove special check/mate symbols.
*/ */
private static final String normalizeMoveString(String str) { private static String normalizeMoveString(String str) {
if (str.length() > 0) { if (str.length() > 0) {
char lastChar = str.charAt(str.length() - 1); char lastChar = str.charAt(str.length() - 1);
if ((lastChar == '#') || (lastChar == '+')) { if ((lastChar == '#') || (lastChar == '+')) {
@@ -597,7 +597,7 @@ public class TextIO {
return str; return str;
} }
private final static String pieceToChar(int p) { private static String pieceToChar(int p) {
switch (p) { switch (p) {
case Piece.WQUEEN: case Piece.BQUEEN: return "Q"; case Piece.WQUEEN: case Piece.BQUEEN: return "Q";
case Piece.WROOK: case Piece.BROOK: return "R"; case Piece.WROOK: case Piece.BROOK: return "R";

View File

@@ -52,7 +52,7 @@ public final class TreeLogger {
} }
/** Get a logger object set up for writing to a log file. */ /** Get a logger object set up for writing to a log file. */
public static final TreeLogger getWriter(String filename, Position pos) { public static TreeLogger getWriter(String filename, Position pos) {
try { try {
TreeLogger log = new TreeLogger(); TreeLogger log = new TreeLogger();
log.os = new FileOutputStream(filename); log.os = new FileOutputStream(filename);
@@ -80,7 +80,7 @@ public final class TreeLogger {
} }
/** Get a logger object set up for analyzing a log file. */ /** Get a logger object set up for analyzing a log file. */
public static final TreeLogger getAnalyzer(String filename) { public static TreeLogger getAnalyzer(String filename) {
RandomAccessFile raf = null; RandomAccessFile raf = null;
try { try {
TreeLogger log = new TreeLogger(); TreeLogger log = new TreeLogger();
@@ -191,7 +191,7 @@ public final class TreeLogger {
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Functions used for tree analyzing // Functions used for tree analyzing
private static final int indexToFileOffs(int index) { private static int indexToFileOffs(int index) {
return 128 + index * 16; return 128 + index * 16;
} }
@@ -211,7 +211,7 @@ public final class TreeLogger {
} }
mapBuf.put(127, (byte)(1 << 7)); mapBuf.put(127, (byte)(1 << 7));
mapBuf.force(); mapBuf.force();
System.out.printf("Computing forward pointers... done\n"); System.out.print("Computing forward pointers... done\n");
} }
/** Get FEN string for root node position. */ /** Get FEN string for root node position. */
@@ -220,8 +220,7 @@ public final class TreeLogger {
byte[] fenB = new byte[len]; byte[] fenB = new byte[len];
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
fenB[i] = mapBuf.get(1+i); fenB[i] = mapBuf.get(1+i);
String ret = new String(fenB); return new String(fenB);
return ret;
} }
static final class StartEntry { static final class StartEntry {
@@ -271,9 +270,9 @@ public final class TreeLogger {
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Functions used for the interactive tree browser // Functions used for the interactive tree browser
public static final void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
if (args.length != 1) { if (args.length != 1) {
System.out.printf("Usage: progname filename\n"); System.out.print("Usage: progname filename\n");
System.exit(1); System.exit(1);
} }
TreeLogger an = getAnalyzer(args[0]); TreeLogger an = getAnalyzer(args[0]);
@@ -445,7 +444,7 @@ public final class TreeLogger {
} }
/** Get integer parameter from an input string. */ /** Get integer parameter from an input string. */
private static final int getArg(String s, int defVal) { private static int getArg(String s, int defVal) {
try { try {
int idx = s.indexOf(' '); int idx = s.indexOf(' ');
if (idx > 0) { if (idx > 0) {
@@ -472,7 +471,7 @@ public final class TreeLogger {
} }
/** Get a string parameter from an input string. */ /** Get a string parameter from an input string. */
private static final String getArgStr(String s, String defVal) { private static String getArgStr(String s, String defVal) {
int idx = s.indexOf(' '); int idx = s.indexOf(' ');
if (idx > 0) if (idx > 0)
return s.substring(idx+1); return s.substring(idx+1);
@@ -480,16 +479,16 @@ public final class TreeLogger {
} }
private void printHelp() { private void printHelp() {
System.out.printf(" p - Print move sequence\n"); System.out.print(" p - Print move sequence\n");
System.out.printf(" n - Print node info corresponding to move sequence\n"); System.out.print(" n - Print node info corresponding to move sequence\n");
System.out.printf(" l [move] - List child nodes, optionally only for one move\n"); System.out.print(" l [move] - List child nodes, optionally only for one move\n");
System.out.printf(" d [n1 [n2...]] - Go to child \"n\"\n"); System.out.print(" d [n1 [n2...]] - Go to child \"n\"\n");
System.out.printf(" move - Go to child \"move\", if unique\n"); System.out.print(" move - Go to child \"move\", if unique\n");
System.out.printf(" u [levels] - Move up\n"); System.out.print(" u [levels] - Move up\n");
System.out.printf(" h [key] - Find nodes with current (or given) hash key\n"); System.out.print(" h [key] - Find nodes with current (or given) hash key\n");
System.out.printf(" num - Go to node \"num\"\n"); System.out.print(" num - Go to node \"num\"\n");
System.out.printf(" q - Quit\n"); System.out.print(" q - Quit\n");
System.out.printf(" ? - Print this help\n"); System.out.print(" ? - Print this help\n");
} }
/** Read start/end entries for a tree node. Return true if the end entry exists. */ /** Read start/end entries for a tree node. Return true if the end entry exists. */

View File

@@ -436,7 +436,7 @@ public class ChessController {
* Move a piece from one square to another. * Move a piece from one square to another.
* @return True if the move was legal, false otherwise. * @return True if the move was legal, false otherwise.
*/ */
final private boolean doMove(Move move) { private boolean doMove(Move move) {
Position pos = game.pos; Position pos = game.pos;
MoveGen.MoveList moves = new MoveGen().pseudoLegalMoves(pos); MoveGen.MoveList moves = new MoveGen().pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos, moves); MoveGen.removeIllegal(pos, moves);
@@ -461,14 +461,14 @@ public class ChessController {
} }
final private void updateGUI() { private void updateGUI() {
setStatusString(); setStatusString();
setMoveList(); setMoveList();
setThinkingPV(); setThinkingPV();
gui.setPosition(game.pos); gui.setPosition(game.pos);
} }
final private void setStatusString() { private void setStatusString() {
String str = game.pos.whiteMove ? "White's move" : "Black's move"; String str = game.pos.whiteMove ? "White's move" : "Black's move";
if (computerThread != null) str += " (thinking)"; if (computerThread != null) str += " (thinking)";
if (game.getGameState() != GameState.ALIVE) { if (game.getGameState() != GameState.ALIVE) {
@@ -490,7 +490,7 @@ public class ChessController {
gui.setThinkingString(str); gui.setThinkingString(str);
} }
final private void setSelection() { private void setSelection() {
Move m = game.getLastMove(); Move m = game.getLastMove();
int sq = (m != null) ? m.to : -1; int sq = (m != null) ? m.to : -1;
gui.setSelection(sq); gui.setSelection(sq);

View File

@@ -99,7 +99,7 @@ public class BitBoardTest {
* If there is a piece type that can move from "from" to "to", return the * If there is a piece type that can move from "from" to "to", return the
* corresponding direction, 8*dy+dx. * corresponding direction, 8*dy+dx.
*/ */
private static final int computeDirection(int from, int to) { private static int computeDirection(int from, int to) {
int dx = Position.getX(to) - Position.getX(from); int dx = Position.getX(to) - Position.getX(from);
int dy = Position.getY(to) - Position.getY(from); int dy = Position.getY(to) - Position.getY(from);
if (dx == 0) { // Vertical rook direction if (dx == 0) { // Vertical rook direction
@@ -125,7 +125,7 @@ public class BitBoardTest {
} }
} }
private static final int computeDistance(int from, int to) { private static int computeDistance(int from, int to) {
int dx = Position.getX(to) - Position.getX(from); int dx = Position.getX(to) - Position.getX(from);
int dy = Position.getY(to) - Position.getY(from); int dy = Position.getY(to) - Position.getY(from);
return Math.max(Math.abs(dx), Math.abs(dy)); return Math.max(Math.abs(dx), Math.abs(dy));

View File

@@ -471,7 +471,7 @@ public class EvaluateTest {
} }
/** Return static evaluation score for white, regardless of whose turn it is to move. */ /** Return static evaluation score for white, regardless of whose turn it is to move. */
final static int evalWhite(Position pos) { static int evalWhite(Position pos) {
Evaluate eval = new Evaluate(); Evaluate eval = new Evaluate();
int ret = eval.evalPos(pos); int ret = eval.evalPos(pos);
Position symPos = swapColors(pos); Position symPos = swapColors(pos);
@@ -483,7 +483,7 @@ public class EvaluateTest {
return ret; return ret;
} }
final static Position swapColors(Position pos) { static Position swapColors(Position pos) {
Position sym = new Position(); Position sym = new Position();
sym.whiteMove = !pos.whiteMove; sym.whiteMove = !pos.whiteMove;
for (int x = 0; x < 8; x++) { for (int x = 0; x < 8; x++) {

View File

@@ -26,9 +26,9 @@ import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class SearchTest { public class SearchTest {
static final long[] nullHist = new long[200]; private static final long[] nullHist = new long[200];
static TranspositionTable tt = new TranspositionTable(19); private static TranspositionTable tt = new TranspositionTable(19);
static History ht = new History(); private static History ht = new History();
public SearchTest() { public SearchTest() {
} }

View File

@@ -242,7 +242,7 @@ public class GameTreeTest extends TestCase {
assertEquals(0, gt.currentNode.defaultChild); assertEquals(0, gt.currentNode.defaultChild);
} }
final static String getVariationsAsString(GameTree gt) { static String getVariationsAsString(GameTree gt) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
List<Move> vars = gt.variations(); List<Move> vars = gt.variations();
for (int i = 0; i < vars.size(); i++) { for (int i = 0; i < vars.size(); i++) {

View File

@@ -66,9 +66,9 @@ public class ColorPickerDialog
setTitle(getContext().getText(R.string.prefs_colors_title) + " '" setTitle(getContext().getText(R.string.prefs_colors_title) + " '"
+ additionalInfo + "'"); + additionalInfo + "'");
mColorPicker = (ColorPickerView) findViewById(R.id.color_picker_view); mColorPicker = findViewById(R.id.color_picker_view);
mOldColor = (ColorPickerPanelView) findViewById(R.id.old_color_panel); mOldColor = findViewById(R.id.old_color_panel);
mNewColor = (ColorPickerPanelView) findViewById(R.id.new_color_panel); mNewColor = findViewById(R.id.new_color_panel);
((LinearLayout) mOldColor.getParent()).setPadding( ((LinearLayout) mOldColor.getParent()).setPadding(
Math.round(mColorPicker.getDrawingOffset()), Math.round(mColorPicker.getDrawingOffset()),

View File

@@ -104,7 +104,7 @@ public class ColorPickerPreference
private void setPreviewColor() { private void setPreviewColor() {
if (mView == null) return; if (mView == null) return;
ImageView iView = new ImageView(getContext()); ImageView iView = new ImageView(getContext());
LinearLayout widgetFrameView = ((LinearLayout)mView.findViewById(android.R.id.widget_frame)); LinearLayout widgetFrameView = mView.findViewById(android.R.id.widget_frame);
if (widgetFrameView == null) return; if (widgetFrameView == null) return;
widgetFrameView.setVisibility(View.VISIBLE); widgetFrameView.setVisibility(View.VISIBLE);
widgetFrameView.setPadding( widgetFrameView.setPadding(

View File

@@ -150,7 +150,7 @@ public class ChessBoardPlay extends ChessBoard {
userSelectedSquare = false; userSelectedSquare = false;
return matchingMove; return matchingMove;
} }
if (!anyMatch && (sq >= 0)) { if (!anyMatch) {
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
if (myColor(p)) { if (myColor(p)) {
String msg = getContext().getString(R.string.piece_can_not_be_moved); String msg = getContext().getString(R.string.piece_can_not_be_moved);

View File

@@ -26,7 +26,7 @@ public class ColorTheme {
private static ColorTheme inst = null; private static ColorTheme inst = null;
/** Get singleton instance. */ /** Get singleton instance. */
public static final ColorTheme instance() { public static ColorTheme instance() {
if (inst == null) if (inst == null)
inst = new ColorTheme(); inst = new ColorTheme();
return inst; return inst;
@@ -130,7 +130,7 @@ public class ColorTheme {
Editor editor = settings.edit(); Editor editor = settings.edit();
for (int i = 0; i < numColors; i++) for (int i = 0; i < numColors; i++)
editor.putString(prefPrefix + prefNames[i], themeColors[themeType][i]); editor.putString(prefPrefix + prefNames[i], themeColors[themeType][i]);
editor.commit(); editor.apply();
readColors(settings); readColors(settings);
} }

View File

@@ -217,7 +217,7 @@ public class DroidFish extends Activity
private ImageButton modeButton, undoButton, redoButton; private ImageButton modeButton, undoButton, redoButton;
private ButtonActions custom1ButtonActions, custom2ButtonActions, custom3ButtonActions; private ButtonActions custom1ButtonActions, custom2ButtonActions, custom3ButtonActions;
private TextView whiteTitleText, blackTitleText, engineTitleText; private TextView whiteTitleText, blackTitleText, engineTitleText;
private View firstTitleLine, secondTitleLine; private View secondTitleLine;
private TextView whiteFigText, blackFigText, summaryTitleText; private TextView whiteFigText, blackFigText, summaryTitleText;
private Dialog moveListMenuDlg; private Dialog moveListMenuDlg;
@@ -239,12 +239,11 @@ public class DroidFish extends Activity
private boolean vibrateEnabled; private boolean vibrateEnabled;
private boolean animateMoves; private boolean animateMoves;
private boolean autoScrollTitle; private boolean autoScrollTitle;
private boolean showMaterialDiff;
private boolean showVariationLine; private boolean showVariationLine;
private int autoMoveDelay; // Delay in auto forward/backward mode private int autoMoveDelay; // Delay in auto forward/backward mode
private static enum AutoMode { private enum AutoMode {
OFF, FORWARD, BACKWARD; OFF, FORWARD, BACKWARD
} }
private AutoMode autoMode = AutoMode.OFF; private AutoMode autoMode = AutoMode.OFF;
@@ -253,7 +252,7 @@ public class DroidFish extends Activity
private int ECO_HINTS_ALWAYS = 2; private int ECO_HINTS_ALWAYS = 2;
/** State of requested permissions. */ /** State of requested permissions. */
private static enum PermissionState { private enum PermissionState {
UNKNOWN, UNKNOWN,
REQUESTED, REQUESTED,
GRANTED, GRANTED,
@@ -277,8 +276,6 @@ public class DroidFish extends Activity
private PgnScreenText gameTextListener; private PgnScreenText gameTextListener;
private boolean useWakeLock = false;
private Typeface figNotation; private Typeface figNotation;
private Typeface defaultThinkingListTypeFace; private Typeface defaultThinkingListTypeFace;
@@ -436,16 +433,16 @@ public class DroidFish extends Activity
public void run() { public void run() {
String numArrows = settings.getString("thinkingArrows", "4"); String numArrows = settings.getString("thinkingArrows", "4");
Editor editor = settings.edit(); Editor editor = settings.edit();
if (!numArrows.equals("0")) { if (!"0".equals(numArrows)) {
editor.putString("thinkingArrows", "0"); editor.putString("thinkingArrows", "0");
editor.putString("oldThinkingArrows", numArrows); editor.putString("oldThinkingArrows", numArrows);
} else { } else {
String oldNumArrows = settings.getString("oldThinkingArrows", "0"); String oldNumArrows = settings.getString("oldThinkingArrows", "0");
if (oldNumArrows.equals("0")) if ("0".equals(oldNumArrows))
oldNumArrows = "4"; oldNumArrows = "4";
editor.putString("thinkingArrows", oldNumArrows); editor.putString("thinkingArrows", oldNumArrows);
} }
editor.commit(); editor.apply();
maxNumArrows = getIntSetting("thinkingArrows", 4); maxNumArrows = getIntSetting("thinkingArrows", 4);
updateThinkingInfo(); updateThinkingInfo();
} }
@@ -673,14 +670,14 @@ public class DroidFish extends Activity
guideShowOnStart = false; guideShowOnStart = false;
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putBoolean("guideShowOnStart", false); editor.putBoolean("guideShowOnStart", false);
editor.commit(); editor.apply();
tourGuide.next(); tourGuide.next();
tourGuide = null; tourGuide = null;
} }
})); }));
Sequence sequence = new Sequence.SequenceBuilder() Sequence sequence = new Sequence.SequenceBuilder()
.add(guides.toArray(new TourGuide[guides.size()])) .add(guides.toArray(new TourGuide[0]))
.setDefaultOverlay(new Overlay() .setDefaultOverlay(new Overlay()
.setOnClickListener(new OnClickListener() { .setOnClickListener(new OnClickListener() {
@Override @Override
@@ -841,9 +838,8 @@ public class DroidFish extends Activity
if (data == null) if (data == null)
return null; return null;
StringBuilder ret = new StringBuilder(32768); StringBuilder ret = new StringBuilder(32768);
int nBytes = data.length; for (int b : data) {
for (int i = 0; i < nBytes; i++) { if (b < 0) b += 256;
int b = data[i]; if (b < 0) b += 256;
char c1 = (char)('A' + (b / 16)); char c1 = (char)('A' + (b / 16));
char c2 = (char)('A' + (b & 15)); char c2 = (char)('A' + (b & 15));
ret.append(c1); ret.append(c1);
@@ -914,28 +910,28 @@ public class DroidFish extends Activity
overrideViewAttribs(); overrideViewAttribs();
// title lines need to be regenerated every time due to layout changes (rotations) // title lines need to be regenerated every time due to layout changes (rotations)
firstTitleLine = findViewById(R.id.first_title_line); View firstTitleLine = findViewById(R.id.first_title_line);
secondTitleLine = findViewById(R.id.second_title_line); secondTitleLine = findViewById(R.id.second_title_line);
whiteTitleText = (TextView)findViewById(R.id.white_clock); whiteTitleText = findViewById(R.id.white_clock);
whiteTitleText.setSelected(true); whiteTitleText.setSelected(true);
blackTitleText = (TextView)findViewById(R.id.black_clock); blackTitleText = findViewById(R.id.black_clock);
blackTitleText.setSelected(true); blackTitleText.setSelected(true);
engineTitleText = (TextView)findViewById(R.id.title_text); engineTitleText = findViewById(R.id.title_text);
whiteFigText = (TextView)findViewById(R.id.white_pieces); whiteFigText = findViewById(R.id.white_pieces);
whiteFigText.setTypeface(figNotation); whiteFigText.setTypeface(figNotation);
whiteFigText.setSelected(true); whiteFigText.setSelected(true);
whiteFigText.setTextColor(whiteTitleText.getTextColors()); whiteFigText.setTextColor(whiteTitleText.getTextColors());
blackFigText = (TextView)findViewById(R.id.black_pieces); blackFigText = findViewById(R.id.black_pieces);
blackFigText.setTypeface(figNotation); blackFigText.setTypeface(figNotation);
blackFigText.setSelected(true); blackFigText.setSelected(true);
blackFigText.setTextColor(blackTitleText.getTextColors()); blackFigText.setTextColor(blackTitleText.getTextColors());
summaryTitleText = (TextView)findViewById(R.id.title_text_summary); summaryTitleText = findViewById(R.id.title_text_summary);
status = (TextView)findViewById(R.id.status); status = findViewById(R.id.status);
moveListScroll = (ScrollView)findViewById(R.id.scrollView); moveListScroll = findViewById(R.id.scrollView);
moveList = (MoveListView)findViewById(R.id.moveList); moveList = findViewById(R.id.moveList);
thinkingScroll = (View)findViewById(R.id.scrollViewBot); thinkingScroll = findViewById(R.id.scrollViewBot);
thinking = (TextView)findViewById(R.id.thinking); thinking = findViewById(R.id.thinking);
defaultThinkingListTypeFace = thinking.getTypeface(); defaultThinkingListTypeFace = thinking.getTypeface();
status.setFocusable(false); status.setFocusable(false);
moveListScroll.setFocusable(false); moveListScroll.setFocusable(false);
@@ -965,7 +961,7 @@ public class DroidFish extends Activity
secondTitleLine.setOnClickListener(listener); secondTitleLine.setOnClickListener(listener);
secondTitleLine.setOnTouchListener(listener); secondTitleLine.setOnTouchListener(listener);
cb = (ChessBoardPlay)findViewById(R.id.chessboard); cb = findViewById(R.id.chessboard);
cb.setFocusable(true); cb.setFocusable(true);
cb.requestFocus(); cb.requestFocus();
cb.setClickable(true); cb.setClickable(true);
@@ -1146,15 +1142,15 @@ public class DroidFish extends Activity
} }
}); });
buttons = (View)findViewById(R.id.buttons); buttons = findViewById(R.id.buttons);
custom1Button = (ImageButton)findViewById(R.id.custom1Button); custom1Button = findViewById(R.id.custom1Button);
custom1ButtonActions.setImageButton(custom1Button, this); custom1ButtonActions.setImageButton(custom1Button, this);
custom2Button = (ImageButton)findViewById(R.id.custom2Button); custom2Button = findViewById(R.id.custom2Button);
custom2ButtonActions.setImageButton(custom2Button, this); custom2ButtonActions.setImageButton(custom2Button, this);
custom3Button = (ImageButton)findViewById(R.id.custom3Button); custom3Button = findViewById(R.id.custom3Button);
custom3ButtonActions.setImageButton(custom3Button, this); custom3ButtonActions.setImageButton(custom3Button, this);
modeButton = (ImageButton)findViewById(R.id.modeButton); modeButton = findViewById(R.id.modeButton);
modeButton.setOnClickListener(new OnClickListener() { modeButton.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@@ -1168,7 +1164,7 @@ public class DroidFish extends Activity
return true; return true;
} }
}); });
undoButton = (ImageButton)findViewById(R.id.undoButton); undoButton = findViewById(R.id.undoButton);
undoButton.setOnClickListener(new OnClickListener() { undoButton.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@@ -1183,7 +1179,7 @@ public class DroidFish extends Activity
return true; return true;
} }
}); });
redoButton = (ImageButton)findViewById(R.id.redoButton); redoButton = findViewById(R.id.redoButton);
redoButton.setOnClickListener(new OnClickListener() { redoButton.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@@ -1231,7 +1227,7 @@ public class DroidFish extends Activity
String dataStr = byteArrToString(data); String dataStr = byteArrToString(data);
editor.putString("gameState", dataStr); editor.putString("gameState", dataStr);
editor.putInt("gameStateVersion", 3); editor.putInt("gameStateVersion", 3);
editor.commit(); editor.apply();
} }
lastVisibleMillis = System.currentTimeMillis(); lastVisibleMillis = System.currentTimeMillis();
updateNotification(); updateNotification();
@@ -1251,8 +1247,7 @@ public class DroidFish extends Activity
private int getIntSetting(String settingName, int defaultValue) { private int getIntSetting(String settingName, int defaultValue) {
String tmp = settings.getString(settingName, String.format(Locale.US, "%d", defaultValue)); String tmp = settings.getString(settingName, String.format(Locale.US, "%d", defaultValue));
int value = Integer.parseInt(tmp); return Integer.parseInt(tmp);
return value;
} }
private void readPrefs() { private void readPrefs() {
@@ -1301,7 +1296,7 @@ public class DroidFish extends Activity
autoScrollMoveList = settings.getBoolean("autoScrollMoveList", true); autoScrollMoveList = settings.getBoolean("autoScrollMoveList", true);
discardVariations = settings.getBoolean("discardVariations", false); discardVariations = settings.getBoolean("discardVariations", false);
Util.setFullScreenMode(this, settings); Util.setFullScreenMode(this, settings);
useWakeLock = settings.getBoolean("wakeLock", false); boolean useWakeLock = settings.getBoolean("wakeLock", false);
setWakeLock(useWakeLock); setWakeLock(useWakeLock);
String lang = settings.getString("language", "default"); String lang = settings.getString("language", "default");
@@ -1346,14 +1341,12 @@ public class DroidFish extends Activity
if (gtbPath.length() == 0) if (gtbPath.length() == 0)
gtbPath = extDir.getAbsolutePath() + sep + gtbDefaultDir; gtbPath = extDir.getAbsolutePath() + sep + gtbDefaultDir;
engineOptions.gtbPath = gtbPath; engineOptions.gtbPath = gtbPath;
String gtbPathNet = settings.getString("gtbPathNet", "").trim(); engineOptions.gtbPathNet = settings.getString("gtbPathNet", "").trim();
engineOptions.gtbPathNet = gtbPathNet;
String rtbPath = settings.getString("rtbPath", "").trim(); String rtbPath = settings.getString("rtbPath", "").trim();
if (rtbPath.length() == 0) if (rtbPath.length() == 0)
rtbPath = extDir.getAbsolutePath() + sep + rtbDefaultDir; rtbPath = extDir.getAbsolutePath() + sep + rtbDefaultDir;
engineOptions.rtbPath = rtbPath; engineOptions.rtbPath = rtbPath;
String rtbPathNet = settings.getString("rtbPathNet", "").trim(); engineOptions.rtbPathNet = settings.getString("rtbPathNet", "").trim();
engineOptions.rtbPathNet = rtbPathNet;
setEngineOptions(false); setEngineOptions(false);
setEgtbHints(cb.getSelectedSquare()); setEgtbHints(cb.getSelectedSquare());
@@ -1387,7 +1380,7 @@ public class DroidFish extends Activity
// as well in rotation // as well in rotation
setFigurineNotation(pgnOptions.view.pieceType == PGNOptions.PT_FIGURINE, fontSize); setFigurineNotation(pgnOptions.view.pieceType == PGNOptions.PT_FIGURINE, fontSize);
showMaterialDiff = settings.getBoolean("materialDiff", false); boolean showMaterialDiff = settings.getBoolean("materialDiff", false);
secondTitleLine.setVisibility(showMaterialDiff ? View.VISIBLE : View.GONE); secondTitleLine.setVisibility(showMaterialDiff ? View.VISIBLE : View.GONE);
} }
@@ -1397,7 +1390,7 @@ public class DroidFish extends Activity
private void setLanguage(String lang) { private void setLanguage(String lang) {
Locale newLocale; Locale newLocale;
if (lang.equals("default")) { if ("default".equals(lang)) {
newLocale = Resources.getSystem().getConfiguration().locale; newLocale = Resources.getSystem().getConfiguration().locale;
} else if (lang.contains("_")) { } else if (lang.contains("_")) {
String[] parts = lang.split("_"); String[] parts = lang.split("_");
@@ -1445,8 +1438,8 @@ public class DroidFish extends Activity
private void updateButtons() { private void updateButtons() {
boolean largeButtons = settings.getBoolean("largeButtons", false); boolean largeButtons = settings.getBoolean("largeButtons", false);
Resources r = getResources(); Resources r = getResources();
int bWidth = (int)Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, r.getDisplayMetrics())); int bWidth = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, r.getDisplayMetrics()));
int bHeight = (int)Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, r.getDisplayMetrics())); int bHeight = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, r.getDisplayMetrics()));
if (largeButtons) { if (largeButtons) {
if (custom1ButtonActions.isEnabled() && if (custom1ButtonActions.isEnabled() &&
custom2ButtonActions.isEnabled() && custom2ButtonActions.isEnabled() &&
@@ -1492,7 +1485,7 @@ public class DroidFish extends Activity
} }
@SuppressLint("Wakelock") @SuppressLint("Wakelock")
private synchronized final void setWakeLock(boolean enableLock) { private synchronized void setWakeLock(boolean enableLock) {
if (enableLock) if (enableLock)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else else
@@ -1524,7 +1517,7 @@ public class DroidFish extends Activity
int idx = engine.lastIndexOf('/'); int idx = engine.lastIndexOf('/');
eName = engine.substring(idx + 1); eName = engine.substring(idx + 1);
} else { } else {
eName = getString(engine.equals("cuckoochess") ? eName = getString("cuckoochess".equals(engine) ?
R.string.cuckoochess_engine : R.string.cuckoochess_engine :
R.string.stockfish_engine); R.string.stockfish_engine);
boolean analysis = (ctrl != null) && ctrl.analysisMode(); boolean analysis = (ctrl != null) && ctrl.analysisMode();
@@ -1652,9 +1645,9 @@ public class DroidFish extends Activity
/** Initialize the drawer part of the user interface. */ /** Initialize the drawer part of the user interface. */
private void initDrawers() { private void initDrawers() {
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); drawerLayout = findViewById(R.id.drawer_layout);
leftDrawer = (ListView)findViewById(R.id.left_drawer); leftDrawer = findViewById(R.id.left_drawer);
rightDrawer = (ListView)findViewById(R.id.right_drawer); rightDrawer = findViewById(R.id.right_drawer);
final DrawerItem[] leftItems = new DrawerItem[] { final DrawerItem[] leftItems = new DrawerItem[] {
new DrawerItem(ITEM_EDIT_BOARD, R.string.option_edit_board), new DrawerItem(ITEM_EDIT_BOARD, R.string.option_edit_board),
@@ -1816,7 +1809,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putString("currentScidFile", pathName); editor.putString("currentScidFile", pathName);
editor.putInt("currFT", FT_SCID); editor.putInt("currFT", FT_SCID);
editor.commit(); editor.apply();
Intent i = new Intent(DroidFish.this, LoadScid.class); Intent i = new Intent(DroidFish.this, LoadScid.class);
i.setAction("org.petero.droidfish.loadScid"); i.setAction("org.petero.droidfish.loadScid");
i.putExtra("org.petero.droidfish.pathname", pathName); i.putExtra("org.petero.droidfish.pathname", pathName);
@@ -1880,7 +1873,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
String gameModeStr = String.format(Locale.US, "%d", gameModeType); String gameModeStr = String.format(Locale.US, "%d", gameModeType);
editor.putString("gameMode", gameModeStr); editor.putString("gameMode", gameModeStr);
editor.commit(); editor.apply();
gameMode = new GameMode(gameModeType); gameMode = new GameMode(gameModeType);
maybeAutoModeOff(gameMode); maybeAutoModeOff(gameMode);
ctrl.setGameMode(gameMode); ctrl.setGameMode(gameMode);
@@ -1927,7 +1920,7 @@ public class DroidFish extends Activity
private void setBooleanPref(String name, boolean value) { private void setBooleanPref(String name, boolean value) {
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putBoolean(name, value); editor.putBoolean(name, value);
editor.commit(); editor.apply();
} }
/** Toggle a boolean preference setting. Return new value. */ /** Toggle a boolean preference setting. Return new value. */
@@ -2295,7 +2288,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
String gameModeStr = String.format(Locale.US, "%d", gameModeType); String gameModeStr = String.format(Locale.US, "%d", gameModeType);
editor.putString("gameMode", gameModeStr); editor.putString("gameMode", gameModeStr);
editor.commit(); editor.apply();
gameMode = new GameMode(gameModeType); gameMode = new GameMode(gameModeType);
} }
// savePGNToFile(".autosave.pgn", true); // savePGNToFile(".autosave.pgn", true);
@@ -2309,7 +2302,7 @@ public class DroidFish extends Activity
} }
private Dialog promoteDialog() { private Dialog promoteDialog() {
final CharSequence[] items = { final String[] items = {
getString(R.string.queen), getString(R.string.rook), getString(R.string.queen), getString(R.string.rook),
getString(R.string.bishop), getString(R.string.knight) getString(R.string.bishop), getString(R.string.knight)
}; };
@@ -2320,8 +2313,7 @@ public class DroidFish extends Activity
ctrl.reportPromotePiece(item); ctrl.reportPromotePiece(item);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog clipBoardDialog() { private Dialog clipBoardDialog() {
@@ -2330,14 +2322,14 @@ public class DroidFish extends Activity
final int PASTE = 2; final int PASTE = 2;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.copy_game)); actions.add(COPY_GAME); lst.add(getString(R.string.copy_game)); actions.add(COPY_GAME);
lst.add(getString(R.string.copy_position)); actions.add(COPY_POSITION); lst.add(getString(R.string.copy_position)); actions.add(COPY_POSITION);
lst.add(getString(R.string.paste)); actions.add(PASTE); lst.add(getString(R.string.paste)); actions.add(PASTE);
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.tools_menu); builder.setTitle(R.string.tools_menu);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case COPY_GAME: { case COPY_GAME: {
@@ -2375,8 +2367,7 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog boardMenuDialog() { private Dialog boardMenuDialog() {
@@ -2389,7 +2380,7 @@ public class DroidFish extends Activity
final int REPEAT_LAST_MOVE = 6; final int REPEAT_LAST_MOVE = 6;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.clipboard)); actions.add(CLIPBOARD); lst.add(getString(R.string.clipboard)); actions.add(CLIPBOARD);
if (storageAvailable()) { if (storageAvailable()) {
@@ -2406,7 +2397,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.tools_menu); builder.setTitle(R.string.tools_menu);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case CLIPBOARD: case CLIPBOARD:
@@ -2514,7 +2505,7 @@ public class DroidFish extends Activity
final int SAVE_GAME = 4; final int SAVE_GAME = 4;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
if (currFileType() != FT_NONE) { if (currFileType() != FT_NONE) {
lst.add(getString(R.string.load_last_file)); actions.add(LOAD_LAST_FILE); lst.add(getString(R.string.load_last_file)); actions.add(LOAD_LAST_FILE);
@@ -2527,7 +2518,7 @@ public class DroidFish extends Activity
lst.add(getString(R.string.save_game)); actions.add(SAVE_GAME); lst.add(getString(R.string.save_game)); actions.add(SAVE_GAME);
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.load_save_menu); builder.setTitle(R.string.load_save_menu);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case LOAD_LAST_FILE: case LOAD_LAST_FILE:
@@ -2551,12 +2542,11 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
/** Open dialog to select a game/position from the last used file. */ /** Open dialog to select a game/position from the last used file. */
final private void loadLastFile() { private void loadLastFile() {
String path = currPathName(); String path = currPathName();
if (path.length() == 0) if (path.length() == 0)
return; return;
@@ -2593,8 +2583,7 @@ public class DroidFish extends Activity
} catch (NameNotFoundException e) { } catch (NameNotFoundException e) {
} }
builder.setTitle(title); builder.setTitle(title);
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog selectBookDialog() { private Dialog selectBookDialog() {
@@ -2605,20 +2594,20 @@ public class DroidFish extends Activity
if (dotIdx < 0) if (dotIdx < 0)
return false; return false;
String ext = filename.substring(dotIdx+1); String ext = filename.substring(dotIdx+1);
return (ext.equals("ctg") || ext.equals("bin")); return ("ctg".equals(ext) || "bin".equals(ext));
} }
}); });
final int numFiles = fileNames.length; final int numFiles = fileNames.length;
final CharSequence[] items = new CharSequence[numFiles + 3]; final String[] items = new String[numFiles + 3];
for (int i = 0; i < numFiles; i++) for (int i = 0; i < numFiles; i++)
items[i] = fileNames[i]; items[i] = fileNames[i];
items[numFiles] = getString(R.string.internal_book); items[numFiles] = getString(R.string.internal_book);
items[numFiles + 1] = getString(R.string.eco_book); items[numFiles + 1] = getString(R.string.eco_book);
items[numFiles + 2] = getString(R.string.no_book); items[numFiles + 2] = getString(R.string.no_book);
int defaultItem = numFiles; int defaultItem = numFiles;
if (bookOptions.filename.equals("eco:")) if ("eco:".equals(bookOptions.filename))
defaultItem = numFiles + 1; defaultItem = numFiles + 1;
else if (bookOptions.filename.equals("nobook:")) else if ("nobook:".equals(bookOptions.filename))
defaultItem = numFiles + 2; defaultItem = numFiles + 2;
for (int i = 0; i < numFiles; i++) { for (int i = 0; i < numFiles; i++) {
if (bookOptions.filename.equals(items[i])) { if (bookOptions.filename.equals(items[i])) {
@@ -2641,14 +2630,13 @@ public class DroidFish extends Activity
else else
bookFile = items[item].toString(); bookFile = items[item].toString();
editor.putString("bookFile", bookFile); editor.putString("bookFile", bookFile);
editor.commit(); editor.apply();
bookOptions.filename = bookFile; bookOptions.filename = bookFile;
setBookOptions(); setBookOptions();
dialog.dismiss(); dialog.dismiss();
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private static boolean reservedEngineName(String name) { private static boolean reservedEngineName(String name) {
@@ -2720,7 +2708,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
String engine = ids.get(item); String engine = ids.get(item);
editor.putString("engine", engine); editor.putString("engine", engine);
editor.commit(); editor.apply();
dialog.dismiss(); dialog.dismiss();
int strength = settings.getInt("strength", 1000); int strength = settings.getInt("strength", 1000);
setEngineOptions(false); setEngineOptions(false);
@@ -2734,11 +2722,10 @@ public class DroidFish extends Activity
reShowDialog(MANAGE_ENGINES_DIALOG); reShowDialog(MANAGE_ENGINES_DIALOG);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private static interface Loader { private interface Loader {
void load(String pathName); void load(String pathName);
} }
@@ -2770,8 +2757,7 @@ public class DroidFish extends Activity
if (numFiles == 0) { if (numFiles == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name).setMessage(noFilesMsg); builder.setTitle(R.string.app_name).setMessage(noFilesMsg);
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
int defaultItem = 0; int defaultItem = 0;
String currentFile = settings.getString(settingsName, ""); String currentFile = settings.getString(settingsName, "");
@@ -2793,8 +2779,7 @@ public class DroidFish extends Activity
loader.load(pathName); loader.load(pathName);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog selectPgnFileSaveDialog() { private Dialog selectPgnFileSaveDialog() {
@@ -2810,7 +2795,7 @@ public class DroidFish extends Activity
break; break;
} }
} }
final CharSequence[] items = new CharSequence[numFiles + 1]; final String[] items = new String[numFiles + 1];
for (int i = 0; i < numFiles; i++) for (int i = 0; i < numFiles; i++)
items[i] = fileNames[i]; items[i] = fileNames[i];
items[numFiles] = getString(R.string.new_file); items[numFiles] = getString(R.string.new_file);
@@ -2824,7 +2809,7 @@ public class DroidFish extends Activity
showDialog(SELECT_PGN_SAVE_NEWFILE_DIALOG); showDialog(SELECT_PGN_SAVE_NEWFILE_DIALOG);
} else { } else {
dialog.dismiss(); dialog.dismiss();
pgnFile = fileNames[item].toString(); 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, false);
@@ -2840,7 +2825,7 @@ public class DroidFish extends Activity
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(content); builder.setView(content);
builder.setTitle(R.string.select_pgn_file_save); builder.setTitle(R.string.select_pgn_file_save);
final EditText fileNameView = (EditText)content.findViewById(R.id.create_pgn_filename); final EditText fileNameView = content.findViewById(R.id.create_pgn_filename);
fileNameView.setText(""); fileNameView.setText("");
final Runnable savePGN = new Runnable() { final Runnable savePGN = new Runnable() {
public void run() { public void run() {
@@ -2893,7 +2878,7 @@ public class DroidFish extends Activity
} }
private Dialog gameModeDialog() { private Dialog gameModeDialog() {
final CharSequence[] items = { final String[] items = {
getString(R.string.analysis_mode), getString(R.string.analysis_mode),
getString(R.string.edit_replay_game), getString(R.string.edit_replay_game),
getString(R.string.play_white), getString(R.string.play_white),
@@ -2923,8 +2908,7 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog moveListMenuDialog() { private Dialog moveListMenuDialog() {
@@ -2937,7 +2921,7 @@ public class DroidFish extends Activity
final int ADD_NULL_MOVE = 6; final int ADD_NULL_MOVE = 6;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.edit_headers)); actions.add(EDIT_HEADERS); lst.add(getString(R.string.edit_headers)); actions.add(EDIT_HEADERS);
if (ctrl.humansTurn()) { if (ctrl.humansTurn()) {
@@ -2961,7 +2945,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.edit_game); builder.setTitle(R.string.edit_game);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case EDIT_HEADERS: case EDIT_HEADERS:
@@ -3006,12 +2990,12 @@ public class DroidFish extends Activity
final TextView event, site, date, round, white, black; final TextView event, site, date, round, white, black;
event = (TextView)content.findViewById(R.id.ed_header_event); event = content.findViewById(R.id.ed_header_event);
site = (TextView)content.findViewById(R.id.ed_header_site); site = content.findViewById(R.id.ed_header_site);
date = (TextView)content.findViewById(R.id.ed_header_date); date = content.findViewById(R.id.ed_header_date);
round = (TextView)content.findViewById(R.id.ed_header_round); round = content.findViewById(R.id.ed_header_round);
white = (TextView)content.findViewById(R.id.ed_header_white); white = content.findViewById(R.id.ed_header_white);
black = (TextView)content.findViewById(R.id.ed_header_black); black = content.findViewById(R.id.ed_header_black);
event.setText(headers.get("Event")); event.setText(headers.get("Event"));
site .setText(headers.get("Site")); site .setText(headers.get("Site"));
@@ -3020,10 +3004,10 @@ public class DroidFish extends Activity
white.setText(headers.get("White")); white.setText(headers.get("White"));
black.setText(headers.get("Black")); black.setText(headers.get("Black"));
final Spinner gameResult = (Spinner)content.findViewById(R.id.ed_game_result); final Spinner gameResult = content.findViewById(R.id.ed_game_result);
final String[] items = new String[]{"1-0", "1/2-1/2", "0-1", "*"}; final String[] items = new String[]{"1-0", "1/2-1/2", "0-1", "*"};
ArrayAdapter<CharSequence> adapt = ArrayAdapter<String> adapt =
new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, items); new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gameResult.setAdapter(adapt); gameResult.setAdapter(adapt);
gameResult.setSelection(Arrays.asList(items).indexOf(headers.get("Result"))); gameResult.setSelection(Arrays.asList(items).indexOf(headers.get("Result")));
@@ -3059,10 +3043,10 @@ public class DroidFish extends Activity
DroidChessController.CommentInfo commInfo = ctrl.getComments(); DroidChessController.CommentInfo commInfo = ctrl.getComments();
final TextView preComment, moveView, nag, postComment; final TextView preComment, moveView, nag, postComment;
preComment = (TextView)content.findViewById(R.id.ed_comments_pre); preComment = content.findViewById(R.id.ed_comments_pre);
moveView = (TextView)content.findViewById(R.id.ed_comments_move); moveView = content.findViewById(R.id.ed_comments_move);
nag = (TextView)content.findViewById(R.id.ed_comments_nag); nag = content.findViewById(R.id.ed_comments_nag);
postComment = (TextView)content.findViewById(R.id.ed_comments_post); postComment = content.findViewById(R.id.ed_comments_post);
preComment.setText(commInfo.preComment); preComment.setText(commInfo.preComment);
postComment.setText(commInfo.postComment); postComment.setText(commInfo.postComment);
@@ -3097,7 +3081,7 @@ public class DroidFish extends Activity
final int TRUNCATE_VARS = 3; final int TRUNCATE_VARS = 3;
final int HIDE_STATISTICS = 4; final int HIDE_STATISTICS = 4;
final int SHOW_STATISTICS = 5; final int SHOW_STATISTICS = 5;
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.add_analysis)); actions.add(ADD_ANALYSIS); lst.add(getString(R.string.add_analysis)); actions.add(ADD_ANALYSIS);
int numPV = this.numPV; int numPV = this.numPV;
@@ -3124,7 +3108,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.analysis); builder.setTitle(R.string.analysis);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case ADD_ANALYSIS: { case ADD_ANALYSIS: {
@@ -3158,7 +3142,7 @@ public class DroidFish extends Activity
fullPVLines = actions.get(item) == SHOW_WHOLE_VARS; fullPVLines = actions.get(item) == SHOW_WHOLE_VARS;
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putBoolean("fullPVLines", fullPVLines); editor.putBoolean("fullPVLines", fullPVLines);
editor.commit(); editor.apply();
updateThinkingInfo(); updateThinkingInfo();
break; break;
} }
@@ -3167,15 +3151,14 @@ public class DroidFish extends Activity
mShowStats = actions.get(item) == SHOW_STATISTICS; mShowStats = actions.get(item) == SHOW_STATISTICS;
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putBoolean("showStats", mShowStats); editor.putBoolean("showStats", mShowStats);
editor.commit(); editor.apply();
updateThinkingInfo(); updateThinkingInfo();
break; break;
} }
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
/** Handle user interface to set MultiPV value. */ /** Handle user interface to set MultiPV value. */
@@ -3184,7 +3167,7 @@ public class DroidFish extends Activity
numPV = nPV; numPV = nPV;
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putInt("numPV", numPV); editor.putInt("numPV", numPV);
editor.commit(); editor.apply();
ctrl.setMultiPVMode(numPV); ctrl.setMultiPVMode(numPV);
} }
@@ -3225,8 +3208,8 @@ public class DroidFish extends Activity
View content = View.inflate(DroidFish.this, R.layout.num_variations, null); View content = View.inflate(DroidFish.this, R.layout.num_variations, null);
builder.setView(content); builder.setView(content);
final SeekBar seekBar = (SeekBar)content.findViewById(R.id.numvar_seekbar); final SeekBar seekBar = content.findViewById(R.id.numvar_seekbar);
final EditText editTxt = (EditText)content.findViewById(R.id.numvar_edittext); final EditText editTxt = content.findViewById(R.id.numvar_edittext);
seekBar.setMax(numPVToProgress(maxPV, maxPV)); seekBar.setMax(numPVToProgress(maxPV, maxPV));
seekBar.setProgress(numPVToProgress(numPV, maxPV)); seekBar.setProgress(numPVToProgress(numPV, maxPV));
@@ -3288,7 +3271,7 @@ public class DroidFish extends Activity
final int AUTO_BACKWARD = 4; final int AUTO_BACKWARD = 4;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.goto_start_game)); actions.add(GOTO_START_GAME); lst.add(getString(R.string.goto_start_game)); actions.add(GOTO_START_GAME);
lst.add(getString(R.string.goto_start_variation)); actions.add(GOTO_START_VAR); lst.add(getString(R.string.goto_start_variation)); actions.add(GOTO_START_VAR);
@@ -3304,7 +3287,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.go_back); builder.setTitle(R.string.go_back);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case GOTO_START_GAME: ctrl.gotoMove(0); break; case GOTO_START_GAME: ctrl.gotoMove(0); break;
@@ -3319,8 +3302,7 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog goForwardMenuDialog() { private Dialog goForwardMenuDialog() {
@@ -3330,7 +3312,7 @@ public class DroidFish extends Activity
final int AUTO_FORWARD = 3; final int AUTO_FORWARD = 3;
setAutoMode(AutoMode.OFF); setAutoMode(AutoMode.OFF);
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.goto_end_variation)); actions.add(GOTO_END_VAR); lst.add(getString(R.string.goto_end_variation)); actions.add(GOTO_END_VAR);
if (ctrl.currVariation() < ctrl.numVariations() - 1) { if (ctrl.currVariation() < ctrl.numVariations() - 1) {
@@ -3345,7 +3327,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.go_forward); builder.setTitle(R.string.go_forward);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case GOTO_END_VAR: ctrl.gotoMove(Integer.MAX_VALUE); break; case GOTO_END_VAR: ctrl.gotoMove(Integer.MAX_VALUE); break;
@@ -3359,12 +3341,11 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
private Dialog makeButtonDialog(ButtonActions buttonActions) { private Dialog makeButtonDialog(ButtonActions buttonActions) {
List<CharSequence> names = new ArrayList<>(); List<String> names = new ArrayList<>();
final List<UIAction> actions = new ArrayList<>(); final List<UIAction> actions = new ArrayList<>();
HashSet<String> used = new HashSet<>(); HashSet<String> used = new HashSet<>();
@@ -3377,7 +3358,7 @@ public class DroidFish extends Activity
} }
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(buttonActions.getMenuTitle()); builder.setTitle(buttonActions.getMenuTitle());
builder.setItems(names.toArray(new CharSequence[names.size()]), new DialogInterface.OnClickListener() { builder.setItems(names.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
UIAction a = actions.get(item); UIAction a = actions.get(item);
a.run(); a.run();
@@ -3390,7 +3371,7 @@ public class DroidFish extends Activity
final int SELECT_ENGINE = 0; final int SELECT_ENGINE = 0;
final int SET_ENGINE_OPTIONS = 1; final int SET_ENGINE_OPTIONS = 1;
final int CONFIG_NET_ENGINE = 2; final int CONFIG_NET_ENGINE = 2;
List<CharSequence> lst = new ArrayList<>(); List<String> lst = new ArrayList<>();
final List<Integer> actions = new ArrayList<>(); final List<Integer> actions = new ArrayList<>();
lst.add(getString(R.string.select_engine)); actions.add(SELECT_ENGINE); lst.add(getString(R.string.select_engine)); actions.add(SELECT_ENGINE);
if (canSetEngineOptions()) { if (canSetEngineOptions()) {
@@ -3400,7 +3381,7 @@ public class DroidFish extends Activity
lst.add(getString(R.string.configure_network_engine)); actions.add(CONFIG_NET_ENGINE); lst.add(getString(R.string.configure_network_engine)); actions.add(CONFIG_NET_ENGINE);
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.option_manage_engines); builder.setTitle(R.string.option_manage_engines);
builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { builder.setItems(lst.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { public void onClick(DialogInterface dialog, int item) {
switch (actions.get(item)) { switch (actions.get(item)) {
case SELECT_ENGINE: case SELECT_ENGINE:
@@ -3415,8 +3396,7 @@ public class DroidFish extends Activity
} }
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
/** Return true if engine UCI options can be set now. */ /** Return true if engine UCI options can be set now. */
@@ -3452,16 +3432,15 @@ public class DroidFish extends Activity
return EngineUtil.isNetEngine(filename); return EngineUtil.isNetEngine(filename);
} }
}); });
final int numFiles = fileNames.length; final int numItems = fileNames.length + 1;
final int numItems = numFiles + 1;
final String[] items = new String[numItems]; final String[] items = new String[numItems];
final String[] ids = new String[numItems]; final String[] ids = new String[numItems];
int idx = 0; int idx = 0;
String sep = File.separator; String sep = File.separator;
String base = Environment.getExternalStorageDirectory() + sep + engineDir + sep; String base = Environment.getExternalStorageDirectory() + sep + engineDir + sep;
for (int i = 0; i < numFiles; i++) { for (String fileName : fileNames) {
ids[idx] = base + fileNames[i]; ids[idx] = base + fileName;
items[idx] = fileNames[i]; items[idx] = fileName;
idx++; idx++;
} }
ids[idx] = ""; items[idx] = getString(R.string.new_engine); idx++; ids[idx] = ""; items[idx] = getString(R.string.new_engine); idx++;
@@ -3493,8 +3472,7 @@ public class DroidFish extends Activity
reShowDialog(MANAGE_ENGINES_DIALOG); reShowDialog(MANAGE_ENGINES_DIALOG);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
// Filename of network engine to configure // Filename of network engine to configure
@@ -3506,7 +3484,7 @@ public class DroidFish extends Activity
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(content); builder.setView(content);
builder.setTitle(R.string.create_network_engine); builder.setTitle(R.string.create_network_engine);
final EditText engineNameView = (EditText)content.findViewById(R.id.create_network_engine); final EditText engineNameView = content.findViewById(R.id.create_network_engine);
engineNameView.setText(""); engineNameView.setText("");
final Runnable createEngine = new Runnable() { final Runnable createEngine = new Runnable() {
public void run() { public void run() {
@@ -3570,8 +3548,8 @@ public class DroidFish extends Activity
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(content); builder.setView(content);
builder.setTitle(R.string.configure_network_engine); builder.setTitle(R.string.configure_network_engine);
final EditText hostNameView = (EditText)content.findViewById(R.id.network_engine_host); final EditText hostNameView = content.findViewById(R.id.network_engine_host);
final EditText portView = (EditText)content.findViewById(R.id.network_engine_port); final EditText portView = content.findViewById(R.id.network_engine_port);
String hostName = ""; String hostName = "";
String port = "0"; String port = "0";
try { try {
@@ -3658,7 +3636,7 @@ public class DroidFish extends Activity
engine = "stockfish"; engine = "stockfish";
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putString("engine", engine); editor.putString("engine", engine);
editor.commit(); editor.apply();
dialog.dismiss(); dialog.dismiss();
int strength = settings.getInt("strength", 1000); int strength = settings.getInt("strength", 1000);
setEngineOptions(false); setEngineOptions(false);
@@ -3680,8 +3658,7 @@ public class DroidFish extends Activity
reShowDialog(NETWORK_ENGINE_DIALOG); reShowDialog(NETWORK_ENGINE_DIALOG);
} }
}); });
AlertDialog alert = builder.create(); return builder.create();
return alert;
} }
/** Open a load/save file dialog. Uses OI file manager if available. */ /** Open a load/save file dialog. Uses OI file manager if available. */
@@ -3727,7 +3704,7 @@ public class DroidFish extends Activity
} }
} }
public final static boolean hasFenProvider(PackageManager manager) { public static boolean hasFenProvider(PackageManager manager) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT); Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("application/x-chess-fen"); i.setType("application/x-chess-fen");
List<ResolveInfo> resolvers = manager.queryIntentActivities(i, 0); List<ResolveInfo> resolvers = manager.queryIntentActivities(i, 0);
@@ -3773,7 +3750,7 @@ public class DroidFish extends Activity
} }
} }
private static interface FileNameFilter { private interface FileNameFilter {
boolean accept(String filename); boolean accept(String filename);
} }
@@ -3805,7 +3782,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putString("currentPGNFile", pathName); editor.putString("currentPGNFile", pathName);
editor.putInt("currFT", FT_PGN); editor.putInt("currFT", FT_PGN);
editor.commit(); editor.apply();
Intent i = new Intent(DroidFish.this, EditPGNSave.class); Intent i = new Intent(DroidFish.this, EditPGNSave.class);
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);
@@ -3819,7 +3796,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putString("currentPGNFile", pathName); editor.putString("currentPGNFile", pathName);
editor.putInt("currFT", FT_PGN); editor.putInt("currFT", FT_PGN);
editor.commit(); editor.apply();
Intent i = new Intent(DroidFish.this, EditPGNLoad.class); Intent i = new Intent(DroidFish.this, EditPGNLoad.class);
i.setAction("org.petero.droidfish.loadFile"); i.setAction("org.petero.droidfish.loadFile");
i.putExtra("org.petero.droidfish.pathname", pathName); i.putExtra("org.petero.droidfish.pathname", pathName);
@@ -3833,7 +3810,7 @@ public class DroidFish extends Activity
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putString("currentFENFile", pathName); editor.putString("currentFENFile", pathName);
editor.putInt("currFT", FT_FEN); editor.putInt("currFT", FT_FEN);
editor.commit(); editor.apply();
Intent i = new Intent(DroidFish.this, LoadFEN.class); Intent i = new Intent(DroidFish.this, LoadFEN.class);
i.setAction("org.petero.droidfish.loadFen"); i.setAction("org.petero.droidfish.loadFen");
i.putExtra("org.petero.droidfish.pathname", pathName); i.putExtra("org.petero.droidfish.pathname", pathName);
@@ -3943,11 +3920,11 @@ public class DroidFish extends Activity
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;
CharSequence tickerText = getString(R.string.heavy_cpu_usage); String tickerText = getString(R.string.heavy_cpu_usage);
long when = System.currentTimeMillis(); long when = System.currentTimeMillis();
Context context = getApplicationContext(); Context context = getApplicationContext();
CharSequence contentTitle = getString(R.string.background_processing); String contentTitle = getString(R.string.background_processing);
CharSequence contentText = getString(R.string.lot_cpu_power); String contentText = getString(R.string.lot_cpu_power);
Intent notificationIntent = new Intent(this, CPUWarning.class); Intent notificationIntent = new Intent(this, CPUWarning.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View File

@@ -40,7 +40,7 @@ public class FileUtil {
while ((line = inBuf.readLine()) != null) while ((line = inBuf.readLine()) != null)
ret.add(line); ret.add(line);
inBuf.close(); inBuf.close();
return ret.toArray(new String[ret.size()]); return ret.toArray(new String[0]);
} }
/** Read all data from an input stream. Return null if IO error. */ /** Read all data from an input stream. Return null if IO error. */
@@ -81,7 +81,7 @@ public class FileUtil {
} }
/** Return the length of a file, or -1 if length can not be determined. */ /** Return the length of a file, or -1 if length can not be determined. */
public static final long getFileLength(String filename) { public static long getFileLength(String filename) {
try { try {
RandomAccessFile raf = new RandomAccessFile(filename, "r"); RandomAccessFile raf = new RandomAccessFile(filename, "r");
try { try {

View File

@@ -144,27 +144,27 @@ public class EditBoard extends Activity {
View firstTitleLine = findViewById(R.id.first_title_line); View firstTitleLine = findViewById(R.id.first_title_line);
View secondTitleLine = findViewById(R.id.second_title_line); View secondTitleLine = findViewById(R.id.second_title_line);
cb = (ChessBoardEdit)findViewById(R.id.eb_chessboard); cb = findViewById(R.id.eb_chessboard);
cb.setFlipped(boardFlipped); cb.setFlipped(boardFlipped);
status = (TextView)findViewById(R.id.eb_status); status = findViewById(R.id.eb_status);
okButton = (Button)findViewById(R.id.eb_ok); okButton = findViewById(R.id.eb_ok);
cancelButton = (Button)findViewById(R.id.eb_cancel); cancelButton = findViewById(R.id.eb_cancel);
TextView whiteTitleText = (TextView)findViewById(R.id.white_clock); TextView whiteTitleText = findViewById(R.id.white_clock);
whiteTitleText.setVisibility(View.GONE); whiteTitleText.setVisibility(View.GONE);
TextView blackTitleText = (TextView)findViewById(R.id.black_clock); TextView blackTitleText = findViewById(R.id.black_clock);
blackTitleText.setVisibility(View.GONE); blackTitleText.setVisibility(View.GONE);
TextView engineTitleText = (TextView)findViewById(R.id.title_text); TextView engineTitleText = findViewById(R.id.title_text);
engineTitleText.setVisibility(View.GONE); engineTitleText.setVisibility(View.GONE);
whiteFigText = (TextView) findViewById(R.id.white_pieces); whiteFigText = findViewById(R.id.white_pieces);
whiteFigText.setTypeface(figNotation); whiteFigText.setTypeface(figNotation);
whiteFigText.setSelected(true); whiteFigText.setSelected(true);
whiteFigText.setTextColor(whiteTitleText.getTextColors()); whiteFigText.setTextColor(whiteTitleText.getTextColors());
blackFigText = (TextView) findViewById(R.id.black_pieces); blackFigText = findViewById(R.id.black_pieces);
blackFigText.setTypeface(figNotation); blackFigText.setTypeface(figNotation);
blackFigText.setSelected(true); blackFigText.setSelected(true);
blackFigText.setTextColor(blackTitleText.getTextColors()); blackFigText.setTextColor(blackTitleText.getTextColors());
TextView summaryTitleText = (TextView) findViewById(R.id.title_text_summary); TextView summaryTitleText = findViewById(R.id.title_text_summary);
summaryTitleText.setText(R.string.edit_board); summaryTitleText.setText(R.string.edit_board);
TextUtils.TruncateAt where = autoScrollTitle ? TextUtils.TruncateAt.MARQUEE TextUtils.TruncateAt where = autoScrollTitle ? TextUtils.TruncateAt.MARQUEE
@@ -253,8 +253,8 @@ public class EditBoard extends Activity {
/** Initialize the drawer part of the user interface. */ /** Initialize the drawer part of the user interface. */
private void initDrawers() { private void initDrawers() {
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); drawerLayout = findViewById(R.id.drawer_layout);
leftDrawer = (ListView)findViewById(R.id.left_drawer); leftDrawer = findViewById(R.id.left_drawer);
class DrawerItem { class DrawerItem {
int id; int id;
@@ -596,8 +596,8 @@ public class EditBoard extends Activity {
builder.setView(content); builder.setView(content);
builder.setTitle(R.string.edit_move_counters); builder.setTitle(R.string.edit_move_counters);
final EditText halfMoveClock = (EditText)content.findViewById(R.id.ed_cnt_halfmove); final EditText halfMoveClock = content.findViewById(R.id.ed_cnt_halfmove);
final EditText fullMoveCounter = (EditText)content.findViewById(R.id.ed_cnt_fullmove); final EditText fullMoveCounter = content.findViewById(R.id.ed_cnt_fullmove);
halfMoveClock.setText(String.format(Locale.US, "%d", cb.pos.halfMoveClock)); halfMoveClock.setText(String.format(Locale.US, "%d", cb.pos.halfMoveClock));
fullMoveCounter.setText(String.format(Locale.US, "%d", cb.pos.fullMoveCounter)); fullMoveCounter.setText(String.format(Locale.US, "%d", cb.pos.fullMoveCounter));
final Runnable setCounters = new Runnable() { final Runnable setCounters = new Runnable() {

View File

@@ -95,7 +95,7 @@ public class EditOptions extends Activity {
View view = View.inflate(this, R.layout.editoptions, null); View view = View.inflate(this, R.layout.editoptions, null);
if (uciOpts != null) { if (uciOpts != null) {
LinearLayout content = (LinearLayout)view.findViewById(R.id.eo_content); LinearLayout content = view.findViewById(R.id.eo_content);
for (String name : uciOpts.getOptionNames()) { for (String name : uciOpts.getOptionNames()) {
UCIOptions.OptionBase o = uciOpts.getOption(name); UCIOptions.OptionBase o = uciOpts.getOption(name);
if (!o.visible) if (!o.visible)
@@ -103,7 +103,7 @@ public class EditOptions extends Activity {
switch (o.type) { switch (o.type) {
case CHECK: { case CHECK: {
View v = View.inflate(this, R.layout.uci_option_check, null); View v = View.inflate(this, R.layout.uci_option_check, null);
CheckBox checkBox = (CheckBox)v.findViewById(R.id.eo_value); CheckBox checkBox = v.findViewById(R.id.eo_value);
checkBox.setText(o.name); checkBox.setText(o.name);
final UCIOptions.CheckOption co = (UCIOptions.CheckOption)o; final UCIOptions.CheckOption co = (UCIOptions.CheckOption)o;
checkBox.setChecked(co.value); checkBox.setChecked(co.value);
@@ -118,8 +118,8 @@ public class EditOptions extends Activity {
} }
case SPIN: { case SPIN: {
View v = View.inflate(this, R.layout.uci_option_spin, null); View v = View.inflate(this, R.layout.uci_option_spin, null);
TextView label = (TextView)v.findViewById(R.id.eo_label); TextView label = v.findViewById(R.id.eo_label);
EditText value = (EditText)v.findViewById(R.id.eo_value); EditText value = v.findViewById(R.id.eo_value);
final UCIOptions.SpinOption so = (UCIOptions.SpinOption)o; final UCIOptions.SpinOption so = (UCIOptions.SpinOption)o;
String labelText = String.format(Locale.US, "%s (%d\u2013%d)", so.name, so.minValue, so.maxValue); String labelText = String.format(Locale.US, "%s (%d\u2013%d)", so.name, so.minValue, so.maxValue);
label.setText(labelText); label.setText(labelText);
@@ -148,8 +148,8 @@ public class EditOptions extends Activity {
} }
case COMBO: { case COMBO: {
View v = View.inflate(this, R.layout.uci_option_combo, null); View v = View.inflate(this, R.layout.uci_option_combo, null);
TextView label = (TextView)v.findViewById(R.id.eo_label); TextView label = v.findViewById(R.id.eo_label);
Spinner value = (Spinner)v.findViewById(R.id.eo_value); Spinner value = v.findViewById(R.id.eo_value);
label.setText(o.name); label.setText(o.name);
final UCIOptions.ComboOption co = (UCIOptions.ComboOption)o; final UCIOptions.ComboOption co = (UCIOptions.ComboOption)o;
ArrayAdapter<CharSequence> adapter = ArrayAdapter<CharSequence> adapter =
@@ -171,7 +171,7 @@ public class EditOptions extends Activity {
} }
case BUTTON: { case BUTTON: {
View v = View.inflate(this, R.layout.uci_option_button, null); View v = View.inflate(this, R.layout.uci_option_button, null);
ToggleButton button = (ToggleButton)v.findViewById(R.id.eo_label); ToggleButton button = v.findViewById(R.id.eo_label);
final UCIOptions.ButtonOption bo = (UCIOptions.ButtonOption)o; final UCIOptions.ButtonOption bo = (UCIOptions.ButtonOption)o;
bo.trigger = false; bo.trigger = false;
button.setText(o.name); button.setText(o.name);
@@ -188,8 +188,8 @@ public class EditOptions extends Activity {
} }
case STRING: { case STRING: {
View v = View.inflate(this, R.layout.uci_option_string, null); View v = View.inflate(this, R.layout.uci_option_string, null);
TextView label = (TextView)v.findViewById(R.id.eo_label); TextView label = v.findViewById(R.id.eo_label);
EditText value = (EditText)v.findViewById(R.id.eo_value); EditText value = v.findViewById(R.id.eo_value);
label.setText(o.name + " "); label.setText(o.name + " ");
final UCIOptions.StringOption so = (UCIOptions.StringOption)o; final UCIOptions.StringOption so = (UCIOptions.StringOption)o;
value.setText(so.value); value.setText(so.value);
@@ -210,9 +210,9 @@ public class EditOptions extends Activity {
setContentView(view); setContentView(view);
Util.overrideViewAttribs(findViewById(android.R.id.content)); Util.overrideViewAttribs(findViewById(android.R.id.content));
Button okButton = (Button)findViewById(R.id.eo_ok); Button okButton = findViewById(R.id.eo_ok);
Button cancelButton = (Button)findViewById(R.id.eo_cancel); Button cancelButton = findViewById(R.id.eo_cancel);
Button resetButton = (Button)findViewById(R.id.eo_reset); Button resetButton = findViewById(R.id.eo_reset);
okButton.setOnClickListener(new OnClickListener() { okButton.setOnClickListener(new OnClickListener() {
@Override @Override

View File

@@ -213,7 +213,7 @@ public class EditPGN extends ListActivity {
editor.putString("lastSearchString", lastSearchString); editor.putString("lastSearchString", lastSearchString);
editor.putString("lastFileName", lastFileName); editor.putString("lastFileName", lastFileName);
editor.putLong("lastModTime", lastModTime); editor.putLong("lastModTime", lastModTime);
editor.commit(); editor.apply();
super.onPause(); super.onPause();
} }
@@ -290,7 +290,7 @@ public class EditPGN extends ListActivity {
} }
}); });
filterText = (EditText)findViewById(R.id.select_game_filter); filterText = findViewById(R.id.select_game_filter);
filterText.addTextChangedListener(new TextWatcher() { filterText.addTextChangedListener(new TextWatcher() {
@Override @Override
public void afterTextChanged(Editable s) { } public void afterTextChanged(Editable s) { }
@@ -303,7 +303,7 @@ public class EditPGN extends ListActivity {
} }
}); });
filterText.setText(lastSearchString); filterText.setText(lastSearchString);
hintText = (TextView)findViewById(R.id.select_game_hint); hintText = findViewById(R.id.select_game_hint);
if (loadGame) { if (loadGame) {
hintText.setVisibility(View.GONE); hintText.setVisibility(View.GONE);
} else { } else {

View File

@@ -180,7 +180,7 @@ public class LoadFEN extends ListActivity {
editor.putInt("defaultItem", defaultItem); editor.putInt("defaultItem", defaultItem);
editor.putString("lastFenFileName", lastFileName); editor.putString("lastFenFileName", lastFileName);
editor.putLong("lastFenModTime", lastModTime); editor.putLong("lastFenModTime", lastModTime);
editor.commit(); editor.apply();
super.onPause(); super.onPause();
} }
@@ -202,9 +202,9 @@ public class LoadFEN extends ListActivity {
removeProgressDialog(); removeProgressDialog();
setContentView(R.layout.load_fen); setContentView(R.layout.load_fen);
cb = (ChessBoardPlay)findViewById(R.id.loadfen_chessboard); cb = findViewById(R.id.loadfen_chessboard);
okButton = (Button)findViewById(R.id.loadfen_ok); okButton = findViewById(R.id.loadfen_ok);
cancelButton = (Button)findViewById(R.id.loadfen_cancel); cancelButton = findViewById(R.id.loadfen_cancel);
okButton.setEnabled(false); okButton.setEnabled(false);
okButton.setOnClickListener(new OnClickListener() { okButton.setOnClickListener(new OnClickListener() {

View File

@@ -212,7 +212,7 @@ public class LoadScid extends ListActivity {
editor.putInt("defaultScidItem", defaultItem); editor.putInt("defaultScidItem", defaultItem);
editor.putString("lastScidFileName", lastFileName); editor.putString("lastScidFileName", lastFileName);
editor.putLong("lastScidModTime", lastModTime); editor.putLong("lastScidModTime", lastModTime);
editor.commit(); editor.apply();
super.onPause(); super.onPause();
} }

View File

@@ -52,7 +52,7 @@ public class Preferences extends PreferenceActivity {
if (v == null) if (v == null)
return null; return null;
final ListView lv = (ListView) v.findViewById(android.R.id.list); final ListView lv = v.findViewById(android.R.id.list);
if (lv != null) { if (lv != null) {
lv.setOnScrollListener(new OnScrollListener() { lv.setOnScrollListener(new OnScrollListener() {
@Override @Override
@@ -94,6 +94,6 @@ public class Preferences extends PreferenceActivity {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = settings.edit(); Editor editor = settings.edit();
editor.putInt("prefsViewInitialItem", currentItem); editor.putInt("prefsViewInitialItem", currentItem);
editor.commit(); editor.apply();
} }
} }

View File

@@ -141,7 +141,7 @@ public class SeekBarPreference extends Preference
title = getContext().getString(R.string.edit_randomization); title = getContext().getString(R.string.edit_randomization);
} }
builder.setTitle(title); builder.setTitle(title);
final EditText valueView = (EditText)content.findViewById(R.id.selpercentage_number); final EditText valueView = content.findViewById(R.id.selpercentage_number);
valueView.setText(currValBox.getText().toString().replaceAll("%", "").replaceAll(",", ".")); valueView.setText(currValBox.getText().toString().replaceAll("%", "").replaceAll(",", "."));
final Runnable selectValue = new Runnable() { final Runnable selectValue = new Runnable() {
public void run() { public void run() {
@@ -195,7 +195,7 @@ public class SeekBarPreference extends Preference
currValBox.setText(valToString()); currValBox.setText(valToString());
SharedPreferences.Editor editor = getEditor(); SharedPreferences.Editor editor = getEditor();
editor.putInt(getKey(), progress); editor.putInt(getKey(), progress);
editor.commit(); editor.apply();
if ((progress == 0) && showStrengthHint) { if ((progress == 0) && showStrengthHint) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
String engine = settings.getString("engine", "stockfish"); String engine = settings.getString("engine", "stockfish");

View File

@@ -250,7 +250,7 @@ class CtgBook implements IOpeningBook {
this.f = f; this.f = f;
} }
final static ArrayList<Integer> getHashIndices(byte[] encodedPos, CtbFile ctb) throws IOException { static ArrayList<Integer> getHashIndices(byte[] encodedPos, CtbFile ctb) throws IOException {
ArrayList<Integer> ret = new ArrayList<>(); ArrayList<Integer> ret = new ArrayList<>();
int hash = getHashValue(encodedPos); int hash = getHashValue(encodedPos);
for (int n = 0; n < 0x7fffffff; n = 2*n + 1) { for (int n = 0; n < 0x7fffffff; n = 2*n + 1) {

View File

@@ -284,7 +284,7 @@ public class EcoDb {
start = i + 1; start = i + 1;
} }
} }
strPool = names.toArray(new String[names.size()]); strPool = names.toArray(new String[0]);
} catch (IOException ex) { } catch (IOException ex) {
throw new RuntimeException("Can't read ECO database"); throw new RuntimeException("Can't read ECO database");
} }

View File

@@ -97,11 +97,11 @@ public class EngineUtil {
} }
/** Executes chmod 744 exePath. */ /** Executes chmod 744 exePath. */
final static native boolean chmod(String exePath); static native boolean chmod(String exePath);
/** Change the priority of a process. */ /** Change the priority of a process. */
final static native void reNice(int pid, int prio); static native void reNice(int pid, int prio);
/** For synchronizing non thread safe native calls. */ /** For synchronizing non thread safe native calls. */
public static Object nativeLock = new Object(); public static final Object nativeLock = new Object();
} }

View File

@@ -236,7 +236,7 @@ public abstract class UCIEngineBase implements UCIEngine {
} }
} else if (type.equals("combo")) { } else if (type.equals("combo")) {
if (defVal != null && var.size() > 0) { if (defVal != null && var.size() > 0) {
String[] allowed = var.toArray(new String[var.size()]); String[] allowed = var.toArray(new String[0]);
for (String s : allowed) for (String s : allowed)
if (s.equals(defVal)) { if (s.equals(defVal)) {
option = new UCIOptions.ComboOption(name, allowed, defVal); option = new UCIOptions.ComboOption(name, allowed, defVal);

View File

@@ -29,7 +29,7 @@ public class UCIOptions implements Serializable, Cloneable {
private ArrayList<String> names; private ArrayList<String> names;
private Map<String, OptionBase> options; private Map<String, OptionBase> options;
public static enum Type { public enum Type {
CHECK, CHECK,
SPIN, SPIN,
COMBO, COMBO,
@@ -70,8 +70,8 @@ public class UCIOptions implements Serializable, Cloneable {
SpinOption so = (SpinOption)o; SpinOption so = (SpinOption)o;
return so.set(val); return so.set(val);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
}
return false; return false;
}
case COMBO: case COMBO:
return ((ComboOption)o).set(value); return ((ComboOption)o).set(value);
case BUTTON: case BUTTON:
@@ -251,7 +251,7 @@ public class UCIOptions implements Serializable, Cloneable {
} }
public final String[] getOptionNames() { public final String[] getOptionNames() {
return names.toArray(new String[names.size()]); return names.toArray(new String[0]);
} }
public final OptionBase getOption(String name) { public final OptionBase getOption(String name) {

View File

@@ -208,7 +208,7 @@ public class DroidEngineControl {
} }
} }
static final int clamp(int val, int min, int max) { 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) {
@@ -218,7 +218,7 @@ public class DroidEngineControl {
} }
} }
final private void startThread(final int minTimeLimit, final int maxTimeLimit, private void startThread(final int minTimeLimit, final int maxTimeLimit,
int maxDepth, final int maxNodes) { int maxDepth, final int maxNodes) {
synchronized (threadMutex) {} // Must not start new search until old search is finished synchronized (threadMutex) {} // Must not start new search until old search is finished
sc = new Search(pos, posHashList, posHashListSize, tt, ht); sc = new Search(pos, posHashList, posHashListSize, tt, ht);
@@ -336,7 +336,7 @@ public class DroidEngineControl {
return ret; return ret;
} }
static final String moveToString(Move m) { 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);

View File

@@ -960,7 +960,7 @@ public class GameTree {
return res; return res;
} }
private static final boolean insufficientMaterial(Position pos) { private static boolean insufficientMaterial(Position pos) {
if (pos.nPieces(Piece.WQUEEN) > 0) return false; if (pos.nPieces(Piece.WQUEEN) > 0) return false;
if (pos.nPieces(Piece.WROOK) > 0) return false; if (pos.nPieces(Piece.WROOK) > 0) return false;
if (pos.nPieces(Piece.WPAWN) > 0) return false; if (pos.nPieces(Piece.WPAWN) > 0) return false;
@@ -1125,7 +1125,7 @@ public class GameTree {
throw new RuntimeException(); throw new RuntimeException();
} }
static final void writeToStream(DataOutputStream dos, Node node) throws IOException { static void writeToStream(DataOutputStream dos, Node node) throws IOException {
while (true) { while (true) {
dos.writeUTF(node.moveStr); dos.writeUTF(node.moveStr);
if (node.move != null) { if (node.move != null) {
@@ -1152,7 +1152,7 @@ public class GameTree {
} }
} }
static final void readFromStream(DataInputStream dis, Node node) throws IOException { static void readFromStream(DataInputStream dis, Node node) throws IOException {
while (true) { while (true) {
node.moveStr = dis.readUTF(); node.moveStr = dis.readUTF();
node.moveStrLocal = node.moveStr; node.moveStrLocal = node.moveStr;
@@ -1186,7 +1186,7 @@ public class GameTree {
} }
/** Export whole tree rooted at "node" in PGN format. */ /** Export whole tree rooted at "node" in PGN format. */
public static final void addPgnData(PgnToken.PgnTokenReceiver out, Node node, public static void addPgnData(PgnToken.PgnTokenReceiver out, Node node,
MoveNumber moveNum, PGNOptions options) { MoveNumber moveNum, PGNOptions options) {
boolean needMoveNr = node.addPgnDataOneNode(out, moveNum, true, options); boolean needMoveNr = node.addPgnDataOneNode(out, moveNum, true, options);
while (true) { while (true) {
@@ -1265,7 +1265,7 @@ public class GameTree {
out.processToken(this, PgnToken.COMMENT, "[%" + extCmd + " " + extData + "]"); out.processToken(this, PgnToken.COMMENT, "[%" + extCmd + " " + extData + "]");
} }
private static final String getTimeStr(int remainingTime) { private static String getTimeStr(int remainingTime) {
int secs = (int)Math.floor((remainingTime + 999) / 1000.0); int secs = (int)Math.floor((remainingTime + 999) / 1000.0);
boolean neg = false; boolean neg = false;
if (secs < 0) { if (secs < 0) {
@@ -1411,7 +1411,7 @@ public class GameTree {
} }
} }
private static final Pair<String, String> extractExtInfo(String comment, String cmd) { private static Pair<String, String> extractExtInfo(String comment, String cmd) {
comment = comment.replaceAll("\n|\r|\t", " "); comment = comment.replaceAll("\n|\r|\t", " ");
String remaining = comment; String remaining = comment;
String param = null; String param = null;
@@ -1428,7 +1428,7 @@ public class GameTree {
} }
/** Convert hh:mm:ss to milliseconds */ /** Convert hh:mm:ss to milliseconds */
private static final int parseTimeString(String str) { private static int parseTimeString(String str) {
str = str.trim(); str = str.trim();
int ret = 0; int ret = 0;
boolean neg = false; boolean neg = false;
@@ -1456,7 +1456,7 @@ public class GameTree {
return ret; return ret;
} }
public final static String nagStr(int nag) { public static String nagStr(int nag) {
switch (nag) { switch (nag) {
case 1: return "!"; case 1: return "!";
case 2: return "?"; case 2: return "?";
@@ -1476,7 +1476,7 @@ public class GameTree {
} }
} }
public final static int strToNag(String str) { public static int strToNag(String str) {
if (str.equals("!")) return 1; if (str.equals("!")) return 1;
else if (str.equals("?")) return 2; else if (str.equals("?")) return 2;
else if (str.equals("!!")) return 3; else if (str.equals("!!")) return 3;
@@ -1494,14 +1494,13 @@ public class GameTree {
else { else {
try { try {
str = str.replace("$", ""); str = str.replace("$", "");
int nag = Integer.parseInt(str); return Integer.parseInt(str);
return nag;
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
}
return 0; return 0;
} }
} }
} }
}
/** Set PGN header tags and values. Setting a non-required /** Set PGN header tags and values. Setting a non-required
* tag to null causes it to be removed. * tag to null causes it to be removed.

View File

@@ -156,7 +156,7 @@ public class MoveGen {
/** /**
* Return true if the side to move is in check. * Return true if the side to move is in check.
*/ */
public static final boolean inCheck(Position pos) { public static boolean inCheck(Position pos) {
int kingSq = pos.getKingSq(pos.whiteMove); int kingSq = pos.getKingSq(pos.whiteMove);
if (kingSq < 0) if (kingSq < 0)
return false; return false;
@@ -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 final boolean sqAttacked(Position pos, int sq) { public 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;
@@ -223,7 +223,7 @@ public class MoveGen {
* "moveList" is assumed to be a list of pseudo-legal moves. * "moveList" is assumed to be a list of pseudo-legal moves.
* This function removes the moves that don't defend from check threats. * This function removes the moves that don't defend from check threats.
*/ */
public static final ArrayList<Move> removeIllegal(Position pos, ArrayList<Move> moveList) { public static ArrayList<Move> removeIllegal(Position pos, ArrayList<Move> moveList) {
ArrayList<Move> ret = new ArrayList<>(); ArrayList<Move> ret = new ArrayList<>();
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();
int mlSize = moveList.size(); int mlSize = moveList.size();
@@ -296,7 +296,7 @@ public class MoveGen {
* @return The first piece in the given direction, or EMPTY if there is no piece * @return The first piece in the given direction, or EMPTY if there is no piece
* in that direction. * in that direction.
*/ */
private static final int checkDirection(Position pos, int sq, int maxSteps, int delta) { private static int checkDirection(Position pos, int sq, int maxSteps, int delta) {
while (maxSteps > 0) { while (maxSteps > 0) {
sq += delta; sq += delta;
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
@@ -307,7 +307,7 @@ public class MoveGen {
return Piece.EMPTY; return Piece.EMPTY;
} }
private static final Move getMoveObj(int from, int to, int promoteTo) { private static Move getMoveObj(int from, int to, int promoteTo) {
return new Move(from, to, promoteTo); return new Move(from, to, promoteTo);
} }
} }

View File

@@ -83,8 +83,8 @@ public class Piece {
} }
/** Converts the piece into a character for the material diff. */ /** Converts the piece into a character for the material diff. */
public final static char toUniCode(int p) { public static char toUniCode(int p) {
// As we assume, the coding of the pieces is sequential, lets do some math. // As we assume the coding of the pieces is sequential, lets do some math.
return (char)(WHITE_KING + p - 1); return (char)(WHITE_KING + p - 1);
} }
} }

View File

@@ -132,19 +132,19 @@ public class Position {
} }
} }
/** Return index in squares[] vector corresponding to (x,y). */ /** Return index in squares[] vector corresponding to (x,y). */
public final static int getSquare(int x, int y) { public static int getSquare(int x, int y) {
return y * 8 + x; return y * 8 + x;
} }
/** Return x position (file) corresponding to a square. */ /** Return x position (file) corresponding to a square. */
public final static int getX(int square) { public static int getX(int square) {
return square & 7; return square & 7;
} }
/** Return y position (rank) corresponding to a square. */ /** Return y position (rank) corresponding to a square. */
public final static int getY(int square) { public static int getY(int square) {
return square >> 3; return square >> 3;
} }
/** Return true if (x,y) is a dark square. */ /** Return true if (x,y) is a dark square. */
public final static boolean darkSquare(int x, int y) { public static boolean darkSquare(int x, int y) {
return (x & 1) == (y & 1); return (x & 1) == (y & 1);
} }

View File

@@ -34,14 +34,14 @@ public class TextIO {
private static String[] pieceNames = null; private static String[] pieceNames = null;
/** Set localized piece names. */ /** Set localized piece names. */
public static final void setPieceNames(String pieceNames) { public static void setPieceNames(String pieceNames) {
String[] pn = pieceNames.split(" "); String[] pn = pieceNames.split(" ");
if (pn.length == 6) if (pn.length == 6)
TextIO.pieceNames = pn; TextIO.pieceNames = pn;
} }
/** Parse a FEN string and return a chess Position object. */ /** Parse a FEN string and return a chess Position object. */
public static final Position readFEN(String fen) throws ChessParseError { public static Position readFEN(String fen) throws ChessParseError {
fen = fen.trim(); fen = fen.trim();
Position pos = new Position(); Position pos = new Position();
String[] words = fen.split(" "); String[] words = fen.split(" ");
@@ -198,7 +198,7 @@ public class TextIO {
return pos; return pos;
} }
public static final void removeBogusCastleFlags(Position pos) { public static void removeBogusCastleFlags(Position pos) {
int castleMask = pos.getCastleMask(); int castleMask = pos.getCastleMask();
int validCastle = 0; int validCastle = 0;
if (pos.getPiece(4) == Piece.WKING) { if (pos.getPiece(4) == Piece.WKING) {
@@ -214,7 +214,7 @@ public class TextIO {
} }
/** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */ /** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */
public static final void fixupEPSquare(Position pos) { public static void fixupEPSquare(Position pos) {
int epSquare = pos.getEpSquare(); int epSquare = pos.getEpSquare();
if (epSquare >= 0) { if (epSquare >= 0) {
ArrayList<Move> moves = MoveGen.instance.legalMoves(pos); ArrayList<Move> moves = MoveGen.instance.legalMoves(pos);
@@ -232,7 +232,7 @@ public class TextIO {
} }
} }
private static final void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError { private static void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError {
if (row < 0) throw new ChessParseError(R.string.err_too_many_rows); if (row < 0) throw new ChessParseError(R.string.err_too_many_rows);
if (col > 7) throw new ChessParseError(R.string.err_too_many_columns); if (col > 7) throw new ChessParseError(R.string.err_too_many_columns);
if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) { if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) {
@@ -243,7 +243,7 @@ public class TextIO {
} }
/** Return a FEN string corresponding to a chess Position object. */ /** Return a FEN string corresponding to a chess Position object. */
public static final String toFEN(Position pos) { public static String toFEN(Position pos) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
// Piece placement // Piece placement
for (int r = 7; r >=0; r--) { for (int r = 7; r >=0; r--) {
@@ -335,11 +335,11 @@ public class TextIO {
* Otherwise, use short notation, eg Nf3. * Otherwise, use short notation, eg Nf3.
* @param localized If true, use localized piece names. * @param localized If true, use localized piece names.
*/ */
public static final String moveToString(Position pos, Move move, boolean longForm, public static String moveToString(Position pos, Move move, boolean longForm,
boolean localized) { boolean localized) {
return moveToString(pos, move, longForm, localized, null); return moveToString(pos, move, longForm, localized, null);
} }
public static final String moveToString(Position pos, Move move, boolean longForm, public static String moveToString(Position pos, Move move, boolean longForm,
boolean localized, List<Move> moves) { boolean localized, List<Move> moves) {
if ((move == null) || move.equals(new Move(0, 0, 0))) if ((move == null) || move.equals(new Move(0, 0, 0)))
return "--"; return "--";
@@ -439,7 +439,7 @@ public class TextIO {
return ret.toString(); return ret.toString();
} }
private static final 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())) { if ((p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare())) {
@@ -458,7 +458,7 @@ public class TextIO {
* @param move The move to check for validity. * @param move The move to check for validity.
* @return True if move is valid in position pos, false otherwise. * @return True if move is valid in position pos, false otherwise.
*/ */
public static final boolean isValid(Position pos, Move move) { public static boolean isValid(Position pos, Move move) {
if (move == null) if (move == null)
return false; return false;
ArrayList<Move> moves = new MoveGen().legalMoves(pos); ArrayList<Move> moves = new MoveGen().legalMoves(pos);
@@ -480,10 +480,10 @@ public class TextIO {
* The string may specify any combination of piece/source/target/promotion * The string may specify any combination of piece/source/target/promotion
* information as long as it matches exactly one valid move. * information as long as it matches exactly one valid move.
*/ */
public static final Move stringToMove(Position pos, String strMove) { public static Move stringToMove(Position pos, String strMove) {
return stringToMove(pos, strMove, null); return stringToMove(pos, strMove, null);
} }
public static final Move stringToMove(Position pos, String strMove, public static Move stringToMove(Position pos, String strMove,
ArrayList<Move> moves) { ArrayList<Move> moves) {
if (strMove.equals("--")) if (strMove.equals("--"))
return new Move(0, 0, 0); return new Move(0, 0, 0);
@@ -608,7 +608,7 @@ public class TextIO {
} }
/** Convert a move object to UCI string format. */ /** Convert a move object to UCI string format. */
public static final String moveToUCIString(Move m) { public static String moveToUCIString(Move m) {
String ret = squareToString(m.from); String ret = squareToString(m.from);
ret += squareToString(m.to); ret += squareToString(m.to);
switch (m.promoteTo) { switch (m.promoteTo) {
@@ -638,7 +638,7 @@ public class TextIO {
* Convert a string in UCI move format to a Move object. * Convert a string in UCI move format to a Move object.
* @return A move object, or null if move has invalid syntax * @return A move object, or null if move has invalid syntax
*/ */
public static final Move UCIstringToMove(String move) { public static Move UCIstringToMove(String move) {
Move m = null; Move m = null;
if ((move.length() < 4) || (move.length() > 5)) if ((move.length() < 4) || (move.length() > 5))
return m; return m;
@@ -687,7 +687,7 @@ public class TextIO {
* Convert a string, such as "e4" to a square number. * Convert a string, such as "e4" to a square number.
* @return The square number, or -1 if not a legal square. * @return The square number, or -1 if not a legal square.
*/ */
public static final int getSquare(String s) { public static int getSquare(String s) {
int x = s.charAt(0) - 'a'; int x = s.charAt(0) - 'a';
int y = s.charAt(1) - '1'; int y = s.charAt(1) - '1';
if ((x < 0) || (x > 7) || (y < 0) || (y > 7)) if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
@@ -698,7 +698,7 @@ public class TextIO {
/** /**
* Convert a square number to a string, such as "e4". * Convert a square number to a string, such as "e4".
*/ */
public static final String squareToString(int square) { public static String squareToString(int square) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int x = Position.getX(square); int x = Position.getX(square);
int y = Position.getY(square); int y = Position.getY(square);
@@ -710,7 +710,7 @@ public class TextIO {
/** /**
* Create an ascii representation of a position. * Create an ascii representation of a position.
*/ */
public static final String asciiBoard(Position pos) { public static String asciiBoard(Position pos) {
StringBuilder ret = new StringBuilder(400); StringBuilder ret = new StringBuilder(400);
String nl = String.format(Locale.US, "%n"); String nl = String.format(Locale.US, "%n");
ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl);
@@ -739,7 +739,7 @@ public class TextIO {
} }
/** Convert a piece and a square to a string, such as Nf3. */ /** Convert a piece and a square to a string, such as Nf3. */
public final static String pieceAndSquareToString(int currentPieceType, int p, int sq) { public static String pieceAndSquareToString(int currentPieceType, int p, int sq) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
if (currentPieceType == PGNOptions.PT_FIGURINE) { if (currentPieceType == PGNOptions.PT_FIGURINE) {
ret.append(Piece.toUniCode(p)); ret.append(Piece.toUniCode(p));
@@ -765,7 +765,7 @@ public class TextIO {
return ""; return "";
} }
public final static String pieceToCharLocalized(int p) { public static String pieceToCharLocalized(int p) {
switch (p) { switch (p) {
case Piece.WQUEEN: case Piece.BQUEEN: return pieceNames[4]; case Piece.WQUEEN: case Piece.BQUEEN: return pieceNames[4];
case Piece.WROOK: case Piece.BROOK: return pieceNames[3]; case Piece.WROOK: case Piece.BROOK: return pieceNames[3];
@@ -789,7 +789,7 @@ public class TextIO {
} }
/** Add an = sign to a promotion move, as required by the PGN standard. */ /** Add an = sign to a promotion move, as required by the PGN standard. */
public final static String pgnPromotion(String str) { public static String pgnPromotion(String str) {
int idx = str.length() - 1; int idx = str.length() - 1;
while (idx > 0) { while (idx > 0) {
char c = str.charAt(idx); char c = str.charAt(idx);

View File

@@ -97,7 +97,7 @@ public final class ProbeResult implements Comparable<ProbeResult> {
/** Return f((wdl1,score1)) - f((wdl2,score2)), where f(x) modifies /** Return f((wdl1,score1)) - f((wdl2,score2)), where f(x) modifies
* the score so that larger values are better. */ * the score so that larger values are better. */
final static int compareScore(int wdl1, int score1, static int compareScore(int wdl1, int score1,
int wdl2, int score2) { int wdl2, int score2) {
final int M = 1000; final int M = 1000;
if (wdl1 > 0) if (wdl1 > 0)

View File

@@ -303,7 +303,6 @@ public abstract 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) {
boolean doInvalidate = false; boolean doInvalidate = false;
@@ -480,7 +479,7 @@ public abstract class ChessBoard extends View {
float x4 = (float)(x3 - d * sinv); float x4 = (float)(x3 - d * sinv);
float y4 = (float)(y3 + d * cosv); float y4 = (float)(y3 + d * cosv);
float x5 = (float)(x4 + (-d/2 - y4) / tanv); float x5 = (float)(x4 + (-d/2 - y4) / tanv);
float y5 = (float)(-d / 2); float y5 = -d / 2;
float x6 = 0; float x6 = 0;
float y6 = y5 / 2; float y6 = y5 / 2;
Path path = new Path(); Path path = new Path();

View File

@@ -280,8 +280,8 @@ public class TourGuide {
LayoutInflater layoutInflater = mActivity.getLayoutInflater(); LayoutInflater layoutInflater = mActivity.getLayoutInflater();
mToolTipViewGroup = layoutInflater.inflate(R.layout.tooltip, null); mToolTipViewGroup = layoutInflater.inflate(R.layout.tooltip, null);
View toolTipContainer = mToolTipViewGroup.findViewById(R.id.toolTip_container); View toolTipContainer = mToolTipViewGroup.findViewById(R.id.toolTip_container);
TextView toolTipTitleTV = (TextView) mToolTipViewGroup.findViewById(R.id.title); TextView toolTipTitleTV = mToolTipViewGroup.findViewById(R.id.title);
TextView toolTipDescriptionTV = (TextView) mToolTipViewGroup.findViewById(R.id.description); TextView toolTipDescriptionTV = mToolTipViewGroup.findViewById(R.id.description);
/* set tooltip attributes */ /* set tooltip attributes */
toolTipContainer.setBackgroundColor(mToolTip.mBackgroundColor); toolTipContainer.setBackgroundColor(mToolTip.mBackgroundColor);
@@ -449,7 +449,7 @@ public class TourGuide {
private void setupFrameLayout(){ private void setupFrameLayout(){
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
ViewGroup contentArea = (ViewGroup) mActivity.getWindow().getDecorView().findViewById(android.R.id.content); ViewGroup contentArea = mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
int [] pos = new int[2]; int [] pos = new int[2];
contentArea.getLocationOnScreen(pos); contentArea.getLocationOnScreen(pos);
// frameLayoutWithHole's coordinates are calculated taking full screen height into account // frameLayoutWithHole's coordinates are calculated taking full screen height into account

View File

@@ -170,7 +170,7 @@ public class BitBoard {
0x000000007efa8146L, 0x0000007ed3e2ef60L, 0x00007f47243adcd6L, 0x007fb65afabfb3b5L 0x000000007efa8146L, 0x0000007ed3e2ef60L, 0x00007f47243adcd6L, 0x007fb65afabfb3b5L
}; };
private static final long createPattern(int i, long mask) { private static long createPattern(int i, long mask) {
long ret = 0L; long ret = 0L;
for (int j = 0; ; j++) { for (int j = 0; ; j++) {
long nextMask = mask & (mask - 1); long nextMask = mask & (mask - 1);
@@ -184,7 +184,7 @@ public class BitBoard {
return ret; return ret;
} }
private static final long addRookRays(int x, int y, long occupied, boolean inner) { private static long addRookRays(int x, int y, long occupied, boolean inner) {
long mask = 0; long mask = 0;
mask = addRay(mask, x, y, 1, 0, occupied, inner); mask = addRay(mask, x, y, 1, 0, occupied, inner);
mask = addRay(mask, x, y, -1, 0, occupied, inner); mask = addRay(mask, x, y, -1, 0, occupied, inner);
@@ -192,7 +192,7 @@ public class BitBoard {
mask = addRay(mask, x, y, 0, -1, occupied, inner); mask = addRay(mask, x, y, 0, -1, occupied, inner);
return mask; return mask;
} }
private static final long addBishopRays(int x, int y, long occupied, boolean inner) { private static long addBishopRays(int x, int y, long occupied, boolean inner) {
long mask = 0; long mask = 0;
mask = addRay(mask, x, y, 1, 1, occupied, inner); mask = addRay(mask, x, y, 1, 1, occupied, inner);
mask = addRay(mask, x, y, -1, -1, occupied, inner); mask = addRay(mask, x, y, -1, -1, occupied, inner);
@@ -201,7 +201,7 @@ public class BitBoard {
return mask; return mask;
} }
private static final long addRay(long mask, int x, int y, int dx, int dy, private static long addRay(long mask, int x, int y, int dx, int dy,
long occupied, boolean inner) { long occupied, boolean inner) {
int lo = inner ? 1 : 0; int lo = inner ? 1 : 0;
int hi = inner ? 6 : 7; int hi = inner ? 6 : 7;
@@ -270,11 +270,11 @@ public class BitBoard {
} }
} }
public static final long bishopAttacks(int sq, long occupied) { public static long bishopAttacks(int sq, long occupied) {
return bTables[sq][(int)(((occupied & bMasks[sq]) * bMagics[sq]) >>> (64 - bBits[sq]))]; return bTables[sq][(int)(((occupied & bMasks[sq]) * bMagics[sq]) >>> (64 - bBits[sq]))];
} }
public static final long rookAttacks(int sq, long occupied) { public static long rookAttacks(int sq, long occupied) {
return rTables[sq][(int)(((occupied & rMasks[sq]) * rMagics[sq]) >>> (64 - rBits[sq]))]; return rTables[sq][(int)(((occupied & rMasks[sq]) * rMagics[sq]) >>> (64 - rBits[sq]))];
} }
@@ -346,19 +346,19 @@ public class BitBoard {
0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
}; };
public static final int getDistance(int from, int to) { public static int getDistance(int from, int to) {
int offs = to + (to|7) - from - (from|7) + 0x77; int offs = to + (to|7) - from - (from|7) + 0x77;
return distTable[offs]; return distTable[offs];
} }
public static final long southFill(long mask) { public static long southFill(long mask) {
mask |= (mask >>> 8); mask |= (mask >>> 8);
mask |= (mask >>> 16); mask |= (mask >>> 16);
mask |= (mask >>> 32); mask |= (mask >>> 32);
return mask; return mask;
} }
public static final long northFill(long mask) { public static long northFill(long mask) {
mask |= (mask << 8); mask |= (mask << 8);
mask |= (mask << 16); mask |= (mask << 16);
mask |= (mask << 32); mask |= (mask << 32);

View File

@@ -162,7 +162,7 @@ public class Book {
throw new RuntimeException(); throw new RuntimeException();
} }
final private int getWeight(int count) { private int getWeight(int count) {
double tmp = Math.sqrt(count); double tmp = Math.sqrt(count);
return (int)(tmp * Math.sqrt(tmp) * 100 + 1); return (int)(tmp * Math.sqrt(tmp) * 100 + 1);
} }

View File

@@ -290,7 +290,7 @@ public class Evaluate {
} }
/** Compute white_material - black_material. */ /** Compute white_material - black_material. */
static final int material(Position pos) { static int material(Position pos) {
return pos.wMtrl - pos.bMtrl; return pos.wMtrl - pos.bMtrl;
} }
@@ -1135,7 +1135,7 @@ public class Evaluate {
return score; return score;
} }
private static final int evalKQKP(int wKing, int wQueen, int bKing, int bPawn, boolean whiteMove) { private static int evalKQKP(int wKing, int wQueen, int bKing, int bPawn, boolean whiteMove) {
boolean canWin = false; boolean canWin = false;
if (((1L << bKing) & 0xFFFF) == 0) { if (((1L << bKing) & 0xFFFF) == 0) {
canWin = true; // King doesn't support pawn canWin = true; // King doesn't support pawn
@@ -1172,7 +1172,7 @@ public class Evaluate {
return score; return score;
} }
private static final int kpkEval(int wKing, int bKing, int wPawn, boolean whiteMove) { private static int kpkEval(int wKing, int bKing, int wPawn, boolean whiteMove) {
if (Position.getX(wKing) >= 4) { // Mirror X if (Position.getX(wKing) >= 4) { // Mirror X
wKing ^= 7; wKing ^= 7;
bKing ^= 7; bKing ^= 7;
@@ -1191,7 +1191,7 @@ public class Evaluate {
return qV - pV / 4 * (7-Position.getY(wPawn)); return qV - pV / 4 * (7-Position.getY(wPawn));
} }
private static final int krkpEval(int wKing, int bKing, int bPawn, boolean whiteMove) { private static int krkpEval(int wKing, int bKing, int bPawn, boolean whiteMove) {
if (Position.getX(bKing) >= 4) { // Mirror X if (Position.getX(bKing) >= 4) { // Mirror X
wKing ^= 7; wKing ^= 7;
bKing ^= 7; bKing ^= 7;
@@ -1216,7 +1216,7 @@ public class Evaluate {
* Interpolate between (x1,y1) and (x2,y2). * Interpolate between (x1,y1) and (x2,y2).
* If x < x1, return y1, if x > x2 return y2. Otherwise, use linear interpolation. * If x < x1, return y1, if x > x2 return y2. Otherwise, use linear interpolation.
*/ */
static final int interpolate(int x, int x1, int y1, int x2, int y2) { static int interpolate(int x, int x1, int y1, int x2, int y2) {
if (x > x2) { if (x > x2) {
return y2; return y2;
} else if (x < x1) { } else if (x < x1) {

View File

@@ -717,7 +717,7 @@ public final class MoveGen {
/** /**
* Return true if the side to move is in check. * Return true if the side to move is in check.
*/ */
public static final boolean inCheck(Position pos) { public static boolean inCheck(Position pos) {
int kingSq = pos.getKingSq(pos.whiteMove); int kingSq = pos.getKingSq(pos.whiteMove);
return sqAttacked(pos, kingSq); return sqAttacked(pos, kingSq);
} }
@@ -725,7 +725,7 @@ public final class MoveGen {
/** /**
* Return the next piece in a given direction, starting from sq. * Return the next piece in a given direction, starting from sq.
*/ */
private static final int nextPiece(Position pos, int sq, int delta) { private static int nextPiece(Position pos, int sq, int delta) {
while (true) { while (true) {
sq += delta; sq += delta;
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
@@ -735,7 +735,7 @@ public final class MoveGen {
} }
/** Like nextPiece(), but handles board edges. */ /** Like nextPiece(), but handles board edges. */
private static final int nextPieceSafe(Position pos, int sq, int delta) { private static int nextPieceSafe(Position pos, int sq, int delta) {
int dx = 0, dy = 0; int dx = 0, dy = 0;
switch (delta) { switch (delta) {
case 1: dx=1; dy=0; break; case 1: dx=1; dy=0; break;
@@ -764,7 +764,7 @@ public final class MoveGen {
/** /**
* Return true if making a move delivers check to the opponent * Return true if making a move delivers check to the opponent
*/ */
public static final boolean givesCheck(Position pos, Move m) { public static boolean givesCheck(Position pos, Move m) {
boolean wtm = pos.whiteMove; boolean wtm = pos.whiteMove;
int oKingSq = pos.getKingSq(!wtm); int oKingSq = pos.getKingSq(!wtm);
int oKing = wtm ? Piece.BKING : Piece.WKING; int oKing = wtm ? Piece.BKING : Piece.WKING;
@@ -875,7 +875,7 @@ public final class MoveGen {
/** /**
* Return true if the side to move can take the opponents king. * Return true if the side to move can take the opponents king.
*/ */
public static final boolean canTakeKing(Position pos) { public static boolean canTakeKing(Position pos) {
pos.setWhiteMove(!pos.whiteMove); pos.setWhiteMove(!pos.whiteMove);
boolean ret = inCheck(pos); boolean ret = inCheck(pos);
pos.setWhiteMove(!pos.whiteMove); pos.setWhiteMove(!pos.whiteMove);
@@ -885,7 +885,7 @@ public final 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 final boolean sqAttacked(Position pos, int sq) { public static boolean sqAttacked(Position pos, int sq) {
if (pos.whiteMove) { if (pos.whiteMove) {
if ((BitBoard.knightAttacks[sq] & pos.pieceTypeBB[Piece.BKNIGHT]) != 0) if ((BitBoard.knightAttacks[sq] & pos.pieceTypeBB[Piece.BKNIGHT]) != 0)
return true; return true;
@@ -921,7 +921,7 @@ public final class MoveGen {
* "moveList" is assumed to be a list of pseudo-legal moves. * "moveList" is assumed to be a list of pseudo-legal moves.
* This function removes the moves that don't defend from check threats. * This function removes the moves that don't defend from check threats.
*/ */
public static final void removeIllegal(Position pos, MoveList moveList) { public static void removeIllegal(Position pos, MoveList moveList) {
int length = 0; int length = 0;
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();

View File

@@ -89,7 +89,7 @@ public class Parameters {
for (Map.Entry<String, ParamBase> e : params.entrySet()) for (Map.Entry<String, ParamBase> e : params.entrySet())
if (e.getValue().visible) if (e.getValue().visible)
parNames.add(e.getKey()); parNames.add(e.getKey());
return parNames.toArray(new String[parNames.size()]); return parNames.toArray(new String[0]);
} }
public final ParamBase getParam(String name) { public final ParamBase getParam(String name) {

View File

@@ -42,13 +42,13 @@ public class Piece {
* Return true if p is a white piece, false otherwise. * Return true if p is a white piece, false otherwise.
* Note that if p is EMPTY, an unspecified value is returned. * Note that if p is EMPTY, an unspecified value is returned.
*/ */
public static final boolean isWhite(int pType) { public static boolean isWhite(int pType) {
return pType < BKING; return pType < BKING;
} }
public static final int makeWhite(int pType) { public static int makeWhite(int pType) {
return pType < BKING ? pType : pType - (BKING - WKING); return pType < BKING ? pType : pType - (BKING - WKING);
} }
public static final int makeBlack(int pType) { public static int makeBlack(int pType) {
return ((pType > EMPTY) && (pType < BKING)) ? pType + (BKING - WKING) : pType; return ((pType > EMPTY) && (pType < BKING)) ? pType + (BKING - WKING) : pType;
} }
} }

View File

@@ -188,19 +188,19 @@ public class Position {
} }
} }
/** Return index in squares[] vector corresponding to (x,y). */ /** Return index in squares[] vector corresponding to (x,y). */
public final static int getSquare(int x, int y) { public static int getSquare(int x, int y) {
return y * 8 + x; return y * 8 + x;
} }
/** Return x position (file) corresponding to a square. */ /** Return x position (file) corresponding to a square. */
public final static int getX(int square) { public static int getX(int square) {
return square & 7; return square & 7;
} }
/** Return y position (rank) corresponding to a square. */ /** Return y position (rank) corresponding to a square. */
public final static int getY(int square) { public static int getY(int square) {
return square >> 3; return square >> 3;
} }
/** Return true if (x,y) is a dark square. */ /** Return true if (x,y) is a dark square. */
public final static boolean darkSquare(int x, int y) { public static boolean darkSquare(int x, int y) {
return (x & 1) == (y & 1); return (x & 1) == (y & 1);
} }

View File

@@ -24,7 +24,7 @@ public class TextIO {
static public final String startPosFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; static public final String startPosFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
/** Parse a FEN string and return a chess Position object. */ /** Parse a FEN string and return a chess Position object. */
public static final Position readFEN(String fen) throws ChessParseError { public static Position readFEN(String fen) throws ChessParseError {
Position pos = new Position(); Position pos = new Position();
String[] words = fen.split(" "); String[] words = fen.split(" ");
if (words.length < 2) { if (words.length < 2) {
@@ -148,7 +148,7 @@ public class TextIO {
} }
/** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */ /** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */
public static final void fixupEPSquare(Position pos) { public static void fixupEPSquare(Position pos) {
int epSquare = pos.getEpSquare(); int epSquare = pos.getEpSquare();
if (epSquare >= 0) { if (epSquare >= 0) {
MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos); MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos);
@@ -169,7 +169,7 @@ public class TextIO {
} }
} }
private static final void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError { private static void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError {
if (row < 0) throw new ChessParseError("Too many rows"); if (row < 0) throw new ChessParseError("Too many rows");
if (col > 7) throw new ChessParseError("Too many columns"); if (col > 7) throw new ChessParseError("Too many columns");
if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) { if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) {
@@ -180,7 +180,7 @@ public class TextIO {
} }
/** Return a FEN string corresponding to a chess Position object. */ /** Return a FEN string corresponding to a chess Position object. */
public static final String toFEN(Position pos) { public static String toFEN(Position pos) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
// Piece placement // Piece placement
for (int r = 7; r >=0; r--) { for (int r = 7; r >=0; r--) {
@@ -271,12 +271,12 @@ public class TextIO {
* @param longForm If true, use long notation, eg Ng1-f3. * @param longForm If true, use long notation, eg Ng1-f3.
* Otherwise, use short notation, eg Nf3 * Otherwise, use short notation, eg Nf3
*/ */
public static final String moveToString(Position pos, Move move, boolean longForm) { public static String moveToString(Position pos, Move move, boolean longForm) {
MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos); MoveGen.MoveList moves = MoveGen.instance.pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos, moves); MoveGen.removeIllegal(pos, moves);
return moveToString(pos, move, longForm, moves); return moveToString(pos, move, longForm, moves);
} }
private static final String moveToString(Position pos, Move move, boolean longForm, MoveGen.MoveList moves) { private static String moveToString(Position pos, Move move, boolean longForm, MoveGen.MoveList moves) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int wKingOrigPos = Position.getSquare(4, 0); int wKingOrigPos = Position.getSquare(4, 0);
int bKingOrigPos = Position.getSquare(4, 7); int bKingOrigPos = Position.getSquare(4, 7);
@@ -365,7 +365,7 @@ public class TextIO {
} }
/** Convert a move object to UCI string format. */ /** Convert a move object to UCI string format. */
public static final String moveToUCIString(Move m) { public static String moveToUCIString(Move m) {
String ret = squareToString(m.from); String ret = squareToString(m.from);
ret += squareToString(m.to); ret += squareToString(m.to);
switch (m.promoteTo) { switch (m.promoteTo) {
@@ -395,7 +395,7 @@ public class TextIO {
* Convert a string to a Move object. * Convert a string to a Move object.
* @return A move object, or null if move has invalid syntax * @return A move object, or null if move has invalid syntax
*/ */
public static final Move uciStringToMove(String move) { public static Move uciStringToMove(String move) {
Move m = null; Move m = null;
if ((move.length() < 4) || (move.length() > 5)) if ((move.length() < 4) || (move.length() > 5))
return m; return m;
@@ -440,7 +440,7 @@ public class TextIO {
return m; return m;
} }
private static final 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())) { if ((p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare())) {
@@ -458,7 +458,7 @@ public class TextIO {
* Any prefix of the string representation of a valid move counts as a legal move string, * Any prefix of the string representation of a valid move counts as a legal move string,
* as long as the string only matches one valid move. * as long as the string only matches one valid move.
*/ */
public static final Move stringToMove(Position pos, String strMove) { public static Move stringToMove(Position pos, String strMove) {
strMove = strMove.replaceAll("=", ""); strMove = strMove.replaceAll("=", "");
Move move = null; Move move = null;
if (strMove.length() == 0) if (strMove.length() == 0)
@@ -533,7 +533,7 @@ public class TextIO {
* Convert a string, such as "e4" to a square number. * Convert a string, such as "e4" to a square number.
* @return The square number, or -1 if not a legal square. * @return The square number, or -1 if not a legal square.
*/ */
public static final int getSquare(String s) { public static int getSquare(String s) {
int x = s.charAt(0) - 'a'; int x = s.charAt(0) - 'a';
int y = s.charAt(1) - '1'; int y = s.charAt(1) - '1';
if ((x < 0) || (x > 7) || (y < 0) || (y > 7)) if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
@@ -544,7 +544,7 @@ public class TextIO {
/** /**
* Convert a square number to a string, such as "e4". * Convert a square number to a string, such as "e4".
*/ */
public static final String squareToString(int square) { public static String squareToString(int square) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int x = Position.getX(square); int x = Position.getX(square);
int y = Position.getY(square); int y = Position.getY(square);
@@ -556,7 +556,7 @@ public class TextIO {
/** /**
* Create an ascii representation of a position. * Create an ascii representation of a position.
*/ */
public static final String asciiBoard(Position pos) { public static String asciiBoard(Position pos) {
StringBuilder ret = new StringBuilder(400); StringBuilder ret = new StringBuilder(400);
String nl = String.format(Locale.US, "%n"); String nl = String.format(Locale.US, "%n");
ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl);
@@ -587,7 +587,7 @@ public class TextIO {
/** /**
* Convert move string to lower case and remove special check/mate symbols. * Convert move string to lower case and remove special check/mate symbols.
*/ */
private static final String normalizeMoveString(String str) { private static String normalizeMoveString(String str) {
if (str.length() > 0) { if (str.length() > 0) {
char lastChar = str.charAt(str.length() - 1); char lastChar = str.charAt(str.length() - 1);
if ((lastChar == '#') || (lastChar == '+')) { if ((lastChar == '#') || (lastChar == '+')) {

View File

@@ -40,7 +40,7 @@ public class FileUtil {
while ((line = inBuf.readLine()) != null) while ((line = inBuf.readLine()) != null)
ret.add(line); ret.add(line);
inBuf.close(); inBuf.close();
return ret.toArray(new String[ret.size()]); return ret.toArray(new String[0]);
} }
/** Read all data from an input stream. Return null if IO error. */ /** Read all data from an input stream. Return null if IO error. */
@@ -81,7 +81,7 @@ public class FileUtil {
} }
/** Return the length of a file, or -1 if length can not be determined. */ /** Return the length of a file, or -1 if length can not be determined. */
public static final long getFileLength(String filename) { public static long getFileLength(String filename) {
try { try {
RandomAccessFile raf = new RandomAccessFile(filename, "r"); RandomAccessFile raf = new RandomAccessFile(filename, "r");
try { try {

View File

@@ -944,7 +944,7 @@ public class GameTree {
return res; return res;
} }
private static final boolean insufficientMaterial(Position pos) { private static boolean insufficientMaterial(Position pos) {
if (pos.nPieces(Piece.WQUEEN) > 0) return false; if (pos.nPieces(Piece.WQUEEN) > 0) return false;
if (pos.nPieces(Piece.WROOK) > 0) return false; if (pos.nPieces(Piece.WROOK) > 0) return false;
if (pos.nPieces(Piece.WPAWN) > 0) return false; if (pos.nPieces(Piece.WPAWN) > 0) return false;
@@ -1109,7 +1109,7 @@ public class GameTree {
throw new RuntimeException(); throw new RuntimeException();
} }
static final void writeToStream(DataOutputStream dos, Node node) throws IOException { static void writeToStream(DataOutputStream dos, Node node) throws IOException {
while (true) { while (true) {
dos.writeUTF(node.moveStr); dos.writeUTF(node.moveStr);
if (node.move != null) { if (node.move != null) {
@@ -1136,7 +1136,7 @@ public class GameTree {
} }
} }
static final void readFromStream(DataInputStream dis, Node node) throws IOException { static void readFromStream(DataInputStream dis, Node node) throws IOException {
while (true) { while (true) {
node.moveStr = dis.readUTF(); node.moveStr = dis.readUTF();
node.moveStrLocal = node.moveStr; node.moveStrLocal = node.moveStr;
@@ -1170,7 +1170,7 @@ public class GameTree {
} }
/** Export whole tree rooted at "node" in PGN format. */ /** Export whole tree rooted at "node" in PGN format. */
public static final void addPgnData(PgnToken.PgnTokenReceiver out, Node node, public static void addPgnData(PgnToken.PgnTokenReceiver out, Node node,
MoveNumber moveNum, PGNOptions options) { MoveNumber moveNum, PGNOptions options) {
boolean needMoveNr = node.addPgnDataOneNode(out, moveNum, true, options); boolean needMoveNr = node.addPgnDataOneNode(out, moveNum, true, options);
while (true) { while (true) {
@@ -1249,7 +1249,7 @@ public class GameTree {
out.processToken(this, PgnToken.COMMENT, "[%" + extCmd + " " + extData + "]"); out.processToken(this, PgnToken.COMMENT, "[%" + extCmd + " " + extData + "]");
} }
private static final String getTimeStr(int remainingTime) { private static String getTimeStr(int remainingTime) {
int secs = (int)Math.floor((remainingTime + 999) / 1000.0); int secs = (int)Math.floor((remainingTime + 999) / 1000.0);
boolean neg = false; boolean neg = false;
if (secs < 0) { if (secs < 0) {
@@ -1279,7 +1279,7 @@ public class GameTree {
return child; return child;
} }
public static final void parsePgn(PgnScanner scanner, Node node, PGNOptions options) { public static void parsePgn(PgnScanner scanner, Node node, PGNOptions options) {
Node nodeToAdd = new Node(); Node nodeToAdd = new Node();
boolean moveAdded = false; boolean moveAdded = false;
while (true) { while (true) {
@@ -1395,7 +1395,7 @@ public class GameTree {
} }
} }
private static final Pair<String, String> extractExtInfo(String comment, String cmd) { private static Pair<String, String> extractExtInfo(String comment, String cmd) {
comment = comment.replaceAll("\n|\r|\t", " "); comment = comment.replaceAll("\n|\r|\t", " ");
String remaining = comment; String remaining = comment;
String param = null; String param = null;
@@ -1412,7 +1412,7 @@ public class GameTree {
} }
/** Convert hh:mm:ss to milliseconds */ /** Convert hh:mm:ss to milliseconds */
private static final int parseTimeString(String str) { private static int parseTimeString(String str) {
str = str.trim(); str = str.trim();
int ret = 0; int ret = 0;
boolean neg = false; boolean neg = false;
@@ -1440,7 +1440,7 @@ public class GameTree {
return ret; return ret;
} }
public final static String nagStr(int nag) { public static String nagStr(int nag) {
switch (nag) { switch (nag) {
case 1: return "!"; case 1: return "!";
case 2: return "?"; case 2: return "?";
@@ -1460,7 +1460,7 @@ public class GameTree {
} }
} }
public final static int strToNag(String str) { public static int strToNag(String str) {
if (str.equals("!")) return 1; if (str.equals("!")) return 1;
else if (str.equals("?")) return 2; else if (str.equals("?")) return 2;
else if (str.equals("!!")) return 3; else if (str.equals("!!")) return 3;

View File

@@ -156,7 +156,7 @@ public class MoveGen {
/** /**
* Return true if the side to move is in check. * Return true if the side to move is in check.
*/ */
public static final boolean inCheck(Position pos) { public static boolean inCheck(Position pos) {
int kingSq = pos.getKingSq(pos.whiteMove); int kingSq = pos.getKingSq(pos.whiteMove);
if (kingSq < 0) if (kingSq < 0)
return false; return false;
@@ -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 final boolean sqAttacked(Position pos, int sq) { public 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;
@@ -223,7 +223,7 @@ public class MoveGen {
* "moveList" is assumed to be a list of pseudo-legal moves. * "moveList" is assumed to be a list of pseudo-legal moves.
* This function removes the moves that don't defend from check threats. * This function removes the moves that don't defend from check threats.
*/ */
public static final ArrayList<Move> removeIllegal(Position pos, ArrayList<Move> moveList) { public static ArrayList<Move> removeIllegal(Position pos, ArrayList<Move> moveList) {
ArrayList<Move> ret = new ArrayList<>(); ArrayList<Move> ret = new ArrayList<>();
UndoInfo ui = new UndoInfo(); UndoInfo ui = new UndoInfo();
int mlSize = moveList.size(); int mlSize = moveList.size();
@@ -296,7 +296,7 @@ public class MoveGen {
* @return The first piece in the given direction, or EMPTY if there is no piece * @return The first piece in the given direction, or EMPTY if there is no piece
* in that direction. * in that direction.
*/ */
private static final int checkDirection(Position pos, int sq, int maxSteps, int delta) { private static int checkDirection(Position pos, int sq, int maxSteps, int delta) {
while (maxSteps > 0) { while (maxSteps > 0) {
sq += delta; sq += delta;
int p = pos.getPiece(sq); int p = pos.getPiece(sq);
@@ -307,7 +307,7 @@ public class MoveGen {
return Piece.EMPTY; return Piece.EMPTY;
} }
private static final Move getMoveObj(int from, int to, int promoteTo) { private static Move getMoveObj(int from, int to, int promoteTo) {
return new Move(from, to, promoteTo); return new Move(from, to, promoteTo);
} }
} }

View File

@@ -83,7 +83,7 @@ public class Piece {
} }
/** Converts the piece into a character for the material diff. */ /** Converts the piece into a character for the material diff. */
public final static char toUniCode(int p) { public static char toUniCode(int p) {
// As we assume, the coding of the pieces is sequential, lets do some math. // As we assume, the coding of the pieces is sequential, lets do some math.
return (char)(WHITE_KING + p - 1); return (char)(WHITE_KING + p - 1);
} }

View File

@@ -132,19 +132,19 @@ public class Position {
} }
} }
/** Return index in squares[] vector corresponding to (x,y). */ /** Return index in squares[] vector corresponding to (x,y). */
public final static int getSquare(int x, int y) { public static int getSquare(int x, int y) {
return y * 8 + x; return y * 8 + x;
} }
/** Return x position (file) corresponding to a square. */ /** Return x position (file) corresponding to a square. */
public final static int getX(int square) { public static int getX(int square) {
return square & 7; return square & 7;
} }
/** Return y position (rank) corresponding to a square. */ /** Return y position (rank) corresponding to a square. */
public final static int getY(int square) { public static int getY(int square) {
return square >> 3; return square >> 3;
} }
/** Return true if (x,y) is a dark square. */ /** Return true if (x,y) is a dark square. */
public final static boolean darkSquare(int x, int y) { public static boolean darkSquare(int x, int y) {
return (x & 1) == (y & 1); return (x & 1) == (y & 1);
} }

View File

@@ -33,14 +33,14 @@ public class TextIO {
private static String[] pieceNames = null; private static String[] pieceNames = null;
/** Set localized piece names. */ /** Set localized piece names. */
public static final void setPieceNames(String pieceNames) { public static void setPieceNames(String pieceNames) {
String[] pn = pieceNames.split(" "); String[] pn = pieceNames.split(" ");
if (pn.length == 6) if (pn.length == 6)
TextIO.pieceNames = pn; TextIO.pieceNames = pn;
} }
/** Parse a FEN string and return a chess Position object. */ /** Parse a FEN string and return a chess Position object. */
public static final Position readFEN(String fen) throws ChessParseError { public static Position readFEN(String fen) throws ChessParseError {
fen = fen.trim(); fen = fen.trim();
Position pos = new Position(); Position pos = new Position();
String[] words = fen.split(" "); String[] words = fen.split(" ");
@@ -197,7 +197,7 @@ public class TextIO {
return pos; return pos;
} }
public static final void removeBogusCastleFlags(Position pos) { public static void removeBogusCastleFlags(Position pos) {
int castleMask = pos.getCastleMask(); int castleMask = pos.getCastleMask();
int validCastle = 0; int validCastle = 0;
if (pos.getPiece(4) == Piece.WKING) { if (pos.getPiece(4) == Piece.WKING) {
@@ -213,7 +213,7 @@ public class TextIO {
} }
/** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */ /** Remove pseudo-legal EP square if it is not legal, ie would leave king in check. */
public static final void fixupEPSquare(Position pos) { public static void fixupEPSquare(Position pos) {
int epSquare = pos.getEpSquare(); int epSquare = pos.getEpSquare();
if (epSquare >= 0) { if (epSquare >= 0) {
ArrayList<Move> moves = MoveGen.instance.legalMoves(pos); ArrayList<Move> moves = MoveGen.instance.legalMoves(pos);
@@ -231,7 +231,7 @@ public class TextIO {
} }
} }
private static final void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError { private static void safeSetPiece(Position pos, int col, int row, int p) throws ChessParseError {
if (row < 0) throw new ChessParseError("R.string.err_too_many_rows"); if (row < 0) throw new ChessParseError("R.string.err_too_many_rows");
if (col > 7) throw new ChessParseError("R.string.err_too_many_columns"); if (col > 7) throw new ChessParseError("R.string.err_too_many_columns");
if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) { if ((p == Piece.WPAWN) || (p == Piece.BPAWN)) {
@@ -242,7 +242,7 @@ public class TextIO {
} }
/** Return a FEN string corresponding to a chess Position object. */ /** Return a FEN string corresponding to a chess Position object. */
public static final String toFEN(Position pos) { public static String toFEN(Position pos) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
// Piece placement // Piece placement
for (int r = 7; r >=0; r--) { for (int r = 7; r >=0; r--) {
@@ -334,11 +334,11 @@ public class TextIO {
* Otherwise, use short notation, eg Nf3. * Otherwise, use short notation, eg Nf3.
* @param localized If true, use localized piece names. * @param localized If true, use localized piece names.
*/ */
public static final String moveToString(Position pos, Move move, boolean longForm, public static String moveToString(Position pos, Move move, boolean longForm,
boolean localized) { boolean localized) {
return moveToString(pos, move, longForm, localized, null); return moveToString(pos, move, longForm, localized, null);
} }
public static final String moveToString(Position pos, Move move, boolean longForm, public static String moveToString(Position pos, Move move, boolean longForm,
boolean localized, List<Move> moves) { boolean localized, List<Move> moves) {
if ((move == null) || move.equals(new Move(0, 0, 0))) if ((move == null) || move.equals(new Move(0, 0, 0)))
return "--"; return "--";
@@ -438,7 +438,7 @@ public class TextIO {
return ret.toString(); return ret.toString();
} }
private static final 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())) { if ((p == (pos.whiteMove ? Piece.WPAWN : Piece.BPAWN)) && (move.to == pos.getEpSquare())) {
@@ -455,10 +455,9 @@ public class TextIO {
* Decide if move is valid in position pos. * Decide if move is valid in position pos.
* @param pos Position for which to test move. * @param pos Position for which to test move.
* @param move The move to check for validity. * @param move The move to check for validity.
* @param moves If non-null, list of valid moves in position pos.
* @return True if move is valid in position pos, false otherwise. * @return True if move is valid in position pos, false otherwise.
*/ */
public static final boolean isValid(Position pos, Move move) { public static boolean isValid(Position pos, Move move) {
if (move == null) if (move == null)
return false; return false;
ArrayList<Move> moves = new MoveGen().legalMoves(pos); ArrayList<Move> moves = new MoveGen().legalMoves(pos);
@@ -480,10 +479,10 @@ public class TextIO {
* The string may specify any combination of piece/source/target/promotion * The string may specify any combination of piece/source/target/promotion
* information as long as it matches exactly one valid move. * information as long as it matches exactly one valid move.
*/ */
public static final Move stringToMove(Position pos, String strMove) { public static Move stringToMove(Position pos, String strMove) {
return stringToMove(pos, strMove, null); return stringToMove(pos, strMove, null);
} }
public static final Move stringToMove(Position pos, String strMove, public static Move stringToMove(Position pos, String strMove,
ArrayList<Move> moves) { ArrayList<Move> moves) {
if (strMove.equals("--")) if (strMove.equals("--"))
return new Move(0, 0, 0); return new Move(0, 0, 0);
@@ -608,7 +607,7 @@ public class TextIO {
} }
/** Convert a move object to UCI string format. */ /** Convert a move object to UCI string format. */
public static final String moveToUCIString(Move m) { public static String moveToUCIString(Move m) {
String ret = squareToString(m.from); String ret = squareToString(m.from);
ret += squareToString(m.to); ret += squareToString(m.to);
switch (m.promoteTo) { switch (m.promoteTo) {
@@ -638,7 +637,7 @@ public class TextIO {
* Convert a string in UCI move format to a Move object. * Convert a string in UCI move format to a Move object.
* @return A move object, or null if move has invalid syntax * @return A move object, or null if move has invalid syntax
*/ */
public static final Move UCIstringToMove(String move) { public static Move UCIstringToMove(String move) {
Move m = null; Move m = null;
if ((move.length() < 4) || (move.length() > 5)) if ((move.length() < 4) || (move.length() > 5))
return m; return m;
@@ -687,7 +686,7 @@ public class TextIO {
* Convert a string, such as "e4" to a square number. * Convert a string, such as "e4" to a square number.
* @return The square number, or -1 if not a legal square. * @return The square number, or -1 if not a legal square.
*/ */
public static final int getSquare(String s) { public static int getSquare(String s) {
int x = s.charAt(0) - 'a'; int x = s.charAt(0) - 'a';
int y = s.charAt(1) - '1'; int y = s.charAt(1) - '1';
if ((x < 0) || (x > 7) || (y < 0) || (y > 7)) if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
@@ -698,7 +697,7 @@ public class TextIO {
/** /**
* Convert a square number to a string, such as "e4". * Convert a square number to a string, such as "e4".
*/ */
public static final String squareToString(int square) { public static String squareToString(int square) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int x = Position.getX(square); int x = Position.getX(square);
int y = Position.getY(square); int y = Position.getY(square);
@@ -710,7 +709,7 @@ public class TextIO {
/** /**
* Create an ascii representation of a position. * Create an ascii representation of a position.
*/ */
public static final String asciiBoard(Position pos) { public static String asciiBoard(Position pos) {
StringBuilder ret = new StringBuilder(400); StringBuilder ret = new StringBuilder(400);
String nl = String.format(Locale.US, "%n"); String nl = String.format(Locale.US, "%n");
ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl); ret.append(" +----+----+----+----+----+----+----+----+"); ret.append(nl);
@@ -739,7 +738,7 @@ public class TextIO {
} }
/** Convert a piece and a square to a string, such as Nf3. */ /** Convert a piece and a square to a string, such as Nf3. */
public final static String pieceAndSquareToString(int currentPieceType, int p, int sq) { public static String pieceAndSquareToString(int currentPieceType, int p, int sq) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
if (currentPieceType == PGNOptions.PT_FIGURINE) { if (currentPieceType == PGNOptions.PT_FIGURINE) {
ret.append(Piece.toUniCode(p)); ret.append(Piece.toUniCode(p));
@@ -765,7 +764,7 @@ public class TextIO {
return ""; return "";
} }
public final static String pieceToCharLocalized(int p) { public static String pieceToCharLocalized(int p) {
switch (p) { switch (p) {
case Piece.WQUEEN: case Piece.BQUEEN: return pieceNames[4]; case Piece.WQUEEN: case Piece.BQUEEN: return pieceNames[4];
case Piece.WROOK: case Piece.BROOK: return pieceNames[3]; case Piece.WROOK: case Piece.BROOK: return pieceNames[3];
@@ -789,7 +788,7 @@ public class TextIO {
} }
/** Add an = sign to a promotion move, as required by the PGN standard. */ /** Add an = sign to a promotion move, as required by the PGN standard. */
public final static String pgnPromotion(String str) { public static String pgnPromotion(String str) {
int idx = str.length() - 1; int idx = str.length() - 1;
while (idx > 0) { while (idx > 0) {
char c = str.charAt(idx); char c = str.charAt(idx);