001 package rules;
002
003 import java.util.*;
004
005 import core.Color;
006 import core.Move;
007 import core.Piece;
008 import core.Position;
009
010
011 /**
012 * Pawn piece.
013 */
014 public class Pawn extends Piece
015 {
016
017 protected String getName()
018 {
019 return "P";
020 }
021
022 public String pieceString()
023 {
024 return "pawn";
025 }
026
027 public Pawn(Color color, int lastMove)
028 {
029 super(color, lastMove);
030 }
031
032 /**
033 * @see Piece
034 */
035 public Collection<Move> moveCandidates(GameState g, Position here)
036 {
037 Board board = g.getBoard();
038 Collection<Move> answer = new ArrayList<Move>();
039 int x = here.getX();
040 int y = here.getY();
041 int direction = getColor() == Color.WHITE ? 1 : -1;
042 int end = getColor() == Color.WHITE ? 7 : 0;
043 if (board.get(x, y+direction).getColor() == Color.NONE)
044 {
045 Position newPos = Position.get(x, y + direction);
046 answer.add(new Move(here, newPos));
047 if (y == 7 - end + direction && getLastMove() == 0) {
048 if (board.get(x, y+2*direction).getColor() == Color.NONE) {
049 newPos = Position.get(x, y + 2 * direction);
050 answer.add(new Move(here, newPos));
051 }
052 }
053 }
054 for (int dx = -1; dx <= 1; dx += 2)
055 {
056 if(!Position.isValid(x+dx, y+direction))
057 continue;
058 Piece p = board.get(x+dx, y+direction);
059 if (p.getColor() == getColor().otherColor()) {
060 answer.add(new Move(here, Position.get(x + dx, y + direction)));
061 }
062
063 // Check for en passant
064 if (y == end - 3 * direction) {
065 Piece otherPawn = board.get(x+dx, y);
066 if (otherPawn instanceof Pawn
067 && otherPawn.getColor() == getColor().otherColor()
068 && otherPawn.getLastMove() == g.getMoveNum()) {
069 Move m = new Move(here, Position.get(x + dx, y + direction));
070 answer.add(m);
071 }
072 }
073 }
074 return answer;
075 }
076
077 /**
078 * @see Piece
079 */
080 public static boolean threatens(GameState g, Color color, Position pos)
081 {
082 Board board = g.getBoard();
083 int x = pos.getX(), y = pos.getY();
084 //Pawn
085 int dy = (color == Color.WHITE ? -1 : 1);
086 for(int dx = -1; dx <= 1; dx += 2){
087 if (!Position.isValid(x+dx, y+dy))
088 continue;
089 Piece p = board.get(x+dx, y+dy);
090 if (p.getColor() == color &&
091 p instanceof Pawn)
092 return true;
093 }
094 return false;
095 }
096
097 public int hashCode() {
098 return 2*5 + (color == Color.WHITE ? 0 : 1);
099 }
100 }