001 package rules; 002 003 import java.util.*; 004 005 import core.*; 006 007 /** 008 * Knight piece. 009 */ 010 011 public class Knight extends Piece 012 { 013 014 protected String getName() 015 { 016 return "N"; 017 } 018 019 public Knight(Color color, int lastMove) 020 { 021 super(color, lastMove); 022 } 023 024 public String pieceString() 025 { 026 return "knight"; 027 } 028 029 /** 030 * @see Piece 031 */ 032 public Collection<Move> moveCandidates(GameState g, Position here) 033 { 034 Board board = g.getBoard(); 035 Collection<Move> answer = new ArrayList<Move>(); 036 int x = here.getX(); 037 int y = here.getY(); 038 int nx, ny; 039 for (int dx = -2; dx <= 2; dx++) 040 { 041 for (int dy = -2; dy <= 2; dy++) 042 { 043 if (Math.abs(dx * dy) != 2) 044 continue; 045 nx = x + dx; 046 ny = y + dy; 047 if (Position.isValid(nx, ny)) { 048 if (board.get(nx, ny).getColor() != getColor()) { 049 Position newPos = Position.get(nx, ny); 050 answer.add(new Move(here, newPos)); 051 } 052 } 053 } 054 } 055 return answer; 056 } 057 058 /** 059 * @returns whether any piece of this type and a color 060 * threatens a given position pos. 061 * @requires g, from, to != null 062 */ 063 public static boolean threatens(GameState g, Color c, Position pos) 064 { 065 Board board = g.getBoard(); 066 int x = pos.getX(), y = pos.getY(); 067 //Knight 068 for(int dx = -2; dx <= 2; dx++){ 069 if (dx == 0) 070 continue; 071 for(int k = -1; k <= 1; k += 2){ 072 int dy = k * (3 - Math.abs(dx)); 073 if (!Position.isValid(x+dx, y+dy)) 074 continue; 075 Piece p = board.get(x+dx, y+dy); 076 if (p.getColor() == c && 077 p instanceof Knight) 078 return true; 079 } 080 } 081 return false; 082 } 083 084 public int hashCode() { 085 return 2*4 + (color == Color.WHITE ? 0 : 1); 086 } 087 }