id
stringlengths
36
36
text
stringlengths
1
1.25M
7ce37ef6-c184-492f-95ec-63a281dc9d23
public JSONException syntaxError(String message) { return new JSONException(message + this.toString()); }
601f145c-c2be-4a1b-a43d-1d64e8dfb9ef
@Override public String toString() { return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; }
f0495032-e8e0-4106-aa33-baf0a79af626
public static synchronized GameModeInventoriesDatabase getInstance() { return instance; }
7c0d8bed-09d0-48bb-be7e-60154434a7b5
public void setConnection(String path) throws Exception { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:" + path); }
e0582406-0644-48b3-8daf-6e0e0bc4e1f9
public Connection getConnection() { return connection; }
3b40b3c6-b085-4e39-942f-33a561ae26ad
@Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not allowed."); }
b2e6188e-ca46-4ec2-b454-8215a0e13425
@Override public void onDisable() { // TODO: Place any custom disable code here. }
808c8246-ad1f-4230-8bc4-12b7a35045e9
@Override public void onEnable() { saveDefaultConfig(); PluginManager pm = getServer().getPluginManager(); Plugin gmi = pm.getPlugin("GameModeInventories"); if (gmi == null) { System.err.println("[GMIDatabaseConverter] This plugin requires GameModeInventories!"); pm.disablePlugin(this); return; } String v = gmi.getDescription().getVersion(); Version gmiversion = new Version(v); Version notneededversion = new Version("2.0"); if (gmiversion.compareTo(notneededversion) >= 0) { System.err.println("[GMIDatabaseConverter] You do not need to run this with version " + v + " of GameModeInventories!"); pm.disablePlugin(this); return; } if (getConfig().getBoolean("conversion_done")) { System.err.println("[GMIDatabaseConverter] The GameModeInventories database has already been converted!"); pm.disablePlugin(this); return; } File old_file = new File(gmi.getDataFolder() + File.separator + "GMI.db"); if (!old_file.exists()) { System.err.println("[GMIDatabaseConverter] Could not find GameModeInventories database file!"); pm.disablePlugin(this); return; } File backup_file = new File(gmi.getDataFolder() + File.separator + "GMI_backup.db"); try { copyFile(old_file, backup_file); } catch (IOException io) { System.err.println("[GMIDatabaseConverter] Could backup GameModeInventories database file!"); pm.disablePlugin(this); return; } System.out.println("[GMIDatabaseConverter] The GameModeInventories database file was backed up successfully!"); try { String path = gmi.getDataFolder() + File.separator + "GMI.db"; service.setConnection(path); } catch (Exception e) { System.err.println("[GMIDatabaseConverter] Database connection error: " + e); } if (!convertInventories()) { System.err.println("[GMIDatabaseConverter] Inventory conversion failed!"); pm.disablePlugin(this); } else { getConfig().set("conversion_done", true); } }
4a9499bd-1838-4e2b-9918-83dc6c3bdb0f
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
d9ee6ed2-9068-40b9-8d04-8fe2e481b0b7
private boolean convertInventories() { System.out.println("[GMIDatabaseConverter] Beginning conversion..."); // get all the records try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String getQuery = "SELECT id, inventory, armour, enderchest FROM inventories"; ResultSet rsInv = statement.executeQuery(getQuery); int count = 0; while (rsInv.next()) { // set their inventory to the saved one String base64 = rsInv.getString("inventory"); Inventory i = fromBase64(base64); ItemStack[] iis = i.getContents(); String i_string = GameModeInventoriesSerialization.toString(iis); String savedarmour = rsInv.getString("armour"); Inventory a = fromBase64(savedarmour); ItemStack[] ais = a.getContents(); String a_string = GameModeInventoriesSerialization.toString(ais); String savedender = rsInv.getString("enderchest"); if (savedender == null || savedender.equals("[Null]") || savedender.equals("") || savedender.isEmpty()) { // empty inventory savedender = "[\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\",\"null\"]"; } Inventory e = fromBase64(savedender); ItemStack[] eis = e.getContents(); String e_string = GameModeInventoriesSerialization.toString(eis); // update String setQuery = "UPDATE inventories SET inventory = ?, armour = ?, enderchest = ? WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(setQuery); ps.setString(1, i_string); ps.setString(2, a_string); ps.setString(3, e_string); ps.setInt(4, rsInv.getInt("id")); ps.executeUpdate(); count++; } System.out.println("[GMIDatabaseConverter] Conversion complete - " + count + " records updated successfully."); rsInv.close(); statement.close(); } catch (SQLException e) { System.err.println("Could not save inventory on gamemode change, " + e); return false; } return true; }
62604f85-2f18-4df7-b40f-0e35f965a5df
public static Inventory fromBase64(String data) { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); NBTTagList itemList = (NBTTagList) NBTBase.a(new DataInputStream(inputStream)); Inventory inventory = new CraftInventoryCustom(null, itemList.size()); for (int i = 0; i < itemList.size(); i++) { NBTTagCompound inputObject = (NBTTagCompound) itemList.get(i); if (!inputObject.isEmpty()) { inventory.setItem(i, CraftItemStack.asCraftMirror(net.minecraft.server.v1_6_R3.ItemStack.createStack(inputObject))); } } return inventory; }
662a31f5-5d9b-45ae-ba5c-2a5577a4d760
public Version(String version) { if (version == null) { throw new IllegalArgumentException("Version can not be null"); } if (!version.matches("[0-9]+(\\.[0-9]+)*")) { throw new IllegalArgumentException("Invalid version format"); } this.version = version; }
8c9a3cb1-5109-4004-9470-4675d7cdd8ca
public String get() { return this.version; }
295245c2-a220-4d6d-b921-e74aff06d524
@Override public int compareTo(Version that) { if (that == null) { return 1; } String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); int length = Math.max(thisParts.length, thatParts.length); for (int i = 0; i < length; i++) { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; if (thisPart < thatPart) { return -1; } if (thisPart > thatPart) { return 1; } } return 0; }
e04cca4c-8e21-4497-8cb2-13d9eb90e101
@Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (this.getClass() != that.getClass()) { return false; } return this.compareTo((Version) that) == 0; }
0f97676c-0387-409d-bad7-77f5eebdac0b
@Override public int hashCode() { int hash = 3; return hash; }
16f4a967-9635-4afe-8513-07baf3349487
public static String toString(ItemStack[] inv) { List<String> result = new ArrayList<String>(); List<ConfigurationSerializable> items = new ArrayList<ConfigurationSerializable>(); items.addAll(Arrays.asList(inv)); for (ConfigurationSerializable cs : items) { if (cs == null) { result.add("null"); } else { result.add(new JSONObject(serialize(cs)).toString()); } } JSONArray json_array = new JSONArray(result); return json_array.toString(); }
dcf3daf0-8f44-49ba-a611-96ef1d334515
public static Map<String, Object> serialize(ConfigurationSerializable cs) { Map<String, Object> serialized = recreateMap(cs.serialize()); for (Entry<String, Object> entry : serialized.entrySet()) { if (entry.getValue() instanceof ConfigurationSerializable) { entry.setValue(serialize((ConfigurationSerializable) entry.getValue())); } } serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass())); return serialized; }
e3c6b1ed-133e-42e7-86b1-936e5102aab4
public static Map<String, Object> recreateMap(Map<String, Object> original) { Map<String, Object> map = new HashMap<String, Object>(); for (Entry<String, Object> entry : original.entrySet()) { map.put(entry.getKey(), entry.getValue()); } return map; }
b5174b05-31d3-4168-aec1-d6796b6814fb
public static void main(String[] args) { System.out.println("Trial Round - Google Hash Code 2014"); }
217245dc-f190-4fda-9800-1d7a71c81ff9
public static void main(String[] args) { // Read File BufferedReader br = null; BufferedWriter bw = null; try { String sCurrentLine; Date date = new Date(); File output = new File("D:\\MyWorks\\GoogleHashCode\\streetview" + date.getTime() + ".txt"); // if file doesnt exists, then create it if (!output.exists()) { output.createNewFile(); } bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(output), "US-ASCII")); br = new BufferedReader(new FileReader( "D:\\MyWorks\\GoogleHashCode\\paris_54000.txt")); // Read the first Line String firstLine = br.readLine(); // Get junctions number Integer junctionsNumber = 0; // Get streets number Integer streetNumber = 0; // Get time to live number, else we will be killed :) Integer ttl = 0; // Get cars number Integer carsNumber = 0; // Get cars number Integer launchJunction = 0; StringTokenizer st = new StringTokenizer(firstLine); while (st.hasMoreElements()) { junctionsNumber = Integer.parseInt(st.nextElement().toString()); streetNumber = Integer.parseInt(st.nextElement().toString()); ttl = Integer.parseInt(st.nextElement().toString()); carsNumber = Integer.parseInt(st.nextElement().toString()); launchJunction = Integer.parseInt(st.nextElement().toString()); } // Fill Junctions List List<Junction> junctionsList = new ArrayList<Junction>(); junctionsList.clear(); // define a bac junction object Junction bacJunction = new Junction(); Double latitude = 0d; Double longitute = 0d; int currentReadedJunction = 0; while (currentReadedJunction < junctionsNumber && (sCurrentLine = br.readLine()) != null) { // Get informations aboutt the current junction st = new StringTokenizer(sCurrentLine); while (st.hasMoreElements()) { latitude = Double.parseDouble(st.nextElement().toString()); bacJunction.setLatitude(latitude); longitute = Double.parseDouble(st.nextElement().toString()); bacJunction.setLongitude(longitute); // Add the junction to the List junctionsList.add(bacJunction); } currentReadedJunction = currentReadedJunction + 1; } // Fill Streets List List<Street> streetsList = new ArrayList<Street>(); // define an bac street object Integer startJunction; Integer endJunction; Integer beDirectional; Integer cost; Integer distance; int currentReadedStreet = 0; while ((sCurrentLine = br.readLine()) != null) { // Get informations aboutt the current junction st = new StringTokenizer(sCurrentLine); while (st.hasMoreElements()) { Street street = new Street(); street.setStreetIndex(currentReadedStreet); startJunction = Integer.parseInt(st.nextElement() .toString()); street.setStartJunction(startJunction); endJunction = Integer.parseInt(st.nextElement().toString()); street.setEndJunction(endJunction); beDirectional = Integer.parseInt(st.nextElement() .toString()); street.setBeDirectional(beDirectional); cost = Integer.parseInt(st.nextElement().toString()); street.setCost(cost); distance = Integer.parseInt(st.nextElement().toString()); street.setDistance(distance); // Add the street to the List streetsList.add(street); } currentReadedStreet = currentReadedStreet + 1; } // Write the number of the cars bw.write(carsNumber + "\n"); // Get start junction CarTrajectory carTrajectory = new CarTrajectory(); Integer currentDistance = 0; Integer accumulatedCost = 0; // get the List of possible street for the launch junction // List<Street> junctionStreets = getJunctionStreets(launchJunction, // streetsList); // list of street already used List<Integer> reservedStreet = new ArrayList<Integer>(); // Iterate on car number for (int i = 0; i < carsNumber; i++) { System.out.println("Enter Cars Process number: " + i); List<Street> junctionStreets = getJunctionStreets( launchJunction, streetsList); System.out.println("junctionStreets initial size : " + junctionStreets.size()); // System.out.println("Initial junction steet size: "+ // junctionStreets); // Initialize carTrajectory.getTrajectory().add(launchJunction); // get the next possible junction while (junctionStreets.size() > 0 && accumulatedCost < ttl) { Random r = new Random(); Street nextStreet = junctionStreets.get(r .nextInt(junctionStreets.size())); if (accumulatedCost + nextStreet.getCost() < ttl) { accumulatedCost = accumulatedCost + nextStreet.getCost(); // Add the next junction to the trajectory carTrajectory.getTrajectory().add( nextStreet.getEndJunction()); reservedStreet.add(nextStreet.getStreetIndex()); // prepare the next possible street junctionStreets.clear(); junctionStreets = getJunctionStreets( nextStreet.getEndJunction(), streetsList); } else { break; } } // write to number of trajectory for a car bw.write(carTrajectory.getTrajectory().size() + "\n"); // iterate the trajectory list to write in the file for (Integer node : carTrajectory.getTrajectory()) { bw.write(node.intValue() + "\n"); } carTrajectory.getTrajectory().clear(); accumulatedCost = 0; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("End of the processing"); }
4427ed72-ca8d-466a-a280-1d2aabb632bc
private static List<Street> getJunctionStreets(Integer launchJunction, List<Street> streetsList) { List<Street> startJunctionStreets = new ArrayList<Street>(); Iterator<Street> iterator = streetsList.iterator(); while (iterator.hasNext()) { Street street = (Street) iterator.next(); if (street.getStartJunction().intValue() == launchJunction .intValue() /* * || * (street.getEndJunction().equals(launchJunction * ) && street.getBeDirectional().equals(2)) */) { startJunctionStreets.add(street); } } return startJunctionStreets; }
7bc20192-b5b1-4fe8-ba53-414c86f20079
public Integer getStreetIndex() { return streetIndex; }
e5c1bc5a-87a7-4191-b83b-7994cee3d58d
public void setStreetIndex(Integer streetIndex) { this.streetIndex = streetIndex; }
0c3e2cd3-7615-4cdf-b80b-31ea20d8fe8b
public Integer getStartJunction() { return startJunction; }
2ef0ecd3-4814-44bb-9092-d25bbbc91b0b
public void setStartJunction(Integer startJunction) { this.startJunction = startJunction; }
46519273-8e9a-4f64-852a-749b046810f9
public Integer getEndJunction() { return endJunction; }
ffd44ff4-44f4-43f9-a56a-82ab043f6669
public void setEndJunction(Integer endJunction) { this.endJunction = endJunction; }
80717e97-e8fe-4827-9d51-ac19cf1a04ab
public Integer getBeDirectional() { return beDirectional; }
775e7709-58b8-43ee-92ee-d934dc69dc25
public void setBeDirectional(Integer beDirectional) { this.beDirectional = beDirectional; }
b55ba156-3ed0-48ee-9ca4-6eabf8b8e6db
public Integer getCost() { return cost; }
11139800-7648-40be-98ee-d699da666b3a
public void setCost(Integer cost) { this.cost = cost; }
7540378f-eed3-4c85-a6f6-6e259571c357
public Integer getDistance() { return distance; }
0065a03d-5f95-4e7b-b7d0-5949f423d4bb
public void setDistance(Integer distance) { this.distance = distance; }
db785a4b-5d3c-44f0-9f04-13942e710fb5
public Double getLatitude() { return latitude; }
fb95b828-ff0c-41c1-a22a-f7cd96ead903
public void setLatitude(Double latitude) { this.latitude = latitude; }
adb749ca-a3cf-4547-b47c-ff6d04abac2f
public Double getLongitude() { return longitude; }
25db07d1-8ed4-4c82-9d76-493c3cfd844b
public void setLongitude(Double longitude) { this.longitude = longitude; }
0deac246-b051-4b18-a937-427996391923
public List<Integer> getTrajectory() { return trajectory; }
2856290f-28d0-4bab-8a9d-58fa76b6ee41
public void setTrajectory(List<Integer> trajectory) { this.trajectory = trajectory; }
30fe8866-53aa-421b-bd94-fdae2d3265cd
public static void main(String[] args) { // TODO Auto-generated method stub try { GUIChessBoard b = new GUIChessBoard(); // TextChessBoard b = new TextChessBoard(); // b.startGame(); } catch(ChessException e) { System.out.println(e.getMessage()); } }
c188cc8f-c003-411a-8794-ff5862f2964e
public Queen(ChessColor c) throws ChessException { super(c); int r = (c == ChessColor.COLOR_BLACK?0:7); setPosition(new ChessPosition(r, 3)); }
7d9bb1a0-6e11-419f-b25c-cffc6e08e473
public Queen(ChessColor c, ChessPosition p) throws ChessException { super(c); setPosition(p); }
0af4406f-b233-4490-ba34-96ac5da9510d
private boolean addMove(ChessBoard b, ChessMoves moves, int i, int j) throws ChessException { boolean ret = false; ChessPosition tp = new ChessPosition(i,j); ChessPiece p = b.pieceAt(tp); if (p == null) { moves.addMove(tp); ret = true; } else if (p.getColor() != this.getColor()) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); return ret; }
ef8cf9e9-f007-4a15-a45d-b8e9c0637439
public ChessMoves nextMoves(ChessBoard b) { int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); ChessMoves moves = new ChessMoves(); try { for (int k = i; k < 8; k++) { if (k != i) { if (!addMove(b, moves, k, j)) break; } } for (int k = i; k >= 0; k--) { if (k != i) { if (!addMove(b, moves, k, j)) break; } } for (int k = j; k < 8; k++) { if (k != j) { if (!addMove(b, moves, i, k)) break; } } for (int k = j; k >= 0; k--) { if (k != j) { if (!addMove(b, moves, i, k)) break; } } for (i = 1; i > -2; i -= 2) { for (j = 1; j > -2; j -= 2) { boolean good_move; int tr = this.getPosition().getRow(); int tc = this.getPosition().getCol(); do { tr = tr + i; tc = tc + j; if ((tr >= 0) && (tr <= 7) && (tc >= 0) && (tc <= 7)) { // If a piece exists in the current position // and it is of the same color, then it cannot move there // otherwise, you can move to capture, but no more moves beyond that // along that direction ChessPosition tp = new ChessPosition(tr, tc); ChessPiece p = b.pieceAt(tp); if (p == null) { moves.addMove(new ChessPosition(tr, tc)); good_move = true; } else if (p.getColor() != this.getColor()) { moves.addMove(new ChessPosition(tr, tc), ChessMoves.MoveType.CAPTURE); good_move = false; } else good_move = false; } else good_move = false; } while (good_move); } } } catch (Exception e) { moves = null; } return moves; }
be16df75-8093-4760-b423-924da56c8f56
@Override public ChessMoves.MoveType isValidMove(ChessBoard b, ChessPosition p) { if ((b == null) || (p == null)) return ChessMoves.MoveType.INVALID; if ((p.getCol() < 0) || (p.getCol() > 7) || (p.getRow() < 0) || (p.getRow() > 7)) return ChessMoves.MoveType.INVALID; int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); if ((i == p.getRow()) && (j == p.getCol())) return ChessMoves.MoveType.INVALID; int row_diff = i - p.getRow(); int col_diff = j - p.getCol(); // If it is not on the same row, or the same col or the same diagonal, its not valid if ((Math.abs(row_diff) != Math.abs(col_diff)) && ((Math.abs(row_diff) > 0) && (Math.abs(col_diff) > 0))) return ChessMoves.MoveType.INVALID; ChessMoves.MoveType can_move = ChessMoves.MoveType.NORMAL; // Figure out if you are going forward or backward int row_increment = (i < p.getRow())?1:-1; int col_increment = (j < p.getCol())?1:-1; try { if (row_diff == 0) { // Moving horizontally for (j += col_increment; j != p.getCol(); j += col_increment) { ChessPiece piece = b.pieceAt(new ChessPosition(i, j)); if (piece != null) { can_move = ChessMoves.MoveType.INVALID; break; } } } else if (col_diff == 0) { // Moving vertically for (i += row_increment; i != p.getRow(); i += row_increment) { ChessPiece piece = b.pieceAt(new ChessPosition(i, j)); if (piece != null) { can_move = ChessMoves.MoveType.INVALID; break; } } } else { // Moving diagonally for (i += row_increment, j += col_increment; (i != p.getRow()) && (j != p.getCol()); i += row_increment, j += col_increment) { ChessPiece piece = b.pieceAt(new ChessPosition(i, j)); if (piece != null) { can_move = ChessMoves.MoveType.INVALID; break; } } } if (can_move != ChessMoves.MoveType.INVALID) { // One last check to make sure that there is nothing in the landing square ChessPiece piece = b.pieceAt(new ChessPosition(p.getRow(), p.getCol())); if (piece != null) { if (piece.getColor() != this.getColor()) can_move = ChessMoves.MoveType.CAPTURE; else can_move = ChessMoves.MoveType.INVALID; } } } catch (ChessException e) { can_move = ChessMoves.MoveType.INVALID; } return can_move; }
daf5c39e-b39f-4afa-bc75-069ee261771d
@Override public String getShortDescription() { if (this.clr == ChessColor.COLOR_BLACK) return new String("q"); else return new String("Q"); }
ad592555-a20c-42ad-b095-1b81ffd340f5
@Override public String getImage() { if (this.clr == ChessColor.COLOR_BLACK) return new String("\u265B"); else return new String("\u2655"); }
d6853074-fca2-49d7-b186-92d5286dfc5c
public ChessException() { super(DEF_ERROR); }
d5e52bd9-fadc-4ef0-876b-9a95797fc98e
public ChessException(String arg0) { super(arg0); // TODO Auto-generated constructor stub }
dabde295-ce8a-4158-b638-a9f08df26d72
public ChessException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub }
77397ad8-efc3-43eb-8db0-f5f85b688b70
public ChessException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub }
fe0c680b-d770-4329-b659-4f8f47fec023
public Pawn(ChessColor c, int num) throws ChessException { super(c); int r = (c == ChessColor.COLOR_BLACK?1:6); if ((num < 1) || (num > 8)) throw new ChessException("Only eight Pawns are allowed for each color"); setPosition(new ChessPosition(r, num - 1)); }
b6d1aa08-8e12-4930-bb3d-5f8dc5b33db5
public Pawn(ChessColor c, ChessPosition p) throws ChessException { super(c); setPosition(p); }
e4fb090c-0a94-43cc-bd95-c9c3db091d57
public ChessMoves nextMoves(ChessBoard b) { int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); ChessMoves moves = new ChessMoves(); // Not dealing with promotion at this time try { if ((this.getColor() == ChessColor.COLOR_BLACK) && ((i + 1) < 8)) { ChessPosition tp = new ChessPosition(i+1, j); if (b.pieceAt(tp) == null) { moves.addMove(tp); if (i == 1) { tp = new ChessPosition(i+2, j); if (b.pieceAt(tp) == null) moves.addMove(tp); } } // Check for kill moves if ((j+1) < 8) { tp = new ChessPosition(i+1, j+1); ChessPiece p = b.pieceAt(tp); if ((p != null) && (p.getColor() != this.getColor())) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); } if ((j-1) >= 0) { tp = new ChessPosition(i+1, j-1); ChessPiece p = b.pieceAt(tp); if ((p != null) && (p.getColor() != this.getColor())) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); } } else if ((i - 1) >= 0) { ChessPosition tp = new ChessPosition(i-1, j); if (b.pieceAt(tp) == null) { moves.addMove(tp); if (i == 6) { tp = new ChessPosition(i-2, j); if (b.pieceAt(tp) == null) moves.addMove(tp); } } // Check for kill moves if ((j+1) < 8) { tp = new ChessPosition(i-1, j+1); ChessPiece p = b.pieceAt(tp); if ((p != null) && (p.getColor() != this.getColor())) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); } if ((j-1) >= 0) { tp = new ChessPosition(i-1, j-1); ChessPiece p = b.pieceAt(tp); if ((p != null) && (p.getColor() != this.getColor())) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); } } } catch (Exception e) { moves = null; } return moves; }
87f99831-a578-42df-ac6a-22682bb8244d
@Override public ChessMoves.MoveType isValidMove(ChessBoard b, ChessPosition p) { if ((p.getCol() < 0) || (p.getCol() > 7) || (p.getRow() < 0) || (p.getRow() > 7)) return ChessMoves.MoveType.INVALID; ChessPiece cp = b.pieceAt(p); if (this.getColor() == ChessColor.COLOR_BLACK) { if ((p.getCol() == this.getPosition().getCol()) && ((p.getRow() == this.getPosition().getRow() + 1) || ((this.getPosition().getRow() == 1) && (p.getRow() == this.getPosition().getRow()+2))) && (cp == null)) return ChessMoves.MoveType.NORMAL; else if ((cp != null) && (cp.getColor() != this.getColor())) { if (((p.getCol() == this.getPosition().getCol() + 1) || (p.getCol() == this.getPosition().getCol() - 1)) && (p.getRow() == this.getPosition().getRow() + 1)) return ChessMoves.MoveType.CAPTURE; else return ChessMoves.MoveType.INVALID; } else return ChessMoves.MoveType.INVALID; } else { if ((p.getCol() == this.getPosition().getCol()) && ((p.getRow() == this.getPosition().getRow() - 1) || ((this.getPosition().getRow() == 6) && (p.getRow() == this.getPosition().getRow()-2))) && (cp == null)) return ChessMoves.MoveType.NORMAL; else if ((cp != null) && (cp.getColor() != this.getColor())) { if (((p.getCol() == this.getPosition().getCol() + 1) || (p.getCol() == this.getPosition().getCol() - 1)) && (p.getRow() == this.getPosition().getRow() - 1)) return ChessMoves.MoveType.CAPTURE; else return ChessMoves.MoveType.INVALID; } else return ChessMoves.MoveType.INVALID; } }
eacb26ab-ca2f-4c97-9fd4-ba5c9f57d7cb
@Override public String getShortDescription() { if (this.clr == ChessColor.COLOR_BLACK) return new String("p"); else return new String("P"); }
a7d79b66-429b-4f6e-a39a-d4ac84e90eb3
@Override public String getImage() { if (this.clr == ChessColor.COLOR_BLACK) return new String("\u265F"); else return new String("\u2659"); }
87f5f8cb-0bab-4ae3-9440-82cb2eebe60c
private void setPosition(char cb_col, char cb_row) throws ChessException { char tc = Character.toUpperCase(cb_col); if ((tc < 'A') || (tc > 'H')) throw new ChessException("Invalid board column position given: " + cb_col); col = tc - 'A'; if (Character.isDigit(cb_row)) { row = Character.getNumericValue(cb_row); if ((row < 1) || (row > 8)) throw new ChessException("Invalid board row position given: " + cb_row); row = 8 - row; } else { throw new ChessException("Board row position not digit: " + cb_row); } }
bd4c4161-4969-471d-bc71-05e6cd027b35
public ChessPosition(char cb_col, char cb_row) throws ChessException { attack_pieces = new ArrayList<ChessPiece>(); setPosition(cb_col, cb_row); }
5ca0edc0-a733-43aa-9a93-4dbc1ee7eddf
public ChessPosition(int r, int c) throws ChessException { if ((c < 0) || (c>7) || (r < 0) || (r > 7)) throw new ChessException("Invalid board position specified"); attack_pieces = new ArrayList<ChessPiece>(); row = r; col = c; }
3ad39019-4fe9-4fc1-95d4-125690d5203e
public ChessPosition(String pos) throws ChessException { if (pos == null) throw new ChessException("No chess position given"); if (pos.length() != 2) throw new ChessException("Chess position is not valid"); attack_pieces = new ArrayList<ChessPiece>(); setPosition(pos.charAt(0), pos.charAt(1)); }
47e75ef3-abfa-40d9-8613-b7a3395181f9
public char getBoardRow() { return (char)('8' - row); }
1024522e-9651-431b-be8f-1eeabaecce13
public char getBoardCol() { return (char)('A' + col); }
9cdf0759-1321-4c9c-8a28-f9a6b4739234
public int getRow() { return row; }
5eab189e-aa54-43c5-a56d-a7b29a8ab68f
public int getCol() { return col; }
ee94756d-5c49-418c-90f4-e127c0f55080
public String getDescription() { return String.format("%c%c", getBoardCol(), getBoardRow()); }
21ed2b93-3902-43b3-9df2-a7673ff6c109
public void addAttack(ChessPiece p) { if (p != null) attack_pieces.add(p); }
0f067025-93ee-43c3-9dd3-62b415ed0a3d
public void removeAttack(ChessPiece p) { if (p == null) return; attack_pieces.remove(p); }
bc089a9b-38e2-4bf5-b8fc-8471eb5215c5
public ChessPiece[] underAttack() { return (ChessPiece [])attack_pieces.toArray(); }
1f0fe010-828b-4d2c-b0dc-a214ccc5483b
public ChessBoard() throws ChessException { board = new ChessPiece[8][]; for (int i = 0; i < 8; i++) { board[i] = new ChessPiece[8]; for (int j = 0; j < 8; j++) board[i][j] = null; } // Create all the pieces all_pieces = new ChessPiece[32]; ChessColor c = ChessColor.COLOR_BLACK; int j = 0; for (int i = 0; i < 2; i++) { all_pieces[j++] = new King(c); all_pieces[j++] = new Queen(c); all_pieces[j++] = new Bishop(c, 1); all_pieces[j++] = new Bishop(c, 2); all_pieces[j++] = new Knight(c, 1); all_pieces[j++] = new Knight(c, 2); all_pieces[j++] = new Rook(c, 1); all_pieces[j++] = new Rook(c, 2); for (int k = 1; k < 9; k++) all_pieces[j++] = new Pawn(c, k); c = ChessColor.COLOR_WHITE; } for (int i = 0; i < 32; i++) board[all_pieces[i].getPosition().getRow()][all_pieces[i].getPosition().getCol()] = all_pieces[i]; }
0d72bb29-ae11-43ef-bbcf-191f25fb638c
public void makeMove(ChessPosition from, ChessPosition to) throws ChessException { if ((from == null) || (to == null)) throw new ChessException("Invalid position to move from or move to"); ChessPiece p = board[from.getRow()][from.getCol()]; if (p == null) throw new ChessException("No piece to move at origin"); ChessPiece t = board[to.getRow()][to.getCol()]; if (t != null) t.capture(); p.makeMove(this, to); // If move was made, switch its position on the board board[from.getRow()][from.getCol()] = null; board[to.getRow()][to.getCol()] = p; }
b4bc6a3c-1fc2-44cf-a258-bc77f003d78a
public ChessPiece pieceAt(ChessPosition pos) { return board[pos.getRow()][pos.getCol()]; }
3c99557e-687a-474b-9108-bf1ab43a9a2c
public GUIChessBoard() throws ChessException { super(); turn = ChessColor.COLOR_WHITE; from = null; board_ui = null; board_ui = new JFrame("Chess Board"); board_ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); board_ui.setPreferredSize(new Dimension(400,400)); GridLayout gl = new GridLayout(9,9); Container pnl = board_ui.getContentPane(); pnl.setLayout(gl); Font f = new Font(null, Font.BOLD|Font.ITALIC, 16); Font f2 = new Font(null, Font.BOLD, 26); Color clr = new Color(255,0,0); Color clr2 = new Color(0, 0, 255); // Add the first item on the label row pnl.setBackground(Color.WHITE); JLabel jl = new JLabel(); jl.setText(" "); pnl.add(jl); for (int i = 0; i < 8; i++) { jl = new JLabel(); jl.setFont(f); jl.setOpaque(true); jl.setText(Character.toString((char)('A'+i))); jl.setHorizontalAlignment(JLabel.CENTER); jl.setVerticalAlignment(JLabel.CENTER); jl.setForeground(clr); pnl.add(jl); } for (int i = 0; i < 8; i++) { // The Row Label jl = new JLabel(); jl.setFont(f); jl.setHorizontalAlignment(JLabel.CENTER); jl.setVerticalAlignment(JLabel.CENTER); jl.setText(Integer.toString(8-i)); jl.setForeground(clr); pnl.add(jl); for (int j = 0; j < 8; j++) { jl = new JLabel(); jl.setBorder(BorderFactory.createLineBorder(Color.black)); jl.setOpaque(true); jl.setHorizontalAlignment(JLabel.CENTER); jl.setVerticalAlignment(JLabel.CENTER); jl.setFont(f2); jl.setForeground(clr2); if ((i % 2) == 1) { if ((j%2) == 1) jl.setBackground(Color.WHITE); else jl.setBackground(Color.LIGHT_GRAY); } else { if ((j%2) == 0) jl.setBackground(Color.WHITE); else jl.setBackground(Color.LIGHT_GRAY); } if (board[i][j] != null) jl.setText(board[i][j].getImage()); jl.addMouseListener(this); pnl.add(jl); } } board_ui.pack(); board_ui.setVisible(true); }
d70d9bf4-ee03-4bc8-9ffd-586d01f39528
public void makeMove(ChessPosition from, ChessPosition to) throws ChessException { super.makeMove(from, to); int idx = ((from.getRow()+1)*9)+(from.getCol()+1); JLabel jl = (JLabel)board_ui.getContentPane().getComponent(idx); if (jl == null) return; jl.setText(" "); if (to == null) return; idx = ((to.getRow()+1)*9)+(to.getCol()+1); jl = (JLabel)board_ui.getContentPane().getComponent(idx); if (jl == null) return; jl.setText(board[to.getRow()][to.getCol()].getImage()); board_ui.repaint(); }
fc1799b0-5a2e-481f-93d7-5b16949cf33a
public ChessColor getTurn() { return turn; }
9d57e844-0d04-44de-abec-a86b9bf9cdde
private ChessPosition getChessPositionFromClick(MouseEvent e) { ChessPosition pos = null; JLabel jl = (JLabel)e.getSource(); if (jl != null) { Component jc[] = board_ui.getContentPane().getComponents(); for (int i = 0; i < jc.length; i++) { if (jc[i] == jl) { try { pos = new ChessPosition((i/9)-1, (i%9)-1); } catch (ChessException e1) { // TODO Auto-generated catch block pos = null; } break; } } } return pos; }
b2671375-748c-4675-a942-a94966df2ca3
private void removeMoveHighlights() { if (moves_from == null) return; // Remove all the border highlights try { for (int k = 0; k < moves_from.getCount(); k++) { ChessPosition new_pos = moves_from.getMove(k); int idx = ((new_pos.getRow()+1)*9)+(new_pos.getCol()+1); JLabel jl = (JLabel)board_ui.getContentPane().getComponent(idx); if (jl != null) { int i = new_pos.getRow(); int j = new_pos.getCol(); //jl.setBorder(BorderFactory.createLineBorder(Color.BLACK)); if ((i % 2) == 1) { if ((j%2) == 1) jl.setBackground(Color.WHITE); else jl.setBackground(Color.LIGHT_GRAY); } else { if ((j%2) == 0) jl.setBackground(Color.WHITE); else jl.setBackground(Color.LIGHT_GRAY); } } } } catch (ChessException ce) { System.out.println(ce.getMessage()); } }
3318fcbf-76b2-496d-a1e5-51b56990e864
private void setPieceToMove(ChessPiece p) { if ((p == null) || (p.getColor() != turn)) return; // if there was a previous set of moves, // reset the UI from it this.removeMoveHighlights(); moves_from = p.nextMoves(this); if (moves_from == null) { System.out.printf("No valid moves for piece at [%c,%c]\n", p.getPosition().getBoardCol(), p.getPosition().getBoardRow()); return; } from = p.getPosition(); try { for (int k = 0; k < moves_from.getCount(); k++) { ChessPosition new_pos = moves_from.getMove(k); ChessMoves.MoveType mt = moves_from.moveType(k); int idx = ((new_pos.getRow()+1)*9)+(new_pos.getCol()+1); JLabel jl = (JLabel)board_ui.getContentPane().getComponent(idx); if (jl != null) { if (mt == ChessMoves.MoveType.NORMAL) jl.setBackground(Color.GREEN); else if (mt == ChessMoves.MoveType.CAPTURE) jl.setBackground(Color.RED); } } } catch (ChessException ce) { System.out.println(ce.getMessage()); } }
f4ec1349-c5f7-4ef8-9436-fa3c4132a2d1
@Override public void mouseClicked(MouseEvent e) { // If this is the first time a position is selected // and there is a legitimate piece, then mark it if (from == null) { ChessPosition pos = getChessPositionFromClick(e); ChessPiece p = pieceAt(pos); if (p == null) return; setPieceToMove(p); } else { try { ChessPiece moving_piece = pieceAt(from); if (moving_piece == null) { from = null; return; } ChessPosition pos = getChessPositionFromClick(e); if (pos == null) { from = null; return; } // If there is a piece at the target position // and if that piece is the same color, then // the player has changed the mind about the // piece they want to move, so reset the piece ChessPiece p = this.pieceAt(pos); if ((p != null) && (p.getColor() == moving_piece.getColor())) { setPieceToMove(p); return; } makeMove(from, pos); // Remove all the border highlights this.removeMoveHighlights(); // reset where you came from from = null; // Switch the sides to make the move turn = (turn == ChessColor.COLOR_BLACK)?ChessColor.COLOR_WHITE:ChessColor.COLOR_BLACK; } catch (ChessException ce) { from = null; } } }
65aa92c7-9898-4f90-8618-08a030ba6a72
@Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub }
8cbe3f65-7afb-4c54-84d0-136985af7737
@Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub }
1019ce9c-ec99-4d50-a8b3-982163c1f9f2
@Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub }
ebcf0089-ef67-4b2b-8c4c-200bec5209c0
@Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub }
784ff53e-d30c-443a-978c-e22916b95377
public Rook(ChessColor c, int num) throws ChessException { super(c); int r = (c == ChessColor.COLOR_BLACK?0:7); if ((num != 1) && (num != 2)) throw new ChessException("Only two Rooks are allowed for each color"); if (num == 1) setPosition(new ChessPosition(r, 0)); else setPosition(new ChessPosition(r, 7)); }
410ff213-6238-484f-8686-89eb3beaf57f
public Rook(ChessColor c, ChessPosition p) throws ChessException { super(c); setPosition(p); }
24996d90-ddb0-45bc-9dee-0d1996fc8342
private boolean addMove(ChessBoard b, ChessMoves moves, int i, int j) throws ChessException { boolean ret = false; ChessPosition tp = new ChessPosition(i,j); ChessPiece p = b.pieceAt(tp); if (p == null) { moves.addMove(tp); ret = true; } else if (p.getColor() != this.getColor()) moves.addMove(tp, ChessMoves.MoveType.CAPTURE); return ret; }
78b8e0a6-8899-4391-add6-33589954d970
public ChessMoves nextMoves(ChessBoard b) { int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); ChessMoves moves = new ChessMoves(); try { for (int k = i; k < 8; k++) { if (k != i) { if (!addMove(b, moves, k, j)) break; } } for (int k = i; k >= 0; k--) { if (k != i) { if (!addMove(b, moves, k, j)) break; } } for (int k = j; k < 8; k++) { if (k != j) { if (!addMove(b, moves, i, k)) break; } } for (int k = j; k >= 0; k--) { if (k != j) { if (!addMove(b, moves, i, k)) break; } } } catch (Exception e) { moves = null; } return moves; }
e20cc5b4-8eef-40e2-b12c-bd146eb6a3ef
@Override public ChessMoves.MoveType isValidMove(ChessBoard b, ChessPosition p) { if ((p == null) || (b == null)) return ChessMoves.MoveType.INVALID; if ((p.getCol() < 0) || (p.getCol() > 7) || (p.getRow() < 0) || (p.getRow() > 7)) return ChessMoves.MoveType.INVALID; int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); int row_diff = i - p.getRow(); int col_diff = j - p.getCol(); if (((row_diff == 0) && (col_diff == 0)) || ((row_diff != 0) && (col_diff != 0))) return ChessMoves.MoveType.INVALID; ChessMoves.MoveType can_move = ChessMoves.MoveType.NORMAL; try { if (col_diff == 0) { // Figure out if you are going forward or backward int increment = (i < p.getRow())?1:-1;; for (i += increment; i != p.getRow(); i += increment) { ChessPiece piece = b.pieceAt(new ChessPosition(i, j)); if (piece != null) { can_move = ChessMoves.MoveType.INVALID; break; } } } else { // Figure out if you are going forward or backward int increment = (j < p.getCol())?1:-1;; for (j += increment; j != p.getCol(); j += increment) { ChessPiece piece = b.pieceAt(new ChessPosition(i, j)); if (piece != null) { can_move = ChessMoves.MoveType.INVALID; break; } } } // One last check to make sure that there is nothing in the landing square ChessPiece piece = b.pieceAt(new ChessPosition(p.getRow(), p.getCol())); if (piece != null) { if (piece.getColor() != this.getColor()) can_move = ChessMoves.MoveType.CAPTURE; else can_move = ChessMoves.MoveType.INVALID; } } catch (ChessException e) { can_move = ChessMoves.MoveType.INVALID; } return can_move; }
d8c99a04-5183-4554-ab1c-ba1463cdfc3c
@Override public String getShortDescription() { if (this.clr == ChessColor.COLOR_BLACK) return new String("r"); else return new String("R"); }
1bea3c2d-11c3-4c02-8aba-de478f2fdd22
@Override public String getImage() { if (this.clr == ChessColor.COLOR_BLACK) return new String("\u265C"); else return new String("\u2656"); }
ae810e6e-7735-4717-bfa8-8d240f71b44a
public King(ChessColor c) throws ChessException { super(c); int r = (c == ChessColor.COLOR_BLACK?0:7); setPosition(new ChessPosition(r, 4)); }
2f14fbb4-dc7c-493f-8e5f-5466fa260714
public King(ChessColor c, ChessPosition p) throws ChessException { super(c); setPosition(p); }
23ba92c6-48df-45d7-b1b4-970071179014
public ChessMoves nextMoves(ChessBoard b) { // Initialize moves to 0 ChessMoves moves; int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); moves = new ChessMoves(); try { for (int dy = -1; dy < 2; dy++) { for (int dx = -1; dx < 2; dx++) { int to_i = i + dy; int to_j = j + dx; if (!((dx == 0) && (dy == 0)) && (to_i >= 0) && (to_i <=7) && (to_j >= 0) && (to_j <= 7)) { ChessPosition pos = new ChessPosition(to_i, to_j); ChessPiece p = b.pieceAt(pos); if (p == null) moves.addMove(pos); else if (p.getColor() != this.getColor()) moves.addMove(pos, ChessMoves.MoveType.CAPTURE); } } } // Check the King can castle } catch (Exception e) { // Since only valid positions are created, don't worry about exceptions moves = null; } return moves; }
56fd8803-c4b6-47f8-ae5a-3a238b7ede41
@Override public ChessMoves.MoveType isValidMove(ChessBoard b, ChessPosition p) { if ((p.getCol() < 0) || (p.getCol() > 7) || (p.getRow() < 0) || (p.getRow() > 7)) return ChessMoves.MoveType.INVALID; ChessPosition cur_pos = this.getPosition(); int dx = Math.abs(cur_pos.getCol() - p.getCol()); int dy = Math.abs(cur_pos.getRow() - p.getRow()); if (((dx == 1) && (dy == 0)) || ((dx == 0) && (dy == 1)) || ((dx == 1) && (dy == 1))) { ChessPiece cp = b.pieceAt(p); if (cp == null) return ChessMoves.MoveType.NORMAL; else if (cp.getColor() != this.getColor()) return ChessMoves.MoveType.CAPTURE; else return ChessMoves.MoveType.INVALID; } else return ChessMoves.MoveType.INVALID; }
c61db496-e0b2-4e77-bfb5-f340acb6489f
@Override public String getShortDescription() { if (this.clr == ChessColor.COLOR_BLACK) return new String("k"); else return new String("K"); }
4d39650e-fc3e-423c-a134-0b5af81377d6
public String getImage() { if (this.clr == ChessColor.COLOR_BLACK) return new String("\u265A"); else return new String("\u2654"); }
baad2094-74a8-480b-a5ae-d6e10d0015dd
public Bishop(ChessColor c, int num) throws ChessException { super(c); int r = (c == ChessColor.COLOR_BLACK?0:7); if ((num != 1) && (num != 2)) throw new ChessException("Only two Bishops are allowed for each color"); if (num == 1) setPosition(new ChessPosition(r, 2)); else setPosition(new ChessPosition(r, 5)); }
a4295846-aa00-417e-aeff-d632ceb3fde4
public Bishop(ChessColor c, ChessPosition p) throws ChessException { super(c); setPosition(p); }
226e2c7a-fa41-4101-b53c-cc6fb7aca931
public ChessMoves nextMoves(ChessBoard b) { int i = this.getPosition().getRow(); int j = this.getPosition().getCol(); ChessMoves moves = new ChessMoves(); try { for (i = 1; i > -2; i -= 2) { for (j = 1; j > -2; j -= 2) { boolean good_move; int tr = this.getPosition().getRow(); int tc = this.getPosition().getCol(); do { tr = tr + i; tc = tc + j; if ((tr >= 0) && (tr <= 7) && (tc >= 0) && (tc <= 7)) { // If a piece exists in the current position // and it is of the same color, then it cannot move there // otherwise, you can move to capture, but no more moves beyond that // along that direction ChessPosition tp = new ChessPosition(tr, tc); ChessPiece p = b.pieceAt(tp); if (p == null) { moves.addMove(new ChessPosition(tr, tc)); good_move = true; } else if (p.getColor() != this.getColor()) { moves.addMove(new ChessPosition(tr, tc), ChessMoves.MoveType.CAPTURE); good_move = false; } else good_move = false; } else good_move = false; } while (good_move); } } } catch (Exception e) { // Since only valid positions are created, don't worry about exceptions moves = null; } return moves; }