From 60915d31777b9e0c80724d8528a0dc3aa7930b02 Mon Sep 17 00:00:00 2001 From: Nikhil Patil <87567207+Nikhil18Patil@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:50:58 +0530 Subject: [PATCH] Update chess.py These changes make the code more Pythonic and easier to understand while preserving the functionality of the chess program. --- chess.py | 373 ++++++++++++++++++++++++++----------------------------- 1 file changed, 179 insertions(+), 194 deletions(-) diff --git a/chess.py b/chess.py index dbb3972..7dfe79b 100644 --- a/chess.py +++ b/chess.py @@ -1,237 +1,222 @@ import itertools + WHITE = "white" BLACK = "black" +class Piece: + def __init__(self, color, name): + self.name = name + self.position = None + self.color = color + + def is_valid(self, start_pos, end_pos, color, gameboard): + if end_pos in self.available_moves(start_pos[0], start_pos[1], gameboard, color=color): + return True + return False + + def __repr__(self): + return self.name + + def __str__(self): + return self.name + + def available_moves(self, x, y, gameboard, color=None): + print("ERROR: no movement for base class") + + def ad_nauseum(self, x, y, gameboard, color, intervals): + answers = [] + for x_int, y_int in intervals: + x_temp, y_temp = x + x_int, y + y_int + while self.is_in_bounds(x_temp, y_temp): + target = gameboard.get((x_temp, y_temp), None) + if target is None: + answers.append((x_temp, y_temp)) + elif target.color != color: + answers.append((x_temp, y_temp)) + break + else: + break + x_temp, y_temp = x_temp + x_int, y_temp + y_int + return answers + + def is_in_bounds(self, x, y): + if 0 <= x < 8 and 0 <= y < 8: + return True + return False + + def no_conflict(self, gameboard, initial_color, x, y): + if self.is_in_bounds(x, y) and ((x, y) not in gameboard or gameboard[(x, y)].color != initial_color): + return True + return False +class Knight(Piece): + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + return [(xx, yy) for xx, yy in knight_list(x, y, 2, 1) if self.no_conflict(gameboard, color, xx, yy)] + +class Rook(Piece): + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + return self.ad_nauseum(x, y, gameboard, color, chess_cardinals) + + +class Bishop(Piece): + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + return self.ad_nauseum(x, y, gameboard, color, chess_diagonals) + + +class Queen(Piece): + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + return self.ad_nauseum(x, y, gameboard, color, chess_cardinals + chess_diagonals) + + +class King(Piece): + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + return [(xx, yy) for xx, yy in king_list(x, y) if self.no_conflict(gameboard, color, xx, yy)] + + +class Pawn(Piece): + def __init__(self, color, name, direction): + self.name = name + self.color = color + self.direction = direction + + def available_moves(self, x, y, gameboard, color=None): + if color is None: + color = self.color + answers = [] + if (x + 1, y + self.direction) in gameboard and self.no_conflict(gameboard, color, x + 1, y + self.direction): + answers.append((x + 1, y + self.direction)) + if (x - 1, y + self.direction) in gameboard and self.no_conflict(gameboard, color, x - 1, y + self.direction): + answers.append((x - 1, y + self.direction)) + if (x, y + self.direction) not in gameboard and color == self.color: + answers.append((x, y + self.direction)) + return answers class Game: - #ive decided since the number of pieces is capped but the type of pieces is not (pawn transformations), I've already coded much of the modularity to support just using a dictionary of pieces def __init__(self): - self.playersturn = BLACK - self.message = "this is where prompts will go" + self.players_turn = BLACK + self.message = "This is where prompts will go" self.gameboard = {} - self.placePieces() - print("chess program. enter moves in algebraic notation separated by space") + self.place_pieces() + print("Chess program. Enter moves in algebraic notation separated by space") self.main() - - def placePieces(self): - - for i in range(0,8): - self.gameboard[(i,1)] = Pawn(WHITE,uniDict[WHITE][Pawn],1) - self.gameboard[(i,6)] = Pawn(BLACK,uniDict[BLACK][Pawn],-1) - - placers = [Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook] - - for i in range(0,8): - self.gameboard[(i,0)] = placers[i](WHITE,uniDict[WHITE][placers[i]]) - self.gameboard[((7-i),7)] = placers[i](BLACK,uniDict[BLACK][placers[i]]) + def place_pieces(self): + for i in range(8): + self.gameboard[(i, 1)] = Pawn(WHITE, uni_dict[WHITE][Pawn], 1) + self.gameboard[(i, 6)] = Pawn(BLACK, uni_dict[BLACK][Pawn], -1) + + placers = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] + + for i in range(8): + self.gameboard[(i, 0)] = placers[i](WHITE, uni_dict[WHITE][placers[i]]) + self.gameboard[((7 - i), 7)] = placers[i](BLACK, uni_dict[BLACK][placers[i]]) placers.reverse() - def main(self): - while True: - self.printBoard() + self.print_board() print(self.message) self.message = "" - startpos,endpos = self.parseInput() + start_pos, end_pos = self.parse_input() try: - target = self.gameboard[startpos] - except: - self.message = "could not find piece; index probably out of range" + target = self.gameboard[start_pos] + except KeyError: + self.message = "Could not find piece; index probably out of range" target = None - + if target: - print("found "+str(target)) - if target.Color != self.playersturn: - self.message = "you aren't allowed to move that piece this turn" + print("Found " + str(target)) + if target.color != self.players_turn: + self.message = "You aren't allowed to move that piece this turn" continue - if target.isValid(startpos,endpos,target.Color,self.gameboard): - self.message = "that is a valid move" - self.gameboard[endpos] = self.gameboard[startpos] - del self.gameboard[startpos] - self.isCheck() - if self.playersturn == BLACK: - self.playersturn = WHITE - else : self.playersturn = BLACK - else : - self.message = "invalid move" + str(target.availableMoves(startpos[0],startpos[1],self.gameboard)) - print(target.availableMoves(startpos[0],startpos[1],self.gameboard)) - else : self.message = "there is no piece in that space" - - def isCheck(self): - #ascertain where the kings are, check all pieces of opposing color against those kings, then if either get hit, check if its checkmate + if target.is_valid(start_pos, end_pos, target.color, self.gameboard): + self.message = "That is a valid move" + self.gameboard[end_pos] = self.gameboard[start_pos] + del self.gameboard[start_pos] + self.is_check() + if self.players_turn == BLACK: + self.players_turn = WHITE + else: + self.players_turn = BLACK + else: + self.message = "Invalid move" + str(target.available_moves(start_pos[0], start_pos[1], self.gameboard)) + print(target.available_moves(start_pos[0], start_pos[1], self.gameboard)) + else: + self.message = "There is no piece in that space" + + def is_check(self): king = King - kingDict = {} - pieceDict = {BLACK : [], WHITE : []} - for position,piece in self.gameboard.items(): - if type(piece) == King: - kingDict[piece.Color] = position + king_dict = {} + piece_dict = {BLACK: [], WHITE: []} + for position, piece in self.gameboard.items(): + if isinstance(piece, King): + king_dict[piece.color] = position print(piece) - pieceDict[piece.Color].append((piece,position)) - #white - if self.canSeeKing(kingDict[WHITE],pieceDict[BLACK]): + piece_dict[piece.color].append((piece, position)) + if self.can_see_king(king_dict[WHITE], piece_dict[BLACK]): self.message = "White player is in check" - if self.canSeeKing(kingDict[BLACK],pieceDict[WHITE]): + if self.can_see_king(king_dict[BLACK], piece_dict[WHITE]): self.message = "Black player is in check" - - - def canSeeKing(self,kingpos,piecelist): - #checks if any pieces in piece list (which is an array of (piece,position) tuples) can see the king in kingpos - for piece,position in piecelist: - if piece.isValid(position,kingpos,piece.Color,self.gameboard): + + def can_see_king(self, king_pos, piece_list): + for piece, position in piece_list: + if piece.is_valid(position, king_pos, piece.color, self.gameboard): return True - - def parseInput(self): + + def parse_input(self): try: - a,b = input().split() - a = ((ord(a[0])-97), int(a[1])-1) - b = (ord(b[0])-97, int(b[1])-1) - print(a,b) - return (a,b) - except: - print("error decoding input. please try again") - return((-1,-1),(-1,-1)) - - """def validateInput(self, *kargs): - for arg in kargs: - if type(arg[0]) is not type(1) or type(arg[1]) is not type(1): - return False - return True""" - - def printBoard(self): + a, b = input().split() + a = ((ord(a[0]) - 97), int(a[1]) - 1) + b = (ord(b[0]) - 97, int(b[1]) - 1) + print(a, b) + return a, b + except ValueError: + print("Error decoding input. Please try again") + return ((-1, -1), (-1, -1)) + + def print_board(self): print(" 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |") - for i in range(0,8): - print("-"*32) - print(chr(i+97),end="|") - for j in range(0,8): - item = self.gameboard.get((i,j)," ") - print(str(item)+' |', end = " ") + for i in range(8): + print("-" * 32) + print(chr(i + 97), end="|") + for j in range(8): + item = self.gameboard.get((i, j), " ") + print(str(item) + ' |', end=" ") print() - print("-"*32) - - - - """game class. contains the following members and methods: - two arrays of pieces for each player - 8x8 piece array with references to these pieces - a parse function, which turns the input from the user into a list of two tuples denoting start and end points - a checkmateExists function which checks if either players are in checkmate - a checkExists function which checks if either players are in check (woah, I just got that nonsequitur) - a main loop, which takes input, runs it through the parser, asks the piece if the move is valid, and moves the piece if it is. if the move conflicts with another piece, that piece is removed. ischeck(mate) is run, and if there is a checkmate, the game prints a message as to who wins - """ + print("-" * 32) -class Piece: - - def __init__(self,color,name): - self.name = name - self.position = None - self.Color = color - def isValid(self,startpos,endpos,Color,gameboard): - if endpos in self.availableMoves(startpos[0],startpos[1],gameboard, Color = Color): - return True - return False - def __repr__(self): - return self.name - - def __str__(self): - return self.name - - def availableMoves(self,x,y,gameboard): - print("ERROR: no movement for base class") - - def AdNauseum(self,x,y,gameboard, Color, intervals): - """repeats the given interval until another piece is run into. - if that piece is not of the same color, that square is added and - then the list is returned""" - answers = [] - for xint,yint in intervals: - xtemp,ytemp = x+xint,y+yint - while self.isInBounds(xtemp,ytemp): - #print(str((xtemp,ytemp))+"is in bounds") - - target = gameboard.get((xtemp,ytemp),None) - if target is None: answers.append((xtemp,ytemp)) - elif target.Color != Color: - answers.append((xtemp,ytemp)) - break - else: - break - - xtemp,ytemp = xtemp + xint,ytemp + yint - return answers - - def isInBounds(self,x,y): - "checks if a position is on the board" - if x >= 0 and x < 8 and y >= 0 and y < 8: - return True - return False - - def noConflict(self,gameboard,initialColor,x,y): - "checks if a single position poses no conflict to the rules of chess" - if self.isInBounds(x,y) and (((x,y) not in gameboard) or gameboard[(x,y)].Color != initialColor) : return True - return False - - -chessCardinals = [(1,0),(0,1),(-1,0),(0,-1)] -chessDiagonals = [(1,1),(-1,1),(1,-1),(-1,-1)] -def knightList(x,y,int1,int2): - """sepcifically for the rook, permutes the values needed around a position for noConflict tests""" - return [(x+int1,y+int2),(x-int1,y+int2),(x+int1,y-int2),(x-int1,y-int2),(x+int2,y+int1),(x-int2,y+int1),(x+int2,y-int1),(x-int2,y-int1)] -def kingList(x,y): - return [(x+1,y),(x+1,y+1),(x+1,y-1),(x,y+1),(x,y-1),(x-1,y),(x-1,y+1),(x-1,y-1)] +chess_cardinals = [(1, 0), (0, 1), (-1, 0), (0, -1)] +chess_diagonals = [(1, 1), (-1, 1), (1, -1), (-1, -1)] +def knight_list(x, y, int1, int2): + return [(x + int1, y + int2), (x - int1, y + int2), (x + int1, y - int2), (x - int1, y - int2), + (x + int2, y + int1), (x - int2, y + int1), (x + int2, y - int1), (x - int2, y - int1)] -class Knight(Piece): - def availableMoves(self,x,y,gameboard, Color = None): - if Color is None : Color = self.Color - return [(xx,yy) for xx,yy in knightList(x,y,2,1) if self.noConflict(gameboard, Color, xx, yy)] - -class Rook(Piece): - def availableMoves(self,x,y,gameboard ,Color = None): - if Color is None : Color = self.Color - return self.AdNauseum(x, y, gameboard, Color, chessCardinals) - -class Bishop(Piece): - def availableMoves(self,x,y,gameboard, Color = None): - if Color is None : Color = self.Color - return self.AdNauseum(x, y, gameboard, Color, chessDiagonals) - -class Queen(Piece): - def availableMoves(self,x,y,gameboard, Color = None): - if Color is None : Color = self.Color - return self.AdNauseum(x, y, gameboard, Color, chessCardinals+chessDiagonals) - -class King(Piece): - def availableMoves(self,x,y,gameboard, Color = None): - if Color is None : Color = self.Color - return [(xx,yy) for xx,yy in kingList(x,y) if self.noConflict(gameboard, Color, xx, yy)] - -class Pawn(Piece): - def __init__(self,color,name,direction): - self.name = name - self.Color = color - #of course, the smallest piece is the hardest to code. direction should be either 1 or -1, should be -1 if the pawn is traveling "backwards" - self.direction = direction - def availableMoves(self,x,y,gameboard, Color = None): - if Color is None : Color = self.Color - answers = [] - if (x+1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x+1, y+self.direction) : answers.append((x+1,y+self.direction)) - if (x-1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x-1, y+self.direction) : answers.append((x-1,y+self.direction)) - if (x,y+self.direction) not in gameboard and Color == self.Color : answers.append((x,y+self.direction))# the condition after the and is to make sure the non-capturing movement (the only fucking one in the game) is not used in the calculation of checkmate - return answers -uniDict = {WHITE : {Pawn : "♙", Rook : "♖", Knight : "♘", Bishop : "♗", King : "♔", Queen : "♕" }, BLACK : {Pawn : "♟", Rook : "♜", Knight : "♞", Bishop : "♝", King : "♚", Queen : "♛" }} - +def king_list(x, y): + return [(x + 1, y), (x + 1, y + 1), (x + 1, y - 1), (x, y + 1), (x, y - 1), (x - 1, y), (x - 1, y + 1), (x - 1, y - 1)] - +uni_dict = { + WHITE: {Pawn: "♙", Rook: "♖", Knight: "♘", Bishop: "♗", King: "♔", Queen: "♕"}, + BLACK: {Pawn: "♟", Rook: "♜", Knight: "♞", Bishop: "♝", King: "♚", Queen: "♛"} +} Game() +