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